上机题:调试运行讲解的示例题,并发挥自己的创意,改写相应程序。
#py601.py Scikit-learn 机器学习步骤 示例
# 导入 sklearn
from sklearn import neighbors, datasets, preprocessing
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
print('=========== 机器学习步骤 示例 =========')
# 加载数据
print('------加载数据-----------')
iris = datasets.load_iris()
print(iris)
# 划分训练集与测试集
print('-----划分训练集与测试集-------------')
X, y = iris.data[:, :2], iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=33)
print(X,y)
print(X_train, X_test, y_train, y_test)
# 数据预处理
print('-----数据预处理-------------')
scaler = preprocessing.StandardScaler().fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
print(scaler)
print(X_train)
print(X_test)
# 创建模型
print('----- 创建模型-------------')
knn = neighbors.KNeighborsClassifier(n_neighbors=5)
print(knn)
# 模型拟合
print('----模型拟合--------------')
knn.fit(X_train, y_train)
print(knn.fit)
# 预测
print('-----预测-------------')
y_pred = knn.predict(X_test)
print(y_pred)
# 评估
print('------评估------------')
accuracy_score(y_test, y_pred)
print(accuracy_score(y_test, y_pred))
上机实训参考资源包: