使用 sklearn 构建机器学习算法模型的完整流程

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier


# 导入鸢尾花数据集
iris_dataset = load_iris()

# 切分训练数据和测试数据
X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_state=42)

# 实例化 KNeighborsClassifier 类对象
knn = KNeighborsClassifier(n_neighbors=1)

# 构建模型(通过训练特征数据和训练标签数据进行拟合)
knn.fit(X_train, y_train)

# 模型评估
precision = knn.score(X_test, y_test)
print('精度得分:\n', precision)

# 新数据点
X_new = [[5, 2.9, 1, 0.2]]

# 模型预测
y_pred = knn.predict(X_new)
print('预测结果:\n', y_pred)
---------
精度得分:
 1.0
预测结果:
 [0]

你可能感兴趣的:(机器学习,机器学习,sklearn,算法)