文章目录
一、什么是逻辑回归
当不需要通过计算出来的概率值
p
^
\hat{p}
p^来进行分类的话就是回归算法,如果需要进行分类的话就是分类算法
Sigmoid函数
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(t):
return 1/ (1 + np.exp(-t))
x = np.linspace(-10,10,500)
y = sigmoid(x)
plt.plot(x,y)
plt.show()
输出结果:
二、逻辑回归的损失函数
简化成:
考虑到有m个样本,所以逻辑回归的损失函数为:
将
p
^
(
i
)
\hat{p}^{(i)}
p^(i)代入以后得到:
我们真正的未知数是
θ
\theta
θ,下面我们要做的是找到一组
θ
\theta
θ,使得我们的
J
(
θ
)
J(\theta)
J(θ)达到一个最小值。
对于
J
(
θ
)
J(\theta)
J(θ),没有公式解,只能使用梯度下降法求解,该损失函数是一个凸函数,没有局部最优解,只有一个全局最优解。
三、逻辑回归损失函数的梯度
对log(1-\sigma (t))求导,并化简
−
1
1
−
σ
(
t
)
-\frac{1}{1-\sigma (t)}
−1−σ(t)1得到:
将
−
1
1
−
σ
(
t
)
-\frac{1}{1-\sigma (t)}
−1−σ(t)1的值代入
(
l
o
g
(
1
−
σ
(
t
)
)
)
′
(log(1-\sigma (t)))^{'}
(log(1−σ(t)))′中,得到:
得到:
J
(
θ
)
J(\theta)
J(θ)对应的梯度:
回忆线性回归的梯度:
得到逻辑回归对应的梯度:
四、实现逻辑回归算法
import numpy as np
from .metrics import accuracy_score
class LogisticRegression:
def __init__(self):
"""初始化Logistic Regression模型"""
self.coef_ = None
self.intercept_ = None
self._theta = None
def _sigmoid(selfself,t):
return 1. / (1. + np.exp(-t))
def fit(self, X_train, y_train, eta=0.01, n_iters=1e4):
"""根据训练数据集X_train, y_train, 使用梯度下降法训练Logistic Regression模型"""
assert X_train.shape[0] == y_train.shape[0], \
"the size of X_train must be equal to the size of y_train"
def J(theta, X_b, y):
y_hat = self._sigmoid(X_b.dot(theta))
try:
return -np.sum(y * np.log(y_hat) + (1 - y)*np.log(1-y_hat)) / len(y)
except:
return float('inf')
def dJ(theta, X_b, y):
return X_b.T.dot(self._sigmoid(X_b.dot(theta)) - y) / len(X_b)
def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1e-8):
theta = initial_theta
cur_iter = 0
while cur_iter < n_iters:
gradient = dJ(theta, X_b, y)
last_theta = theta
theta = theta - eta * gradient
if (abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon):
break
cur_iter += 1
return theta
X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
initial_theta = np.zeros(X_b.shape[1])
self._theta = gradient_descent(X_b, y_train, initial_theta, eta, n_iters)
self.intercept_ = self._theta[0]
self.coef_ = self._theta[1:]
return self
def predict_proba(self, X_predict):
"""给定待预测数据集X_predict,返回表示X_predict的结果概率向量"""
assert self.intercept_ is not None and self.coef_ is not None, \
"must fit before predict!"
assert X_predict.shape[1] == len(self.coef_), \
"the feature number of X_predict must be equal to X_train"
X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])
return self._sigmoid(X_b.dot(self._theta))
def predict(self, X_predict):
"""给定待预测数据集X_predict,返回表示X_predict的结果向量"""
assert self.intercept_ is not None and self.coef_ is not None, \
"must fit before predict!"
assert X_predict.shape[1] == len(self.coef_), \
"the feature number of X_predict must be equal to X_train"
proba = self.predict_proba(X_predict)
return np.array(proba >= 0.5,dtype='int')
def score(self, X_test, y_test):
"""根据测试数据集 X_test 和 y_test 确定当前模型的准确度"""
y_predict = self.predict(X_test)
return accuracy_score(y_test, y_predict)
def __repr__(self):
return "LogisticRegression()"
下面我们以鸢尾花数据集为例实现逻辑回归算法,以下是notebook中的内容:
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data
y = iris.target
X = X[y<2,:2]
y = y[y<2]
X.shape
输出:(100, 2)
y.shape
输出:(100,)
plt.scatter(X[y==0,0],X[y==0,1],color='red')
plt.scatter(X[y==1,0],X[y==1,1],color='blue')
plt.show()
输出图片:
使用逻辑回归
from playML.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,seed=666)
from playML.LogisticRegression import LogisticRegression
log_reg = LogisticRegression()
log_reg.fit(X_train,y_train)
输出:LogisticRegression()
log_reg.score(X_test,y_test)#对已有的测试数据全都进行了正确的分类
输出:1.0
log_reg.predict_proba(X_test)#和下面的y_test一一对应
输出:array([0.92972035, 0.98664939, 0.14852024, 0.01685947, 0.0369836 ,
0.0186637 , 0.04936918, 0.99669244, 0.97993941, 0.74524655,
0.04473194, 0.00339285, 0.26131273, 0.0369836 , 0.84192923,
0.79892262, 0.82890209, 0.32358166, 0.06535323, 0.20735334])
y_test
输出:array([1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0])
log_reg.predict(X_test)
输出:array([1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0])
五、决策边界
分析:
在二维坐标系中
x
1
x_{1}
x1代表横轴方向,
x
2
x_{2}
x2代表纵轴方向
在上文逻辑回归的基础上,我们可以得到方程的参数(
θ
1
\theta_{1}
θ1、
θ
2
\theta_{2}
θ2)以及截距(
θ
0
\theta_{0}
θ0):
log_reg.coef_
输出:array([ 3.01796521, -5.04447145])
log_reg.intercept_
输出:-0.6937719272911228
我们可以利用所得到的的值生成一条直线,也可以成为边界:
def x2(x1):
return (-log_reg.coef_[0] * x1 - log_reg.intercept_) / log_reg.coef_[1]
x1_plot = np.linspace(4,8,1000)
x2_plot = x2(x1_plot)
plt.scatter(X[y==0,0],X[y==0,1],color='red')
plt.scatter(X[y==1,0],X[y==1,1],color='blue')
plt.plot(x1_plot,x2_plot)
plt.show()
输出图片:
x
T
⋅
x
b
x^{T}\cdot x _{b}
xT⋅xb > 0时,样本位于直线右侧,反之位于直线左侧,当x^{T}\cdot x _{b} = 0时样本可位于决策边界上。
不规则决策边界的绘制方法:对于平面中每一个点都用得到的模型判断该点分为哪一类,然后将不同的颜色绘制出来,就可以得到决策边界。
下面我们用该种方式绘制逻辑回归的决策边界:
逻辑回归的决策边界
def plot_decision_boundary(model, axis):
x0, x1 = np.meshgrid(
np.linspace(axis[0], axis[1], int((axis[1]-axis[0])*100)).reshape(-1,1),
np.linspace(axis[2], axis[3], int((axis[3]-axis[2])*100)).reshape(-1,1)
)
X_new = np.c_[x0.ravel(), x1.ravel()]
y_predict = model.predict(X_new)
zz = y_predict.reshape(x0.shape)
from matplotlib.colors import ListedColormap
custom_cmap = ListedColormap(['#EF9A9A', '#FFF59D','#90CAF9'])
plt.contourf(x0, x1, zz, linewidth=5, cmap=custom_cmap)
plot_decision_boundary(log_reg, axis=[4, 7.5, 1.5, 4.5])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()
kNN的决策边界
from sklearn.neighbors import KNeighborsClassifier
knn_clf = KNeighborsClassifier()
knn_clf.fit(X_train,y_train)
输出:KNeighborsClassifier()
knn_clf.score(X_test,y_test)
输出:1.0
plot_decision_boundary(knn_clf, axis=[4, 7.5, 1.5, 4.5])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()
输出图片:
kNN算法支持多个分类,如果我们将kNN算法作用在三个类别的话:
k=5(默认值)时:
knn_clf_all = KNeighborsClassifier()
knn_clf_all.fit(iris.data[:,:2],iris.target)
plot_decision_boundary(knn_clf_all, axis=[4, 8, 1.5, 4.5])
plt.scatter(iris.data[iris.target==0,0],iris.data[iris.target==0,1])
plt.scatter(iris.data[iris.target==1,0],iris.data[iris.target==1,1])
plt.scatter(iris.data[iris.target==2,0],iris.data[iris.target==2,1])
plt.show()
输出图片:
k=50时:
knn_clf_all = KNeighborsClassifier(n_neighbors=50)#n_neighbors默认值为5,该值越大则模型越简单,决策边界越规整,分类越明显
knn_clf_all.fit(iris.data[:,:2],iris.target)
plot_decision_boundary(knn_clf_all, axis=[4, 8, 1.5, 4.5])
plt.scatter(iris.data[iris.target==0,0],iris.data[iris.target==0,1])
plt.scatter(iris.data[iris.target==1,0],iris.data[iris.target==1,1])
plt.scatter(iris.data[iris.target==2,0],iris.data[iris.target==2,1])
plt.show()
输出图片:
kNN分类算法中的k值越大则模型越简单,决策边界越规整,分类越明显。
六、在逻辑回归中使用多项式特征
为什么说逻辑回归稚嫩狗狗解决二分类问题,因为我们得到的决策边界对应的直线只能够将平面分成两部分。显然,直线的分类方式太简单了,有的样本点是非线性的分布,并不能只使用直线来将它们进行分类。比如说:
那我们能不能让逻辑回归学习到这样的决策边界呢?
我们可以将
x
2
x^{2}
x2看做一个特征,换句话说我们可以将线性回归转化成多项式回归,同理为我们的逻辑回归算法添加多项式项,我们就可以对非线性的数据进行比较好的分类, 得到的决策边界也可以是一个曲线的形状。
逻辑回归中添加多项式特征
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(666)
X = np.random.normal(0,1,size=(200,2))
y = np.array(X[:,0]**2 +X[:,1] **2 < 1.5,dtype='int')
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()
输出图片:
使用逻辑回归
from playML.LogisticRegression import LogisticRegression
log_reg = LogisticRegression()
log_reg.fit(X,y)
log_reg.score(X,y)
输出:0.605
def plot_decision_boundary(model, axis):
x0, x1 = np.meshgrid(
np.linspace(axis[0], axis[1], int((axis[1]-axis[0])*100)).reshape(-1,1),
np.linspace(axis[2], axis[3], int((axis[3]-axis[2])*100)).reshape(-1,1)
)
X_new = np.c_[x0.ravel(), x1.ravel()]
y_predict = model.predict(X_new)
zz = y_predict.reshape(x0.shape)
from matplotlib.colors import ListedColormap
custom_cmap = ListedColormap(['#EF9A9A', '#FFF59D','#90CAF9'])
plt.contourf(x0, x1, zz, linewidth=5, cmap=custom_cmap)
plot_decision_boundary(log_reg,axis=[-4,4,-4,4])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()#得到的结果显然有许多的错误分类
输出图片:
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures
from sklearn.preprocessing import StandardScaler
def PolynomialLogisticRegression(degree):
return Pipeline([
('poly',PolynomialFeatures(degree=degree)),
('std_scaler',StandardScaler()),
('log_reg',LogisticRegression())
])
poly_log_reg = PolynomialLogisticRegression(degree=2)
poly_log_reg.fit(X,y)
输出:Pipeline(steps=[('poly', PolynomialFeatures()),
('std_scaler', StandardScaler()),
('log_reg', LogisticRegression())])
poly_log_reg.score(X,y)
输出:0.95
plot_decision_boundary(poly_log_reg,axis=[-4,4,-4,4])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()
输出图片:
改变degree的值,使得degree=20
poly_log_reg2 = PolynomialLogisticRegression(degree=20)
poly_log_reg2.fit(X,y)
plot_decision_boundary(poly_log_reg2,axis=[-4,4,-4,4])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()#degree的值为20,值偏大导致边界的形状不规则,degree值越大,整个模型就越复杂,越容易产生过拟合的现象
输出图片:
degree的值为20,degree值偏大导致边界的形状不规则,degree值越大,整个模型就越复杂,越容易产生过拟合的现象
解决过拟合的思路:1、简化模型(减小degree)2、模型的正则化
scikit-learn建议我们,在使用逻辑回归算法的时候都使用模型的正则化。
七、scikit-learn中的逻辑回归(逻辑回归中使用正则化)
原来我们是在正则式
L
1
L_{1}
L1、
L
2
L_{2}
L2前面引入一个超参数
α
\alpha
α,来调节+号左右二者之间的平衡。现在我们在
J
(
θ
)
J(\theta)
J(θ)前面添加一个超参数C,如果C的值越大,那么在优化损失函数的时候越会机制那个活力将
J
(
θ
)
J(\theta)
J(θ)减小到最小。如果C非常小的话,小于1,此时
L
1
L_{1}
L1或者
L
2
L_{2}
L2的正则项就非常重要,我们在优化损失函数的时候就更加集中火力让
L
1
L_{1}
L1正则项和
L
2
L_{2}
L2正则项相应的小,也就是限制
θ
\theta
θ中所有的元素相应的小。在scikit-learn中使用的是后面的方式。
scikit-learn中的逻辑回归
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(666)
X = np.random.normal(0,1,size=(200,2))#生成均值为0,标准差为1的200个样本,每个样本有2个特征
y = np.array(X[:,0] ** 2 +X[:,1] < 1.5 ,dtype='int')
for _ in range(20):
y[np.random.randint(200)] = 1
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()
输出图片:
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=666)
使用scikit-learn中的逻辑回归
from sklearn.linear_model import LogisticRegression
log_reg = LogisticRegression()
log_reg.fit(X_train,y_train)
log_reg.score(X_train,y_train)
输出:0.7933333333333333
log_reg.score(X_test,y_test)
输出:0.86
def plot_decision_boundary(model, axis):
x0, x1 = np.meshgrid(
np.linspace(axis[0], axis[1], int((axis[1]-axis[0])*100)).reshape(-1,1),
np.linspace(axis[2], axis[3], int((axis[3]-axis[2])*100)).reshape(-1,1)
)
X_new = np.c_[x0.ravel(), x1.ravel()]
y_predict = model.predict(X_new)
zz = y_predict.reshape(x0.shape)
from matplotlib.colors import ListedColormap
custom_cmap = ListedColormap(['#EF9A9A', '#FFF59D','#90CAF9'])
plt.contourf(x0, x1, zz, linewidth=5, cmap=custom_cmap)
plot_decision_boundary(log_reg, axis=[-4,4,-4,4])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()
输出图片:
使用多项式项进行逻辑回归
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
def PolynomialLogisticRegression(degree):
return Pipeline([
('poly',PolynomialFeatures(degree=degree)),
('std_scaler',StandardScaler()),
('log_reg',LogisticRegression())
])
poly_log_reg = PolynomialLogisticRegression(degree=2)
poly_log_reg.fit(X_train,y_train)
输出:Pipeline(steps=[('poly', PolynomialFeatures()),
('std_scaler', StandardScaler()),
('log_reg', LogisticRegression())])
poly_log_reg.score(X_train,y_train)
输出:0.9066666666666666
poly_log_reg.score(X_test,y_test)
输出:0.94
plot_decision_boundary(poly_log_reg, axis=[-4,4,-4,4])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()
输出图片:
poly_log_reg2 = PolynomialLogisticRegression(degree=20)#改变degree的值
poly_log_reg2.fit(X_train,y_train)
输出:Pipeline(steps=[('poly', PolynomialFeatures(degree=20)),
('std_scaler', StandardScaler()),
('log_reg', LogisticRegression())])
poly_log_reg2.score(X_train,y_train)
输出:0.94
poly_log_reg2.score(X_test,y_test)#得到的结果不如degree=2的时候,存在过拟合的情况
输出:0.92
plot_decision_boundary(poly_log_reg2, axis=[-4,4,-4,4])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()#决策边界弯弯曲曲,表示发生了过拟合现象
输出图片:
在PolynomialLogisticRegression函数中加入一个参数C:
def PolynomialLogisticRegression(degree,C):
return Pipeline([
('poly',PolynomialFeatures(degree=degree)),
('std_scaler',StandardScaler()),
('log_reg',LogisticRegression(C=C))
])
poly_log_reg3 = PolynomialLogisticRegression(degree=20,C=0.1)
poly_log_reg3.fit(X_train,y_train)
poly_log_reg3.score(X_train,y_train)
输出:0.84
poly_log_reg3.score(X_test,y_test)
输出:0.92
plot_decision_boundary(poly_log_reg3, axis=[-4,4,-4,4])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()
输出图片:
使用L2正则(之前默认使用L1正则):
def PolynomialLogisticRegression(degree,C,penalty='l2'):#前面都是使用l1正则项,这次我们使用l2正则项
return Pipeline([
('poly',PolynomialFeatures(degree=degree)),
('std_scaler',StandardScaler()),
('log_reg',LogisticRegression(C=C,penalty=penalty))
])
poly_log_reg4 = PolynomialLogisticRegression(degree=20,C=0.1,penalty='l2')
poly_log_reg4.fit(X_train,y_train)
poly_log_reg4.score(X_train,y_train)
输出:0.84
poly_log_reg4.score(X_test,y_test)
输出:0.92
plot_decision_boundary(poly_log_reg4, axis=[-4,4,-4,4])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.show()
输出图片:
八、OvO和OvR
逻辑回归只能解决二分类问题,解决多分类问题:OvR、OvO
OvR
将上图中红色的点看作是one,那么其他的点就是rest,这样就将四分类问题转化为了二分类问题,我们就可以用逻辑回归算法来估计给定的样本点它是红色类别的概率和是非红色样本的概率,我们也可以将别的颜色看作one
OvO
每次只能挑出两个类别
相较于OvR来说,OvO耗时较多但是分类结果较准确,因为每次只用真实的两个类别进行比较,而没有混淆其它的类别信息。
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
iris = datasets.load_iris()
X = iris.data[:,:2]#这里只使用了两个特征
y = iris.target
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=666)
from sklearn.linear_model import LogisticRegression
log_reg = LogisticRegression(multi_class="ovr",solver="liblinear")
log_reg.fit(X_train,y_train)
输出:LogisticRegression(multi_class='ovr', solver='liblinear')
log_reg.score(X_test,y_test)
输出:0.6578947368421053
def plot_decision_boundary(model, axis):
x0, x1 = np.meshgrid(
np.linspace(axis[0], axis[1], int((axis[1]-axis[0])*100)).reshape(-1,1),
np.linspace(axis[2], axis[3], int((axis[3]-axis[2])*100)).reshape(-1,1)
)
X_new = np.c_[x0.ravel(), x1.ravel()]
y_predict = model.predict(X_new)
zz = y_predict.reshape(x0.shape)
from matplotlib.colors import ListedColormap
custom_cmap = ListedColormap(['#EF9A9A', '#FFF59D','#90CAF9'])
plt.contourf(x0, x1, zz, linewidth=5, cmap=custom_cmap)
plot_decision_boundary(log_reg,axis=[4,8.5,1.5,4.5])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.scatter(X[y==2,0],X[y==2,1])
plt.show()#打印OvR结果对应的决策边界
下面使用OvO的方式
log_reg2 = LogisticRegression(multi_class="multinomial",solver="newton-cg")#multi_class="multinomial"就表示设置方式为ovo,这里需要设置solver="newton-cg"
log_reg2.fit(X_train,y_train)
log_reg2.score(X_test,y_test)
输出:0.7894736842105263
plot_decision_boundary(log_reg2,axis=[4,8.5,1.5,4.5])
plt.scatter(X[y==0,0],X[y==0,1])
plt.scatter(X[y==1,0],X[y==1,1])
plt.scatter(X[y==2,0],X[y==2,1])
plt.show()#打印OvO结果对应的决策边界
输出图片:
使用所有的数据(鸢尾花数据集有四个特征)
X = iris.data
y = iris.target
X_train,X_test,y_train,y_test = train_test_split(X,y,random_state=666)
log_reg = LogisticRegression(multi_class="ovr",solver="liblinear")
log_reg.fit(X_train,y_train)
log_reg.score(X_test,y_test)
输出:0.9473684210526315
log_reg2 = LogisticRegression(multi_class="multinomial",solver="newton-cg")
log_reg2.fit(X_train,y_train)
log_reg2.score(X_test,y_test)
输出:1.0
OvO and OvR in scikit-learn
from sklearn.multiclass import OneVsRestClassifier
ovr = OneVsRestClassifier(log_reg)
ovr.fit(X_train,y_train)
ovr.score(X_test,y_test)
输出:0.9473684210526315
from sklearn.multiclass import OneVsOneClassifier
ovo = OneVsOneClassifier(log_reg)
ovo.fit(X_train,y_train)
ovo.score(X_test,y_test)
输出:1.0