天天看點

邏輯回歸 單特征 多特征 Softmax多特征多分類

邏輯回歸

  • 估計機率公式
    邏輯回歸 單特征 多特征 Softmax多特征多分類
  • 邏輯函數(數值->邏輯值)
    邏輯回歸 單特征 多特征 Softmax多特征多分類
  • 邏輯回歸模型預測
    邏輯回歸 單特征 多特征 Softmax多特征多分類
    邏輯回歸 單特征 多特征 Softmax多特征多分類
當機率越靠近1,則-log(t) 越靠近0,當p越靠近0,-log(t)則越大
邏輯回歸 單特征 多特征 Softmax多特征多分類
  • 邏輯回歸成本函數(對數損失)
    邏輯回歸 單特征 多特征 Softmax多特征多分類
    偏導
    邏輯回歸 單特征 多特征 Softmax多特征多分類
from sklearn import datasets
import numpy as np
import matplotlib.pyplot as plt
      

單特征

iris = datasets.load_iris()
print(iris["data"][0])
X=iris["data"][:,3:] #petal width 花瓣寬度,選擇每行的第四個(每行共四個)
#[:,3:] 前面選擇行範圍  後面選擇列範圍
print(X[0])
y=(iris["target"]==2).astype(np.int)#标簽,數組元素為2則元素為1,否則為0

#訓練一個邏輯回歸模型
from sklearn.linear_model import LogisticRegression
log_reg=LogisticRegression()#建立執行個體
log_reg.fit(X,y)


X_new = np.linspace(0, 3, 1000).reshape(-1, 1)#生成0 - 3 的等差數列,數列有1000個元素

y_proba = log_reg.predict_proba(X_new)#得出預測機率數組
plt.plot(X_new, y_proba[:, 1], "g-", label="Iris virginica")#是的機率
plt.plot(X_new, y_proba[:, 0], "b--", label="Not Iris virginica")#不是的機率

#使用模型進行預測
print( "predict:",log_reg.predict([[1.7], [1.5]]))
plt.show()
      
邏輯回歸 單特征 多特征 Softmax多特征多分類

多特征(二分類)

#使用花兩個資料,花的長度與寬度
X = iris["data"][:, (2, 3)] 
y = (iris["target"] == 2).astype(np.int)
log_reg = LogisticRegression(solver="lbfgs", C=10**10, random_state=42)
#控制Scikit-Learn LogisticRegression模型的正則化強度的超參數不是alpha(與其他
#線性模型一樣),而是反值C。C值越高,對模型的正則化越少。
log_reg.fit(X, y)
#生成随機測試集
x0, x1 = np.meshgrid(
np.linspace(2.9, 7, 500).reshape(-1, 1),#長度
np.linspace(0.8, 2.7, 200).reshape(-1, 1),#寬度
)
#.ravel多元數組轉一維
X_new = np.c_[x0.ravel(), x1.ravel()]
y_proba = log_reg.predict(X)
print(y_proba)
      

Softmax回歸(多特征多分類)

X = iris["data"][:, (2, 3)]  # 兩種特征長度寬度
y = iris["target"] 

softmax_reg = LogisticRegression(multi_class="multinomial",solver="lbfgs", C=10, random_state=42)
softmax_reg.fit(X, y)

x0, x1 = np.meshgrid(
np.linspace(0, 8, 500).reshape(-1, 1),
np.linspace(0, 3.5, 200).reshape(-1, 1),
    )
X_new = np.c_[x0.ravel(), x1.ravel()]


y_proba = softmax_reg.predict_proba(X_new)
print(y_proba)
y_predict = softmax_reg.predict(X_new)
print(y_predict)


#下面為畫圖
'''
zz1 = y_proba[:, 1].reshape(x0.shape)
zz = y_predict.reshape(x0.shape)

plt.figure(figsize=(10, 4))
plt.plot(X[y==2, 0], X[y==2, 1], "g^", label="Iris virginica")
plt.plot(X[y==1, 0], X[y==1, 1], "bs", label="Iris versicolor")
plt.plot(X[y==0, 0], X[y==0, 1], "yo", label="Iris setosa")

from matplotlib.colors import ListedColormap
custom_cmap = ListedColormap(['#fafab0','#9898ff','#a0faa0'])

plt.contourf(x0, x1, zz, cmap=custom_cmap)
contour = plt.contour(x0, x1, zz1, cmap=plt.cm.brg)
plt.clabel(contour, inline=1, fontsize=12)
plt.xlabel("Petal length", fontsize=14)
plt.ylabel("Petal width", fontsize=14)
plt.legend(loc="center left", fontsize=14)
plt.axis([0, 7, 0, 3.5])
plt.show()'''

      

繼續閱讀