python - 具有两个特征的梯度下降计算特征空间

标签 python machine-learning linear-regression gradient-descent

我尝试计算形状线性回归的最佳权重 W[0] 和 W[1]:

prize=W0*dummy+W1*size

地点:

dummy=[1,1,1,1,1,1,1,1,1,1]
size=[500,550,620,630,665,700,770,880,920,1000]

目标功能(rental_prize)具有以下值:

rental_price=[320,380,400,390,385,410,480,600,570,620]

通过以下代码,我尝试计算 W0 和 W1,以便线性回归能够最佳地拟合数据。

# descriptive features
size=[500,550,620,630,665,700,770,880,920,1000]
dummy=[1,1,1,1,1,1,1,1,1,1]

# Vector which contains the descriptive features
features=[dummy,size]

# target feature
rental_price=[320,380,400,390,385,410,480,600,570,620]

# Set the learning rate alpha
alpha=0.002 

# Feature weight vector --> model=[W0,W1]
# Set initial values for W0 and W1
model=[0,0]

for i in range(len(model)):
    for j in range(100):
        errordelta=np.sum([(rental_price[x]-(model[0]*dummy[x]+model[1]*size[x]))*features[i][x] for x in range(len(size))])
        model[i]=model[i]+alpha*errordelta

print(model[0])
print(model[1])

395.09179229

nan

模型实际上应该为 W0 返回大约 6.47,为 W1 返回 0.62。如果我更改 alpha 的值以及初始权重和迭代 (j),模型仍然无法接近所需的值...

显然代码中一定有错误......

谁能帮帮我吗?

最佳答案

您的算法存在三个错误:

  • 我不知道你为什么要将绝对误差乘以特征值;这使得误差函数呈二次方,但您没有使用任何 sqrt 进行补偿。
  • 同样,您在权重调整之前也未能对误差量进行平均;这有效地将变化放大了等于训练行数的系数。
  • 您的循环顺序是相反的:您想要依次训练特征,每个迭代一次。您通过首先训练截距虚拟值,然后尝试将该值作为绝对值,然后训练斜率大小来完成此操作。您需要交替使用它们。

更新后(以及一些文本改进):

for j in range(100):
    for i in range(len(model)):
        errordelta  =  np.sum([(rental_price[x] -
                                 (model[0]*dummy[x] + model[1]*sqft[x])) 
                             for x in range(len(sqft))]) / len(sqft)
        print(model, errordelta)
        model[i]  =  model[i] + alpha*errordelta

print(" sqft coeff", model[0])
print("dummy coeff", model[1])

输出:

[0, 0] 455.5
[0.91100000000000003, 0] 454.589
[0.91100000000000003, 0.90917800000000015] -203.201283
[0.5045974339999999, 0.90917800000000015] -202.794880434
[0.5045974339999999, 0.50358823913200013] 90.649311554
[0.68589605710799573, 0.50358823913200013] 90.4680129309
...
[0.62996765105739105, 0.62870771575527662] -1.70530256582e-14
[0.62996765105739105, 0.62870771575527662] -1.70530256582e-14
 sqft coeff 0.629967651057
dummy coeff 0.628707715755

关于python - 具有两个特征的梯度下降计算特征空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49075305/

相关文章:

python - 在python中运行excel宏并保存结果

python - 计算不在列表中的列表项时打印 0

javascript - D3 从 Python 函数获取数据

Python - 将数组拆分为多个数组

python - Keras `fit_generator` 验证准确度低,但 `fit` 验证准确度低

machine-learning - 低估和高估的不同成本

python - 如何扩展CNN来识别更多物体?

python - 类型错误 : _reshape_dispatcher() missing 1 required positional argument: 'newshape'

matlab - 如何在 MATLAB 中扩展最佳拟合线(polyfit)以在零处穿过 y 轴

R:具有 N 个特征的线性回归