线性回归入门
1.1 数据生成
使用一个二维的函数生成数据,根据该函数生成一些数据点,给每个数据点加噪声
import numpy as np
import matplotlib.pyplot as plt
def true_fun(X): # 这是我们设定的真实函数,即ground truth的模型
return 1.5*X + 0.2
np.random.seed(0) # 设置随机种子
n_samples = 30 # 设置采样数据点的个数
'''生成随机数据作为训练集,并且加一些噪声'''
X_train = np.sort(np.random.rand(n_samples))
y_train = (true_fun(X_train) + np.random.randn(n_samples) * 0.05).reshape(n_samples,1)
1.2 定义模型
生成数据之后,直接从sklearn库中导入类LinearRegression即可,由于线性回归比较简单,这个类的输入参数也比较少,无需多加设置,定义好模型后,直接训练,就能得到拟合的一些参数。
from sklearn.linear_model import LinearRegression # 导入线性回归模型
model = LinearRegression() # 定义模型
model.fit(X_train[:,np.newaxis], y_train) # 训练模型
print("输出参数w:",model.coef_) # 输出模型参数w
print("输出参数b:",model.intercept_) # 输出参数b
输出参数w: [[1.4474774]]
输出参数b: [0.22557542]
1.3 模型测试与比较
线性回归拟合的参数是1.44 和 0.22,接近真实的1.5和0.2,接着再选取一批数据测试,画图看看算法模型与实际模型的差距
X_test = np.linspace(0, 1, 100)
plt.plot(X_test, model.predict(X_test[:, np.newaxis]), label="Model")
plt.plot(X_test, true_fun(X_test), label="True function")
plt.scatter(X_train,y_train) # 画出训练集的点
plt.legend(loc="best")
plt.show()
由于数据简单,从图中也可以看出,算法拟合曲线与真实的比较接近,对于比较复杂以及高维的情况,线性回归就不能满足拟合的要求,这时候需要用到更为高级一些的多项式回归。
多项式回归
多项式回归的思路一般是将m次多项式方程转化为m线性回归方程,即将 y = b 0 + b 1 ∗ x + . . . + b m ∗ x m y=b_0+b_1*x+...+b_m*x^m y=b0+b1∗x+...+bm∗xm转换为 y = b 0 ∗ + b 1 ∗ x 1 + . . . + b m ∗ x m y=b_0*+b_1*x_1+...+b_m*x_m y=b0∗+b1∗x1+...+bm∗xm(令 x m = x m x_m=x^m xm=xm即可),然后使用线性回归的方法求出相应的参数。我们将多项式特征分析器和线性回归串联,算出线性回归后 的参数之后倒推回去。
import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures # 导入能够计算多项式特征的类
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score
def true_fun(X): # 这是我们设定的真实函数,即ground truth的模型
return np.cos(1.5 * np.pi * X)
np.random.seed(0)
n_samples = 30 # 设置随机种子
X = np.sort(np.random.rand(n_samples))
y = true_fun(X) + np.random.randn(n_samples) * 0.1
degrees = [1, 4, 15] # 多项式最高次
plt.figure(figsize=(14, 5))
for i in range(len(degrees)):
ax = plt.subplot(1, len(degrees), i + 1)
plt.setp(ax, xticks=(), yticks=())
polynomial_features = PolynomialFeatures(degree=degrees[i],
include_bias=False)
linear_regression = LinearRegression()
pipeline = Pipeline([("polynomial_features", polynomial_features),
("linear_regression", linear_regression)]) # 使用pipline串联模型
pipeline.fit(X[:, np.newaxis], y) # np.newaxis的作用是增加一个维度
scores = cross_val_score(pipeline, X[:, np.newaxis], y,scoring="neg_mean_squared_error", cv=10) # 使用交叉验证
X_test = np.linspace(0, 1, 100)
plt.plot(X_test, pipeline.predict(X_test[:, np.newaxis]), label="Model")
plt.plot(X_test, true_fun(X_test), label="True function")
plt.scatter(X, y, edgecolor='b', s=20, label="Samples")
plt.xlabel("x")
plt.ylabel("y")
plt.xlim((0, 1))
plt.ylim((-2, 2))
plt.legend(loc="best")
plt.title("Degree {}\nMSE = {:.2e}(+/- {:.2e})".format(
degrees[i], -scores.mean(), scores.std()))
plt.show()
2.1交叉验证
上面使用了交叉验证scores = cross_val_score(pipeline, X[:, np.newaxis], y,scoring="neg_mean_squared_error", cv=10) # 使用交叉验证
,类似的方法还有holdout检验以及自助法,(交叉验证的升级版,即每次又放回去的选取数据)。交叉验证法的作用就是尝试利用不同的训练集/测试集划分来对模型做多组不同的训练/测试,来应对测试结果过于片面以及训练数据不足的问题。
2.2 过拟合与欠拟合
多项式回归根据最高次数的不同,其回归的效果对于同一数据可能也不会不同,高次的多项式能够产生更多的弯曲从而拟合更多非线性规则的数据,低次的则贴近线性回归。
但在这过程中,也会产生一个过拟合与欠拟合的问题。上图结果 第一次的就是欠拟合,第三次是过拟合。
逻辑回归
理论
应用
import sys
from pathlib import Path
curr_path = str(Path().absolute())
parent_path = str(Path().absolute().parent)
sys.path.append(parent_path) # add current terminal path to sys.path
from Mnist.load_data import load_local_mnist
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
(X_train, y_train), (X_test, y_test) = load_local_mnist(normalize = False,one_hot = False)
X_train, y_train= X_train[:2000], y_train[:2000]
X_test, y_test = X_test[:200],y_test[:200]
# solver:即使用的优化器,lbfgs:拟牛顿法, sag:随机梯度下降
model = LogisticRegression(solver='lbfgs', max_iter=500) # lbfgs:拟牛顿法
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(classification_report(y_test, y_pred)) # 打印报告
precision recall f1-score support
0 0.94 1.00 0.97 17
1 1.00 0.93 0.96 28
2 0.76 0.81 0.79 16
3 0.88 0.94 0.91 16
4 0.93 0.89 0.91 28
5 0.94 0.85 0.89 20
6 0.90 0.90 0.90 20
7 1.00 0.88 0.93 24
8 0.91 1.00 0.95 10
9 0.84 1.00 0.91 21
accuracy 0.92 200
macro avg 0.91 0.92 0.91 200
weighted avg 0.92 0.92 0.92 200
[校招内推]
【科大讯飞校园招聘】 内推链接:https://campus.iflytek.com/official-pc#/home?refrenceCode=U2V4437,内推码:U2V4437
。期待您的加入!(通过此链接投递计入内推,内推简历优先筛选~)