线性回归通过建立特征与目标值的线性关系进行预测:
$$ y = w_1x_1 + w_2x_2 + ... + w_nx_n + b = \mathbf{w}^T\mathbf{x} + b $$
fit())coef_/intercept_)性能评估(均方误差)
import os
import urllib
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
# noinspection HttpUrlsUsage
def load_boston():
"""
加载Boston数据集
:return:
"""
data_url = "http://lib.stat.cmu.edu/datasets/boston"
if not os.path.exists("boston.data"):
urllib.request.urlretrieve(data_url, "boston.data")
raw_df = pd.read_csv("boston.data", sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
return data, target
def linear_regression_1():
"""
正规方程的优化方法对波士顿房价进行预测
:return:
"""
# 1)加载数据集
data, target = load_boston()
# 2)数据集的划分
x_train, x_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=0)
# 3) 标准化
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)
# 4) 预估器训练
estimator = LinearRegression()
estimator.fit(x_train, y_train)
# 5) 模型
print("正规方程的系数为:", estimator.coef_)
print("正规方程的偏置为:", estimator.intercept_)
# 6) 模型评估
y_predict = estimator.predict(x_test)
print("正规方程的均方误差为:", mean_squared_error(y_test, y_predict))
return None
def linear_regression_2():
"""
梯度下降的优化方法对波士顿房价进行预测
:return:
"""
# 1)加载数据集
data, target = load_boston()
# 2)数据集的划分
x_train, x_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=0)
# 3) 标准化
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)
# 4) 预估器训练
estimator = SGDRegressor(learning_rate="constant", max_iter=10000, eta0=0.01, penalty='l1')
estimator.fit(x_train, y_train)
# 5) 模型
print("梯度下降的系数为:", estimator.coef_)
print("梯度下降的偏置为:", estimator.intercept_)
# 6) 模型评估
y_predict = estimator.predict(x_test)
print("梯度下降的均方误差为:", mean_squared_error(y_test, y_predict))
return None
if __name__ == '__main__':
linear_regression_1()
linear_regression_2()
| 现象 | 原因 | 解决方法 |
|---|---|---|
| 欠拟合 | 特征不足/模型简单 | 增加特征、使用复杂模型 |
| 过拟合 | 特征过多/噪声干扰 | 正则化、交叉验证、特征选择 |
$$ L(\mathbf{w}) = \sum(y_i - \hat{y}_i)^2 + \lambda\sum w_j^2 $$
优点:缓解多重共线性,提升泛化能力
import os
import urllib
import pandas as pd
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
# noinspection HttpUrlsUsage
def load_boston():
"""
加载Boston数据集
:return:
"""
data_url = "http://lib.stat.cmu.edu/datasets/boston"
if not os.path.exists("boston.data"):
urllib.request.urlretrieve(data_url, "boston.data")
raw_df = pd.read_csv("boston.data", sep="\s+", skiprows=22, header=None)
data = np.hstack([raw_df.values[::2, :], raw_df.values[1::2, :2]])
target = raw_df.values[1::2, 2]
return data, target
def linear_regression_3():
"""
岭回归的优化方法对波士顿房价进行预测
:return:
"""
# 1)加载数据集
data, target = load_boston()
# 2)数据集的划分
x_train, x_test, y_train, y_test = train_test_split(data, target, test_size=0.2, random_state=0)
# 3) 标准化
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)
# 4) 预估器训练
estimator = Ridge(max_iter=10000)
estimator.fit(x_train, y_train)
# 5) 模型
print("岭回归的系数为:", estimator.coef_)
print("岭回归的偏置为:", estimator.intercept_)
# 6) 模型评估
y_predict = estimator.predict(x_test)
print("岭回归的均方误差为:", mean_squared_error(y_test, y_predict))
return None
if __name__ == '__main__':
linear_regression_3()
$$ \sigma(z) = \frac{1}{1 + e^{-z}} $$
保存:使用import joblib
joblib.dump(model, 'model.pkl')
加载:
model = joblib.load('model.pkl')
$$ s = \frac{b_i - a_i}{\max(a_i, b_i)} $$