3.1 基本形式
样本,其中
是
在第i个属性上的取值。线性模型试图学得一个通过属性得线性组合来进行预测得函数,即
3.2 线性回归
3.2.1 一元线性回归
均方误差最小化,对w和b求导:
上面两个方程等于0可以得到
3.2.2 多元线性回归
m个d个元素得示例,把数据集D表示为一个的大小的矩阵
:
则均方误差为:
对求导得到:
当为满秩矩阵或正定矩阵时,上式为0可得:
代码实现1:
import numpy as np
class LinearRegression:
def __init__(self):
self._theta = None
self.intercept_ = None
self.coef_ = None
def fit(self,x_train,y_train):
X_b = np.hstack([np.ones((len(x_train),1)), x_train])
self._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)
self.intercept_ = self._theta[0]
self.coef_ = self._theta[1:]
return self
def predict(self,x_predict):
X_b = np.hstack([np.ones((len(x_predict),1)), x_predict])
return X_b.dot(self._theta)
3.2.3 梯度下降法
因为
所以
代码实现如下:
import numpy as np
alpha = 0.01
def cost_function(theta, X, y):
diff = np.dot(X, theta) - y
return (1./(2*m)) * np.dot(np.transpose(diff), diff)
def gradient_function(theta, X, y):
diff = np.dot(X, theta) - y
return (1./m) * np.dot(np.transpose(X), diff)
def gradient_descent(X, y, alpha):
theta = np.ones((X.shape[1]+1,1))
gradient = gradient_function(theta, X, y)
while not np.all(np.absolute(gradient) <= 1e-5):
theta = theta - alpha * gradient
gradient = gradient_function(theta, X, y)
return theta
3.3 对数几率回归
对于二分类任务,
使用对数几率函数可以得到:
变换后得到:
将y视为样本x作为正例的可能性,1-y是反例的可能性,则有
为简便计算令, 对数回归模型的最大化似然函数为:
带入p的表达式:
可以得到:
利用这个表达式,可以用梯度下降法求解参数。