以前得出邏輯迴歸的損失函數:
\[ J(\theta) = -\frac{1}{m}\sum_{i=1}^{m}y^{(i)}log(\sigma (X _b^{(i)} \cdot \theta))+(1-y^{(i)})log(1-\sigma (X_b^{(i)} \cdot \theta)) \]算法
此方程沒有數學解析解,只能使用梯度降低法的方法來找到最佳的$ \theta $值,使得損失函數最小。
梯度降低法的表達式(推導過程在這裏不進行闡述):
\[ \frac{J(\theta)}{\theta_j} = \frac{1}{m}\sum_{i=1}^{m}(\sigma (X_b^{(i)} \cdot \theta)-y^{(i)})X_j^{(i)} \]函數
比較線性迴歸的梯度表達式及向量化後的表達式:
\[ \frac{J(\theta)}{\theta_j} = \frac{2}{m}\sum_{i=1}^{m}(X_b^{(i)} \cdot \theta-y^{(i)})X_j^{(i)} \]
\[ \Lambda J = \frac{2}{m}(X_b\theta -y)^T\cdot X_b = \frac{2}{m}X_b^T \cdot (X_b\theta -y) \]
不可貴出邏輯迴歸向量化後的梯度表達式:
\[ \Lambda J = \frac{1}{m}X_b^T \cdot (\sigma (X_b\theta) -y) \]spa
加載鳶尾花數據集code
import numpy from sklearn import datasets from mylib import LogisticRegression from matplotlib import pyplot iris = datasets.load_iris() X = iris.data y = iris.target # 取y值爲0和1的數據,爲了數據可視化,特徵只取兩個 X = X[y<2,:2] y = y[y<2]
繪製數據集blog
pyplot.scatter(X[y==0,0],X[y==0,1],color='red') pyplot.scatter(X[y==1,0],X[y==1,1],color='blue') pyplot.show()
用封裝好的邏輯迴歸,查看準確率:get
from mylib.model_selection import train_test_split x_train,x_test,y_train,y_test = train_test_split(X,y,seed =666) logic_reg = LogisticRegression.LogisticRegression() logic_reg.fit(x_train,y_train) logic_reg.score(x_test,y_test)
能夠看出,預測準確率100%數學