逻辑回归
算法基础理解
前面我们讲到过线性回归算法和多项式回归算法,算法的本质以及目的便是求出 ý = f(x),如果给函数输入一个预测样本 x ,经过 f(x) 运算后得到一个 ý;但是这种方法存在问题,那便是,我们得到的预测值是处在负无穷到正无穷之间的,没有限制,这样做的弊端很大。
但是逻辑回归不同,逻辑回归的原理是将样本的特征和样本发生的概率结合起来,预测样本发生的概率,然后再对样本发生的概率进行分析,同时这也是逻辑回归算法和其他算法的不同点。
逻辑回归算法既可以解决分类问题(二分类,也可以通过改进解决多分类问题),也可以解决回归问题。
公式推导以及代码封装
代码封装
class LogisticRegression:
def __init__(self):
self.coef_ = None
self.intercept_ = None
self._theta = None
'''tool function'''
def _sigmod(self,t):
return 1. / (1. + np.exp(-t))
'''use the gradient to fit the model'''
def fit(self,X_train,y_train,eta=0.01,n_iters = 1e4):
'''check'''
assert X_train.shape[0] == y_train.shape[0],\
"the size must be valid"
def J(theta,X_b,y):
y_hat = self._sigmod(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._sigmod(X_b.dot(theta)) - y) / len(X_b)
def gradient_decent(X_b,y,initial_theta,eta,n_iters=1e4,epsilon = 1e-8):
theta = initial_theta
cur_iter = 0
while cur_iter < n_iters:
last_theta = theta
gradient = DJ(theta,X_b,y)
theta = theta - eta*gradient
while(abs(J(theta,X_b