# -*- coding: utf-8 -*-
'''
多元分類:邏輯迴歸分類器 並繪製pcolormesh僞彩圖
sklearn.linear_model.LogisticRegression(
solver='liblinear',
C=正則強度)
'''
# pcolormesh(x, y, c=d, cmap='jet') cmap:漸變色映射
plt.pcolormesh(...):
a = np.array([1, 2, 3])
b = np.array([-1, -2, -3, -4])
a.shape, b.shape
Out[55]: ((3,), (4,))
c = np.meshgrid(a, b); c # c is a 'list', not 'numpy.array'
Out[57]: # c[0]:沿行(axis=0)廣播, 每一行元素跟上一行相同
[array([[1, 2, 3], # c[1]:沿列(axis=1)廣播, 每一列元素跟上一列相同
[1, 2, 3], # (c[0],c[1])組成的座標點(x,y)將覆蓋並形成(1<=x<=3,-4<=y<=-1)區間組成的2*3的矩形
[1, 2, 3],
[1, 2, 3]]),
array([[-1, -1, -1],
[-2, -2, -2],
[-3, -3, -3],
[-4, -4, -4]])]
c[0].shape, c[1].shape
Out[61]: ((4, 3), (4, 3))
plt.pcolormesh(c[0], c[1], c=...) # c[0]表示點橫座標,c[1]表示縱座標
對樣本(c[0], c[1])周圍(包括樣本所在座標)的四個座標點進行着色,C代表着色方案
# 點(c[0], c[1])所有座標點如下:
'''
^
|---1------2------3---->
|
-1 (1,-1) (2,-1) (3,-1)
|
-2 (1,-2) (2,-2) (3,-2)
|
-3 (1,-3) (2,-3) (3,-3)
|
-4 (1,-4) (2,-4) (3,-4)
|
'''
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 31 16:12:18 2018
@author: Administrator
"""
'''
多元分類:邏輯迴歸分類器
sklearn.linear_model.LogisticRegression(
solver='liblinear',
C=正則強度)
'''
import numpy as np
import matplotlib.pyplot as plt
import sklearn.linear_model as lm
# train_set
x = np.array([
[4, 7],
[3.5, 8],
[3.1, 6.2],
[0.5, 1],
[1, 2],
[1.2, 1.9],
[4, 2],
[5.7, 1.5],
[5.4, 2.2]]) # 散點[x,y]
y = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2]) # 多元分類 3類
# 邏輯迴歸分類器
model = lm.LogisticRegression(solver='liblinear', C=50) # C
model.fit(x, y)
plt.figure('Logistic Classification', facecolor='lightgray')
plt.title('Logistic Classification', fontsize=14)
plt.xlabel('x', fontsize=14)
plt.ylabel('y', fontsize=14)
plt.tick_params(labelsize=10)
'''
pcolormesh參數設置:
'''
l, r, h = x[:, 0].min() - 1, x[:, 0].max() + 1, 0.005 # 左邊界,右邊界,水平方向點間距
b, t, v = x[:, 1].min() - 1, x[:, 1].max() + 1, 0.005 # 下邊界,上邊界,垂直方向點間距
#print(np.arange(l, r, h).shape, np.arange(b, t, v).shape) # (1440,) (1800,),shape不同,不能直接作爲輸入,轉爲
grid_x = np.meshgrid(np.arange(l, r, h), np.arange(b, t, v)) # (m-array,n-array)--> list(mat(m,n), mat(m,n))
print(grid_x[0]) # x[i, j] (1800, 1440) <class 'numpy.ndarray'>
print(grid_x[1]) # y[i, j] (1800, 1440) <class 'numpy.ndarray'>
#print(grid_x[1].shape) # (1800, 1440) <class 'numpy.ndarray'>
flat_x = np.c_[grid_x[0].ravel(), grid_x[1].ravel()] # 保證輸入散點的座標點橫縱座標個數一樣
flat_y = model.predict(flat_x) # 輸入柵格點陣座標,模型預測輸出的分類
grid_y = flat_y.reshape(grid_x[0].shape) # 分類標籤:用做pcolormesh柵格着色的依據
print(grid_y)
#[[1 1 1 ... 2 2 2] # 0, 1, 2 分別代表三種不同顏色
# [1 1 1 ... 2 2 2]
# [1 1 1 ... 2 2 2]
# ...
# [0 0 0 ... 0 0 0]
# [0 0 0 ... 0 0 0]
# [0 0 0 ... 0 0 0]]
# pcolormesh: 僞彩圖 pcolormesh(X, Y, C)
# X,Y均爲2-D array,如果爲1-D 會自動廣播,X和Y構成網格點陣
# X,Y對應位置元素x[i,j]和y[i,j]組成一個座標點(x[i,j],y[i,j]),對樣本週圍(包括樣本所在座標)的四
#個座標點進行着色,C代表着色方案
plt.pcolormesh(grid_x[0], grid_x[1], grid_y, cmap='gray') # gray_r 與gray的色帶相反
plt.scatter(x[:, 0], x[:, 1], c=y, cmap='brg', s=60) # 顏色映射