機器學習--手寫數字識別(KNN、決策樹)
阿新 • • 發佈:2019-01-13
KNN 及決策樹演算法為監督學習中的兩種簡單演算法。
KNN
KNN演算法(鄰近演算法)的核心思想是如果一個樣本在特徵空間中的k個最相鄰的樣本中的大多數屬於某一個類別,則該樣本也屬於這個類別,並具有這個類別上樣本的特性。
歐式距離的計算公式:
假設每個樣本有兩個特徵值,如 A :(a1,b1)B:(a2,b2) 則AB的歐式距離為
例如:根據消費分配來預測性格
已知張三美食消費為110、衣服消費為190、文具消費為30,張三的性格為活潑。…
根據前3個樣本我們算出歐式距離
…
尋找d的最近鄰居為143和153,推測出劉二的性格為活潑
決策樹
決策樹是一種樹形結構,其中每個內部節點表示一個屬性上的測試,每個分支代表一個測試輸出,每個葉節點代表一種類別。
每個決策樹都表述了一種樹型結構,它由它的分支來對該型別的物件依靠屬性進行分類。每個決策樹可以依靠對源資料庫的分割進行資料測試。這個過程可以遞迴式的對樹進行修剪。 當不能再進行分割或一個單獨的類可以被應用於某一分支時,遞迴過程就完成了。
例項
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.linear_model import LogisticRegression
from IPython.display import display
X = []
y = []
for i in range(0,10):
for j in range(1,701):
digit = plt.imread('./database/%d/1 (%d).bmp'%(i,j))
X.append(digit)
y.append(i)
X = np.array(X)
y = np.array(y)
X.shape
index = np.random.randint(0,7000,size=1)[0]
digit = X[index]
plt.figure(figsize=(1,1))
plt.imshow(digit,cmap='gray')
print("true:%d"%(y[index]))
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.1)
X_train.shape
knn = KNeighborsClassifier(n_neighbors=5)
knn.fit(X_train.reshape([6300,28*28]),y_train)
knn.score(X_test.reshape([-1,28*28]),y_test)
y_ = knn.predict(X_test.reshape([-1,28*28]))
display(y_[:20],y_test[:20])
X.reshape(7000,-1).shape
#KNN演算法實現預測
plt.figure(figsize=(10*1,10*1.5))
for i in range(100):
axes = plt.subplot(10,10,i+1)
axes.imshow(X_test[i],cmap='gray')
t = y_test[i]
p = y_[i]
axes.set_title('True:%d\nPred:%d'%(t,p))
axes.axis('off')
#決策樹實現預測
##深度為50
plt.figure(figsize=(10*1,10*1.5))
for i in range(100):
axes = plt.subplot(10,10,i+1)
axes.imshow(X_test[i],cmap='gray')
t = y_test[i]
p = y_[i]
axes.set_title('True:%d\nPred:%d'%(t,p))
axes.axis('off')
tree = DecisionTreeClassifier(max_depth=50)
tree.fit(X_train.reshape(6300,-1),y_train)
y_ = tree.predict(X_test.reshape([-1,28*28]))
tree.score(X_test.reshape([-1,28*28]),y_test)
##深度為150
plt.figure(figsize=(10*1,10*1.5))
for i in range(100):
axes = plt.subplot(10,10,i+1)
axes.imshow(X_test[i],cmap='gray')
t = y_test[i]
p = y_[i]
axes.set_title('True:%d\nPred:%d'%(t,p))
axes.axis('off')
tree = DecisionTreeClassifier(max_depth=150)
tree.fit(X_train.reshape(6300,-1),y_train)
y_ = tree.predict(X_test.reshape([-1,28*28]))
tree.score(X_test.reshape([-1,28*28]),y_test)