RT
#调用库
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors, datasets
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import confusion_matrix
#数据集加载
dataset = datasets.load_iris()
X = dataset.data[:, :2]
y = dataset.target
attributes_dict = {0:"sepal_length",1:"sepal_width"}
for attribute in attributes_dict:
max_value = np.max(X[:, attribute])
min_value = np.min(X[:, attribute])
mean_value = np.mean(X[:, attribute])
print("{} 最大值:{}".format(attributes_dict[attribute], max_value))
print("{} 最小值:{}".format(attributes_dict[attribute], min_value))
print("{} 平均值:{:.1f}".format(attributes_dict[attribute], mean_value))
print("-------------------------------------")
#数据集划分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)
#训练KNN
classifier = KNeighborsClassifier(n_neighbors = 5, p = 2)
classifier.fit(X_train, y_train)
y_pred = classifier.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
print('cm',cm)
#训练可视化
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
alpha = 0.75, cmap = ListedColormap(('wheat', 'yellow', 'c')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
color_list = [[[1,0,0],[0,1,0],[1,1,1]][i]]
count = np.sum((y_set == j)==True)
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = color_list*count, label = j)
plt.legend()
plt.show()
plt.savefig('/data/workspace/myshixun/step1/reality/pic')