这里的距离用的是欧几里得距离,也就是欧式距离
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
df = pd.read_excel('./datasets/my_films.xlsx')
#提取特征数据
feature = df[['Action Lens','Love Lens']]
#提起标签数据
target = df['target']
#数据集切分
x_train,x_test,y_train,y_test = train_test_split(feature,target,test_size=0.1,random_state=2020)
#创建算法模型对象
#n_neighbors == knn中的k
knn = KNeighborsClassifier(n_neighbors=3)
#训练模型:特征数据必须是二维的
knn.fit(x_train,y_train)
knn.predict(x_test)
print('模型分类结果:',knn.predict(x_test))
print('真实的结果:',y_test)
结果:
模型分类结果: ['Action' 'Action']
真实的结果: 2 Action
1 Action
Name: target, dtype: object
scikit-learn自带数据集合
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import sklearn.datasets as datasets
from sklearn.neighbors import KNeighborsClassifier
iris = datasets.load_iris()
feature = iris['data']
target = iris['target']
feature.shape,target.shape
x_train,x_test,y_train,y_test = train_test_split(feature,target,test_size=0.2,random_state=2020)
knn = KNeighborsClassifier(n_neighbors=8)
knn.fit(x_train,y_train)
knn.score(x_test,y_test)
print('模型分类结果:',knn.predict(x_test))
print('真实的分类结果:',y_test)
结果:
模型分类结果: [2 0 1 1 1 2 2 1 0 0 2 1 0 2 2 0 1 1 2 0 0 2 1 0 2 1 1 1 0 0]
真实的分类结果: [2 0 1 1 1 2 2 1 0 0 2 2 0 2 2 0 1 1 2 0 0 2 1 0 2 1 1 1 0 0]
import pandas as pd
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler,StandardScaler
df = pd.read_csv('./datasets/datingTestSet.txt',header=None,sep='\t')
feature = df[[0,1,2]]
target = df[3]
x_train,x_test,y_train,y_test = train_test_split(feature,target,test_size=0.2,random_state=2020)
knn = KNeighborsClassifier(n_neighbors=75)
knn.fit(x_train,y_train)
knn.score(x_test,y_test) # 0.82
#归一化
mm = MinMaxScaler()
m_feature = mm.fit_transform(feature)
x_train,x_test,y_train,y_test = train_test_split(m_feature,target,test_size=0.2,random_state=2020)
knn = KNeighborsClassifier(n_neighbors=75)
knn.fit(x_train,y_train)
knn.score(x_test,y_test) # 0.955
#标准化
s = StandardScaler()
s_feature = s.fit_transform(feature)
x_train,x_test,y_train,y_test = train_test_split(s_feature,target,test_size=0.2,random_state=2020)
knn = KNeighborsClassifier(n_neighbors=75)
knn.fit(x_train,y_train)
knn.score(x_test,y_test) # 0.96
import matplotlib.pyplot as plt
ks = np.arange(3,150,5)
scores = []
for k in ks:
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(x_train,y_train)
score = knn.score(x_test,y_test)
scores.append(score)
scores = np.array(scores)
plt.plot(ks,scores)
plt.xlabel('k')
plt.ylabel('score')
#如何具体找出分值最好的k值
max_value_index = scores.argmax() #argmax可以返回numpy数组中最大值的下标
best_k = ks[max_value_index] # 68
目的:
思想:
实现思路:
API
# k折交叉验证应用在KNN
from sklearn.model_selection import cross_val_score
feature = feature
target = target
x_train,x_test,y_train,y_test = train_test_split(feature,target,test_size=0.2,random_state=2020)
#交叉验证(作用在训练集中)
knn = KNeighborsClassifier(n_neighbors=15)
#参数1:模型对象,参数2:训练集的特征,参数3:训练集的标签,参数cv就是折数
mean_score = cross_val_score(knn,x_train,y_train,cv=10).mean() # 0.81875
ks = np.arange(3,150,5)
scores = []
for k in ks:
knn = KNeighborsClassifier(n_neighbors=k)
score = cross_val_score(knn,x_train,y_train,cv=5).mean()
scores.append(score)
plt.plot(ks,scores)
plt.xlabel('k')
plt.ylabel('score')
scores = np.array(scores)
best_k = ks[scores.argmax()]
#使用最优的超参数训练模型
knn = KNeighborsClassifier(n_neighbors=best_k)
knn.fit(x_train,y_train)
knn.score(x_test,y_test) # 0.82
knn.predict(x_test) #训练好的模型进行分类操作