线性回归
这里,我们将工资和年龄作为自变量, 额度作为因变量来建立模型,预测不同情况下,银行根据客户的工资和年龄应该发放的贷款额度。建立特征值和预测值的映射关系公式:
假设为对应特征值和参数θ的情况下的预测值
与真实值的误差:
正态分布,又称高斯分布。我们可以得到的高斯分布中的概率,如下:
(1)
公式(1)表示的的在参数为θ时,特征值为x(i)的情况下,产生(或者越接近于)y(i)的最大(即接近于真实值的概率, 最大似然估计思想)。
(2)
公式(2)表示各特征值产生对应的真实值的概率的累乘。得出的概率值越大,说明模型θ性能越好。但是这里有一个问题,就是累乘计算难度比较大,计算复杂度非常高,所以可以对其进行转换,使计算更加简单,且不影响最终的结果。如下,使用对数似然方法:
得到:
(3)
为什么得到公式(3)呢?
从上面分析,我们可以知道,和
为定值,因此l(θ)的变化只与
有关,即这个公式(3)的值越小,l(θ)的值越大。
推导过程可参考:https://wenku.baidu.com/view/f7fa307a580216fc700afdb9.html
其中令=0,就可以得到 (4)
另外的,公式(4)同时满足一元一次和多元一次方程,只是在数组维度上面有所不同。
线性回归求解(最小二乘法):
• 问题: 不可逆怎么办?(目标:满秩——行列向量线性无关)
• 解决方案:
– 设定正数λ
– 如何设定λ的值,开放测试
案例:
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets
class LinearRegression():
def __init__(self):
self.w = None
def fit(self, X, y):
X = np.insert(X, 0, 1, axis=1)
print (X.shape)
X_ = np.linalg.inv(X.T.dot(X))
self.w = X_.dot(X.T).dot(y)
def predict(self, X):
# Insert constant ones for bias weights
X = np.insert(X, 0, 1, axis=1)
y_pred = X.dot(self.w)
return y_pred
def mean_squared_error(y_true, y_pred):
mse = np.mean(np.power(y_true - y_pred, 2))
return mse
def main():
# Load the diabetes dataset
diabetes = datasets.load_diabetes()
# Use only one feature
X = diabetes.data[:, np.newaxis, 2]
print (X.shape)
# Split the data into training/testing sets
x_train, x_test = X[:-20], X[-20:]
# Split the targets into training/testing sets
y_train, y_test = diabetes.target[:-20], diabetes.target[-20:]
clf = LinearRegression()
clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)
# Print the mean squared error
print ("Mean Squared Error:", mean_squared_error(y_test, y_pred))
# Plot the results
plt.scatter(x_test[:,0], y_test, color='black')
plt.plot(x_test[:,0], y_pred, color='blue', linewidth=3)
plt.show()
main()
之后,我们就可以用得到的θ进行预测了。