【Python机器学习基础教程】第一张引言知识总结及代码总结

【Python机器学习基础教程】第一张引言知识总结及代码总结_第1张图片
第一个实例:鸢尾花分类

#鸢尾花分类
import numpy as np
import pandas as pd
import mglearn

from sklearn.datasets import load_iris
#加载数据
iris_datasets = load_iris()
print('keys of iris_datasets:\n{}'.format(iris_datasets.keys()))
#划分数据
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(iris_datasets['data'],iris_datasets['target'],random_state=0)
#观察数据
iris_dataframe = pd.DataFrame(X_train,columns=iris_datasets.feature_names)

grr = pd.plotting.scatter_matrix(iris_dataframe,alpha=.8,figsize=(15,15),diagonal='hist',
                                marker='o',hist_kwds={'bins':20},s=60,c=y_train,cmap=mglearn.cm3)
#构建模型
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train,y_train)
#做出预测
X_new = np.array([[5,2.9,1,0.2]])
prediction = knn.predict(X_new)
#评估模型
y_pred = knn.predict(X_test)
print('Test set score:{:.2f}'.format(np.mean(y_pred == y_test)))
print('Test set score:{:.2f}'.format(knn.score(X_test,y_test)))

你可能感兴趣的:(python,机器学习,开发语言)