目录:
一、逻辑回归模型
二、损失函数
三、损失函数的优化方法:梯度下降法
四、实现逻辑回归算法
一、逻辑回归模型
(1)逻辑回归既可以看做是回归算法,也可以看做是分类算法,通常作为分类算法使用,只可以解决分类问题。
(2)
模型:
(2)Sigmoid函数:值域(0,1);t=0时,p=0.5
在这里插入代码片
代码
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()
二、损失函数
(1)由
可得损失函数为:
三、损失函数的优化方法:梯度下降法
即:找到一组
,使
达到最小值
对应梯度:
最终可得:
四、实现逻辑回归算法
import numpy as np
import matplotlib.pyplot as plt
#定义一个类,注意括号是空的,因为我们要从空白创建这个类
class LogisticRegression():
def _init_(self):
#初始化Logistic Regression模型
self.coef_=None
self.interception_=None
self._theta=None
def _sigmoid(self,t):
return 1./(1.+np.exp(-t))
def fit(self,X_train,y_train,eta=0.01,n_iters=1e4):
#根据训练数据集x_train,y_train训练 Linear 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')
#求J的导数
def dJ(theta,X_b,y):
return X_b.t.dot(self.sigmoid(X_b.dot(theta))-y)/len(X_b)
#梯度下降法,n_iters=1e4用以防止死循环,epsilon=1e-8用以表示精度
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])#初始化theta,theta是一个向量
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.self.interception_ 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 xpredict must be equal to X_train"
X_b=np.hatack([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.self.interception_ 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 xpredict must be equal to X_train"
proba=self.predict_proba(X_predict)
return np.array(proba>=0.5,dtype='int')
def _repr_(self):
return "LogisticRegression()"