机器学习五步:
- 加载数据集
- 分割数据集
- 建立模型
- 训练模型
- 预测模型
导入库文件
import numpy as np #科学计算库
import matplotlib.pyplot as plt #绘图库可视化函数
import pandas as pd #数据处理库,数据分析库
import seaborn as sns #高级数据可视化库
from sklearn.model_selection import train_test_split #数据分割库
一:加载数据集
fruis_df = pd.read_table("/home/aistudio/data/fruit_data_with_colors.txt")
print(fruis_df.head(3))
注:
wget https://raw.githubusercontent.com/susanli2016/Machine-Learning-with-Python/master/fruit_data_with_colors.txt
获取数据集中的特征名称
fruis_name_dict = dict(zip(fruis_df["fruit_label"], fruis_df["fruit_name"]))
print("___________")
print(fruis_name_dict)
获取数据集中的特征名称
X = fruis_df[["mass", "width", "height", "color_score"]]
y = fruis_df["fruit_label"]
二:分割数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/4, random_state=0)
print("数据集总共:{}, 训练集:{}, 测试集合:{}".format(len(X), len(X_train), len(X_test)))
绘制散点图
sns.pairplot(data = fruis_df, hue="fruit_name", vars=["mass","width","height","color_score"])
运行结果
fruit_label fruit_name fruit_subtype mass width height color_score
0 1 apple granny_smith 192 8.4 7.3 0.55
1 1 apple granny_smith 180 8.0 6.8 0.59
2 1 apple granny_smith 176 7.4 7.2 0.60
___________
{1: 'apple', 2: 'mandarin', 3: 'orange', 4: 'lemon'}
数据集总共:59, 训练集:44, 测试集合:15
三:建立模型
from sklearn.neighbors import KNeighborsClassifier #KNN分类器的算法库
knn = KNeighborsClassifier(n_neighbors=5)
四:训练模型
knn.fit(X_train, y_train)
五:预测模型
y_pred = knn.predict(X_test)
print(y_pred)
from sklearn.metrics import accuracy_score #准确率
accuracy_score(y_test, y_pred) # y_test:实际值,y_pred:预测值
输出
[3 1 4 4 1 1 3 3 1 4 2 1 3 1 4]
0.5333333333333333
可视化模型
k_range = range(1, 20) # k = 1~19
acc_scores = [] # 存储每个 k 值对应的准确率
for k in k_range:
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(X_train, y_train)
acc_scores.append(knn.score(X_test, y_test))
plt.figure()
plt.xlabel(“K”) # X轴标签
plt.ylabel(“Accuracy”) # Y轴标签
plt.scatter(k_range, acc_scores)
plt.xticks([0, 5, 10, 15, 20])
plt.show()