Machine-Learning-Day-7-8-9-10-11
2019-03-01 本文已影响5人
西出玉门东望长安
KNN-K近邻法
Day 7,8,9,10,11的任务是学习和实现KNN. 开始任务~
Knn.jpg
Step1 Data Preprocessing
首先我们import numpy, pandas, matplotlib. 使用pandas来read数据集. 使用sklearn来分配训练集和测试集. test_size为四分之一. 注意, 这里有必要的话, 我们需要使用特征缩放.
code如下:
# Step1 Data Preprocessing
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Import Datasets
dataset = pd.read_csv('../datasets/Social_Network_Ads.csv')
X = dataset.iloc[:, [2, 3]].values
Y = dataset.iloc[:, 4].values
print('X')
print(X)
print('Y')
print(Y)
# Separate TrainSets and TestSets
from sklearn.model_selection import train_test_split
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)
Step2 KNN Model
code如下:
# Step2 KNN train the Model
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors=5, metric="minkowski", p=2)
classifier.fit(X_train, Y_train)
Step3 Prediction
预测结果, 可以使用KNN的分类器来预测结果.
code如下:
# Step3 Predection
Y_pred = classifier.predict(X_test)
Step4 Evaluate the Prediction
我们预测了测试集. 现在我们将评估逻辑回归模型是否正确的学习和理解. 因此这个混淆矩阵将包含我们模型的正确和错误的预测.
code如下:
# Step4 Evaluate the Prediction
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(Y_test, Y_pred)
Step5 Visualization
可视化我们的结果.
code如下:
# Step5 Visualization
from matplotlib.colors import ListedColormap
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(('red', 'green')))
plt.xlim(X1.min(),X1.max())
plt.ylim(X2.min(),X2.max())
for i,j in enumerate(np. unique(Y_set)):
plt.scatter(X_set[Y_set==j,0],X_set[Y_set==j,1],
c = ListedColormap(('red', 'green'))(i), label=j)
plt. title(' KNN(Training set)')
plt. xlabel(' Age')
plt. ylabel(' Estimated Salary')
plt. legend()
plt. show()
X_set,Y_set=X_test,Y_test
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(('red', 'green')))
plt.xlim(X1.min(),X1.max())
plt.ylim(X2.min(),X2.max())
for i,j in enumerate(np. unique(Y_set)):
plt.scatter(X_set[Y_set==j,0],X_set[Y_set==j,1],
c = ListedColormap(('red', 'green'))(i), label=j)
plt. title(' KNN(Test set)')
plt. xlabel(' Age')
plt. ylabel(' Estimated Salary')
plt. legend()
plt. show()
Day_4_TestSet.png
Day4_TrainSet.png