5.2.机器学习--岭回归+局部线性回归
目录
1.最小二乘法:
平面几何表达直线(两个系数):
重新命名变量:
强行加一个x0=1:
向量表达:
2.损失函数:
矩阵表达:
矩阵展开:
推导:
为最小化该函数, 应对w求导, 且其结果为0。
根据矩阵求导法则:
于是有:
解得:
在我们上面求出来的最小二乘法求损失函数最小值的时候,求出来的值,但是有个问题,如多数剧中的如果是奇异阵无法求逆该怎么办。下面将岭回归解决:
1.岭回归
- 动机: 奇异矩阵无法求逆
- 方案: 在对角线上加常数
损失函数:
其中, 后半部分是正则项.
矩阵化的展开式:
求导:
1.1代码示例
# 导入必要的库
import numpy as np
import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# 创建示例数据集
np.random.seed(0)
X = np.random.rand(100, 10) # 100个样本,10个特征
y = 2 * X[:, 0] + 3 * X[:, 1] + np.random.randn(100) # 构造线性关系,并添加噪声
# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义岭回归模型
ridge = Ridge(alpha=1.0) # alpha为岭参数,默认为1.0
# 在训练集上训练模型
ridge.fit(X_train, y_train)
# 在测试集上进行预测
y_pred = ridge.predict(X_test)
# 计算均方误差(MSE)作为性能评估指标
mse = mean_squared_error(y_test, y_pred)
print("岭回归模型的均方误差为:", mse)
# 绘制预测值与真实值的对比图
plt.figure(figsize=(8, 6))
plt.scatter(y_test, y_pred, color='blue')
plt.plot([y_test.min(), y_test.max()], [y_test.min(), y_test.max()], linestyle='--', color='red')
plt.xlabel('True Values')
plt.ylabel('Predictions')
plt.title('True vs. Predicted Values (Ridge Regression)')
plt.show()
2.局部线性回归
local linear regression
- 动机: 线性回归太粗暴, 在x xx或t tt变化大时不适合
- 方案: 局部加权
当两个样本点的特征向量距离较近时,它们的输出变量通常比较接近,也就是说它们具有相似的性质。现在我们有m 个训练样本点( x 1 , y 1 ) , ( x 2 , y 2 ) , … , ( x m , y m )构成训练集。那么当我们给一个特征向量x 时,要根据训练集中的信息预测出它的输出变量y ,距离x 越近的训练集中的样本点越应该被重视。换句话说,我们需要给训练集中的每个样本点一个权值,距离x 越近的样本点的权值应该越大,这是赋权的一个原则,那么具体应该如何赋权呢?
欧氏距离(2范数)是一种常用的度量方法:
高斯核是另外一种度量方法:
其中,x 为新预测的样本特征数据,x i为训练集的样本特征数据。参数τ控制了权值变化的速率.
损失函数:
权值有如下性质:
矩阵化展开式: 是对角矩阵
对w求偏导且等于0(损失函数最小):
它比线性回归的式子多了一个对角矩阵W , 因此在W=I时退化为前者.
2.1代码示例
数据集:
ex0.txt:
1.0000000.0677323.176513
1.0000000.4278103.816464
1.0000000.9957314.550095
1.0000000.7383364.256571
1.0000000.9810834.560815
1.0000000.5261713.929515
1.0000000.3788873.526170
1.0000000.0338593.156393
1.0000000.1327913.110301
1.0000000.1383063.149813
1.0000000.2478093.476346
1.0000000.6482704.119688
1.0000000.7312094.282233
1.0000000.2368333.486582
1.0000000.9697884.655492
1.0000000.6074923.965162
1.0000000.3586223.514900
1.0000000.1478463.125947
1.0000000.6378204.094115
1.0000000.2303723.476039
1.0000000.0702373.210610
1.0000000.0671543.190612
1.0000000.9255774.631504
1.0000000.7177334.295890
1.0000000.0153713.085028
1.0000000.3350703.448080
1.0000000.0404863.167440
1.0000000.2125753.364266
1.0000000.6172183.993482
1.0000000.5411963.891471
1.0000000.0453533.143259
1.0000000.1267623.114204
1.0000000.5564863.851484
1.0000000.9011444.621899
1.0000000.9584764.580768
1.0000000.2745613.620992
1.0000000.3943963.580501
1.0000000.8724804.618706
1.0000000.4099323.676867
1.0000000.9089694.641845
1.0000000.1668193.175939
1.0000000.6650164.264980
1.0000000.2637273.558448
1.0000000.2312143.436632
1.0000000.5529283.831052
1.0000000.0477443.182853
1.0000000.3657463.498906
1.0000000.4950023.946833
1.0000000.4934663.900583
1.0000000.7921014.238522
1.0000000.7696604.233080
1.0000000.2518213.521557
1.0000000.1819513.203344
1.0000000.8081774.278105
1.0000000.3341163.555705
1.0000000.3386303.502661
1.0000000.4525843.859776
1.0000000.6947704.275956
1.0000000.5909023.916191
1.0000000.3079283.587961
1.0000000.1483643.183004
1.0000000.7021804.225236
1.0000000.7215444.231083
1.0000000.6668864.240544
1.0000000.1249313.222372
1.0000000.6182864.021445
1.0000000.3810863.567479
1.0000000.3856433.562580
1.0000000.7771754.262059
1.0000000.1160893.208813
1.0000000.1154873.169825
1.0000000.6635104.193949
1.0000000.2548843.491678
1.0000000.9938884.533306
1.0000000.2954343.550108
1.0000000.9525234.636427
1.0000000.3070473.557078
1.0000000.2772613.552874
1.0000000.2791013.494159
1.0000000.1757243.206828
1.0000000.1563833.195266
1.0000000.7331654.221292
1.0000000.8481424.413372
1.0000000.7711844.184347
1.0000000.4294923.742878
1.0000000.1621763.201878
1.0000000.9170644.648964
1.0000000.3150443.510117
1.0000000.2014733.274434
1.0000000.2970383.579622
1.0000000.3366473.489244
1.0000000.6661094.237386
1.0000000.5838883.913749
1.0000000.0850313.228990
1.0000000.6870064.286286
1.0000000.9496554.628614
1.0000000.1899123.239536
1.0000000.8440274.457997
1.0000000.3332883.513384
1.0000000.4270353.729674
1.0000000.4663693.834274
1.0000000.5506593.811155
1.0000000.2782133.598316
1.0000000.9187694.692514
1.0000000.8865554.604859
1.0000000.5694883.864912
1.0000000.0663793.184236
1.0000000.3357513.500796
1.0000000.4268633.743365
1.0000000.3957463.622905
1.0000000.6942214.310796
1.0000000.2727603.583357
1.0000000.5034953.901852
1.0000000.0671193.233521
1.0000000.0383263.105266
1.0000000.5991223.865544
1.0000000.9470544.628625
1.0000000.6712794.231213
1.0000000.4348113.791149
1.0000000.5093813.968271
1.0000000.7494424.253910
1.0000000.0580143.194710
1.0000000.4829783.996503
1.0000000.4667763.904358
1.0000000.3577673.503976
1.0000000.9491234.557545
1.0000000.4173203.699876
1.0000000.9204614.613614
1.0000000.1564333.140401
1.0000000.6566624.206717
1.0000000.6164183.969524
1.0000000.8534284.476096
1.0000000.1332953.136528
1.0000000.6930074.279071
1.0000000.1784493.200603
1.0000000.1995263.299012
1.0000000.0732243.209873
1.0000000.2865153.632942
1.0000000.1820263.248361
1.0000000.6215233.995783
1.0000000.3445843.563262
1.0000000.3985563.649712
1.0000000.4803693.951845
1.0000000.1533503.145031
1.0000000.1718463.181577
1.0000000.8670824.637087
1.0000000.2238553.404964
1.0000000.5283013.873188
1.0000000.8901924.633648
1.0000000.1063523.154768
1.0000000.9178864.623637
1.0000000.0148553.078132
1.0000000.5676823.913596
1.0000000.0688543.221817
1.0000000.6035353.938071
1.0000000.5320503.880822
1.0000000.6513624.176436
1.0000000.9012254.648161
1.0000000.2043373.332312
1.0000000.6960814.240614
1.0000000.9639244.532224
1.0000000.9813904.557105
1.0000000.9879114.610072
1.0000000.9909474.636569
1.0000000.7360214.229813
1.0000000.2535743.500860
1.0000000.6747224.245514
1.0000000.9393684.605182
1.0000000.2354193.454340
1.0000000.1105213.180775
1.0000000.2180233.380820
1.0000000.8697784.565020
1.0000000.1968303.279973
1.0000000.9581784.554241
1.0000000.9726734.633520
1.0000000.7457974.281037
1.0000000.4456743.844426
1.0000000.4705573.891601
1.0000000.5492363.849728
1.0000000.3356913.492215
1.0000000.8847394.592374
1.0000000.9189164.632025
1.0000000.4418153.756750
1.0000000.1165983.133555
1.0000000.3592743.567919
1.0000000.8148114.363382
1.0000000.3871253.560165
1.0000000.9822434.564305
1.0000000.7808804.215055
1.0000000.6525654.174999
1.0000000.8700304.586640
1.0000000.6047553.960008
1.0000000.2552123.529963
1.0000000.7305464.213412
1.0000000.4938293.908685
1.0000000.2570173.585821
1.0000000.8337354.374394
1.0000000.0700953.213817
1.0000000.5270703.952681
1.0000000.1161633.129283
ex1.txt:
1.0000000.6359754.093119
1.0000000.5524383.804358
1.0000000.8559224.456531
1.0000000.0833863.187049
1.0000000.9758024.506176
1.0000000.1812693.171914
1.0000000.1291563.053996
1.0000000.6056483.974659
1.0000000.3016253.542525
1.0000000.6988054.234199
1.0000000.2264193.405937
1.0000000.5192903.932469
1.0000000.3544243.514051
1.0000000.1183803.105317
1.0000000.5128113.843351
1.0000000.2367953.576074
1.0000000.3535093.544471
1.0000000.4814473.934625
1.0000000.0605093.228226
1.0000000.1740903.300232
1.0000000.8068184.331785
1.0000000.5314623.908166
1.0000000.8531674.386918
1.0000000.3048043.617260
1.0000000.6120214.082411
1.0000000.6208803.949470
1.0000000.5802453.984041
1.0000000.7424434.251907
1.0000000.1107703.115214
1.0000000.7426874.234319
1.0000000.5743903.947544
1.0000000.9863784.532519
1.0000000.2948673.510392
1.0000000.4721253.927832
1.0000000.8723214.631825
1.0000000.8435374.482263
1.0000000.8645774.487656
1.0000000.3418743.486371
1.0000000.0979803.137514
1.0000000.7578744.212660
1.0000000.8776564.506268
1.0000000.4579933.800973
1.0000000.4753413.975979
1.0000000.8483914.494447
1.0000000.7460594.244715
1.0000000.1534623.019251
1.0000000.6942564.277945
1.0000000.4987123.812414
1.0000000.0235803.116973
1.0000000.9768264.617363
1.0000000.6240044.005158
1.0000000.4722203.874188
1.0000000.3905513.630228
1.0000000.0213493.145849
1.0000000.1734883.192618
1.0000000.9710284.540226
1.0000000.5953023.835879
1.0000000.0976383.141948
1.0000000.7459724.323316
1.0000000.6763904.204829
1.0000000.4889493.946710
1.0000000.9828734.666332
1.0000000.2960603.482348
1.0000000.2280083.451286
1.0000000.6710594.186388
1.0000000.3794193.595223
1.0000000.2851703.534446
1.0000000.2363143.420891
1.0000000.6298034.115553
1.0000000.7702724.257463
1.0000000.4930523.934798
1.0000000.6315924.154963
1.0000000.9656764.587470
1.0000000.5986753.944766
1.0000000.3519973.480517
1.0000000.3420013.481382
1.0000000.6614244.253286
1.0000000.1409123.131670
1.0000000.3735743.527099
1.0000000.2231663.378051
1.0000000.9087854.578960
1.0000000.9151024.551773
1.0000000.4109403.634259
1.0000000.7549214.167016
1.0000000.7644534.217570
1.0000000.1015343.237201
1.0000000.7803684.353163
1.0000000.8198684.342184
1.0000000.1739903.236950
1.0000000.3304723.509404
1.0000000.1626563.242535
1.0000000.4762833.907937
1.0000000.6363914.108455
1.0000000.7587374.181959
1.0000000.7783724.251103
1.0000000.9362874.538462
1.0000000.5109043.848193
1.0000000.5157373.974757
1.0000000.4378233.708323
1.0000000.8286074.385210
1.0000000.5561003.927788
1.0000000.0382093.187881
1.0000000.3219933.444542
1.0000000.0672883.199263
1.0000000.7749894.285745
1.0000000.5660773.878557
1.0000000.7963144.155745
1.0000000.7466004.197772
1.0000000.3607783.524928
1.0000000.3973213.525692
1.0000000.0621423.211318
1.0000000.3792503.570495
1.0000000.2482383.462431
1.0000000.6825614.206177
1.0000000.3553933.562322
1.0000000.8890514.595215
1.0000000.7338064.182694
1.0000000.1539493.320695
1.0000000.0361043.122670
1.0000000.3885773.541312
1.0000000.2744813.502135
1.0000000.3194013.537559
1.0000000.4316533.712609
1.0000000.9603984.504875
1.0000000.0836603.262164
1.0000000.1220983.105583
1.0000000.4152993.742634
1.0000000.8541924.566589
1.0000000.9255744.630884
1.0000000.1093063.190539
1.0000000.8051614.289105
1.0000000.3444743.406602
1.0000000.7691164.251899
1.0000000.1820033.183214
1.0000000.2259723.342508
1.0000000.4130883.747926
1.0000000.9644444.499998
1.0000000.2033343.350089
1.0000000.2855743.539554
1.0000000.8502094.443465
1.0000000.0615613.290370
1.0000000.4269353.733302
1.0000000.3893763.614803
1.0000000.0969183.175132
1.0000000.1489383.164284
1.0000000.8937384.619629
1.0000000.1955273.426648
1.0000000.4072483.670722
1.0000000.2243573.412571
1.0000000.0459633.110330
1.0000000.9446474.647928
1.0000000.7565524.164515
1.0000000.4320983.730603
1.0000000.9905114.609868
1.0000000.6496994.094111
1.0000000.5848793.907636
1.0000000.7859344.240814
1.0000000.0299453.106915
1.0000000.0757473.201181
1.0000000.4084083.872302
1.0000000.5838513.860890
1.0000000.4977593.884108
1.0000000.4213013.696816
1.0000000.1403203.114540
1.0000000.5464653.791233
1.0000000.8431814.443487
1.0000000.2953903.535337
1.0000000.8250594.417975
1.0000000.9463434.742471
1.0000000.3504043.470964
1.0000000.0427873.113381
1.0000000.3524873.594600
1.0000000.5907363.914875
1.0000000.1207483.108492
1.0000000.1431403.152725
1.0000000.5119263.994118
1.0000000.4963583.933417
1.0000000.3828023.510829
1.0000000.2524643.498402
1.0000000.8458944.460441
1.0000000.1320233.245277
1.0000000.4423013.771067
1.0000000.2668893.434771
1.0000000.0085752.999612
1.0000000.8976324.454221
1.0000000.5331713.985348
1.0000000.2852433.557982
1.0000000.3772583.625972
1.0000000.4869953.922226
1.0000000.3059933.547421
1.0000000.2775283.580944
1.0000000.7508994.268081
1.0000000.6947564.278096
1.0000000.8701584.517640
1.0000000.2764573.555461
1.0000000.0177613.055026
1.0000000.8020464.354819
1.0000000.5592753.894387
1.0000000.9413054.597773
1.0000000.8568774.523616
1.加载数据集
# 定义一个函数用于加载数据集
def loadDataSet(fileName):
# 计算特征数量,通过读取文件的第一行并计算分隔符'\t'的数量减去1
numFeat = len(open(fileName).readline().split('\t')) - 1
# 初始化数据矩阵和标签矩阵
dataMat = []; labelMat = []
# 打开文件
fr = open(fileName)
# 逐行读取文件内容
for line in fr.readlines():
# 初始化当前行的特征列表
lineArr =[]
# 去除行首尾的空白字符,并按'\t'分割字符串
curLine = line.strip().split('\t')
# 遍历特征,将每个特征转换为浮点数并添加到特征列表中
for i in range(numFeat):
lineArr.append(float(curLine[i]))
# 将特征列表添加到数据矩阵中
dataMat.append(lineArr)
# 将标签(最后一列)添加到标签矩阵中
labelMat.append(float(curLine[-1]))
# 返回数据矩阵和标签矩阵
return dataMat,labelMat
2.局部加权线性回归
from numpy import *
from numpy.linalg import linalg
# 定义局部加权线性回归函数
def lwlr(testPoint, xArr, yArr, k=1.0):
# 将输入数据转换为矩阵形式
xMat = np.asmatrix(xArr)
yMat = np.asmatrix(yArr).T
# 获取数据点的数量
m = shape(xMat)[0]
# 初始化权重矩阵为单位矩阵
weights =np.asmatrix(eye((m)))
# 计算每个数据点的权重
for j in range(m):
# 计算测试点与每个数据点的差值
diffMat = testPoint - xMat[j, :]
# 计算权重,并赋值给权重矩阵的对角线元素
weights[j, j] = exp(diffMat * diffMat.T / (-2.0 * k**2))
# 计算X的转置乘以权重乘以X
xTx = xMat.T * (weights * xMat)
# 检查矩阵是否可逆
if linalg.det(xTx) == 0.0:
print("This matrix is singular, cannot do inverse")
return
# 计算回归系数
ws = xTx.I * (xMat.T * (weights * yMat))
# 返回测试点的预测结果
return testPoint * ws
3.画图
#对所有点计算回归值
def lwlrTest(testArr,xArr,yArr,k=1): #计算所有数据点的预测回归值,默认k=1,即完全线性回归
m = shape(testArr)[0]
yHat = zeros(m)
for i in range(m):
yHat[i] = lwlr(testArr[i],xArr,yArr,k)
return yHat
#画出回归方程
def plot_w_figure(xArr,yArr,k=1):
yHat = lwlrTest(xArr,xArr,yArr,k)
xMat = np.asmatrix(xArr)
srtInd = xMat[:,1].argsort(0)#将输入值x从大到小排序并返回索引
xSort = xMat[srtInd][:,0,:]
# print(xSort.shape)
# print(xSort)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(xSort[:,1],yHat[srtInd])#绘制预测点
ax.scatter(xMat[:,1].flatten().A[0],np.asmatrix(yArr).T.flatten().A[0],s=2,c='red')#绘制初始数据点
plt.show()
xArr,yArr=loadDataSet('C:\pythonProject\机器学习\回归算法\局部线性回归\ex0.txt')
xArr1,yArr1=loadDataSet('C:\pythonProject\机器学习\回归算法\局部线性回归\ex1.txt')
plot_w_figure(xArr,yArr,k=0.01)
plot_w_figure(xArr1,yArr1,k=0.01)
原文地址:https://blog.csdn.net/qq_58602552/article/details/144061030
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!