1. 程式人生 > >sklearn機器學習之邏輯迴歸分類器

sklearn機器學習之邏輯迴歸分類器

物以類聚,人以群分。

是非黑白,金木水火。

乾坤陰陽,寒暑燥溼。

 

 

import numpy as np
import matplotlib.pyplot as plt
from sklearn import linear_model


#訓練資料(此處示例是二維平面上的座標點和各個點對應的類別)    
X = np.array([[3.1, 7.2], [4, 6.7], [2.9, 8], [5.1, 4.5], [6, 5],[5.6, 5], [3.3, 0.4], [3.9, 0.9], [2.8, 1], [0.5, 3.4], [1, 4],[0.6, 4.9]])
y = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3])

#解析模型選用線性模型的邏輯迴歸
classifier = linear_model.LogisticRegression(solver='liblinear',C=100)

#用分類模型和資料進行訓練
classifier.fit(X, y)

#計算邊界(在原資料座標範圍外擴1個單位)
min_x, max_x = X[:, 0].min() - 1.0, X[:, 0].max() + 1.0
min_y, max_y = X[:, 1].min() - 1.0, X[:, 1].max() + 1.0

#繪製網格步長
mesh_step_size = 0.01

#生成網格座標數列
x_vals, y_vals = np.meshgrid(np.arange(min_x, max_x,mesh_step_size), np.arange(min_y, max_y, mesh_step_size))


#★★★★★使用之前用資料訓練好的分類器預測網格座標所屬類別
#實際上可以簡單理解為輸入座標點X',輸出座標點所屬類別y'
#背後的分類演算法sklearn已經做好,此處只是呼叫,無需自己從零開始實現
output = classifier.predict(np.c_[x_vals.ravel(),y_vals.ravel()])

#網格重新造型
output = output.reshape(y_vals.shape)

#視覺化繪製網格圖形
plt.figure()

#plt.pcolormesh(x_vals, y_vals, output, cmap=plt.cm.gray)
plt.pcolormesh(x_vals, y_vals, output, cmap=plt.cm.Spectral)


plt.scatter(X[:, 0], X[:, 1], c=y, s=200, edgecolors='red',linewidth=1)


plt.xlim(x_vals.min(), x_vals.max())
plt.ylim(y_vals.min(), y_vals.max())

plt.xticks((np.arange(int(X[:, 0].min() - 1), int(X[:, 0].max() + 1), 1.0)))
plt.yticks((np.arange(int(X[:, 1].min() - 1), int(X[:, 1].max() + 1), 1.0)))

plt.show()