knn算法分類時,分類器的性能也會受到多種因素的影響,如分類器設置和數據集等。不同的算法在不同數據集上的表現可能完全不同。
import numpy as np
import matplotlib.pyplot as plt
def init():
#四組數據 兩個參數表示武打鏡頭次數以及親吻鏡頭次數
group = np.array([[1,101],[5,89],[108,5],[115,8]])
#四組數據的標籤 類型
labels = ['愛情片','愛情片','動作片','動作片']
return group,labels
def draw(X):
group,label = init()
#print(group[:,0],group[:,1])
plt.scatter(group[:,0],group[:,1])
plt.scatter(X[0],X[1])
plt.show()
def solve(group,k,labels,input):
x = group.shape[0]#行數
new_array = np.tile(input,(x,1))#線性代數矩陣思維
# tile函數的作用 重複n行m列
# 1 2 3
# (2,3)
# 1 2 3 1 2 3 1 2 3
# 1 2 3 1 2 3 1 2 3
new_array -= group
new_array **= 2
new_array = np.sum(new_array,axis = 1)#每行相加獲得的是行向量 axi=0 每列求和
diatance = new_array**0.5 #距離列表
#對距離進行排序
sorted_distance = np.argsort(diatance) #小到大排序返回下標的列表
map = {}#裝k個
for i in range(k):
#sorted_distance labels k
#3 A 0
#1 A 1
#0 B 2
string = labels[sorted_distance[i]]
map[string] = map.get(string,0)+1#用字典模擬c++中map的作用
cnt = 0
for key,value in map.items():#找出出現次數最多的string
if value > cnt:
cnt = value
res_string = key
return res_string
if __name__=='__main__':
x = int(input())
y = int(input())
group,labels = init()
draw((x,y))
res = solve(group,2,labels,np.array([x,y]))
print('經過預測結果是',res)