偏导数线性回归的随机梯度下降

时间:2018-05-14 10:52:00

标签: python pandas numpy gradient-descent

我通过考虑偏导数(df / dm)和(df / db)来手动实现线性回归的随机梯度下降

目标是我们必须随机选择w0(权重)然后收敛它们。 由于这是随机的,我们必须在每次运行中获取数据集的样本

学习率最初应为1,每次运行后应减少2 所以当wK + 1等于wK(k = 1,2,3,......)时,循环应该停止

这是在Sklearn的波士顿数据集中实现的

因为我是python的新手并没有使用函数 以下是代码:

r= 1
m_deriv = 0
b_deriv = 0
learning_rate = 1
it = 1
w0_random = np.random.rand(13)
w0 = np.asmatrix(w0_random).T
b = np.random.rand()
b0 = np.random.rand()
while True:
    df_sample = bos.sample(100)

    price = df_sample['price']

    price = np.asmatrix(price)

    xi = np.asmatrix(df_sample.drop('price',axis=1))

    N = len(xi)

    for i in range(N):
   # -2x * (y-(mx +b))     
        m_deriv += np.dot(-2*xi[i].T , (price[:,i] - np.dot(xi[i] , w0_random) + b))

    # -2(y - (mx + b))
        b_deriv += -2*(price[:,i] - (np.dot(xi[i] , w0_random) + b))

    w0_new = m_deriv * learning_rate
    b0_new = b_deriv * learning_rate
    w1 = w0 - w0_new
    b1 = b0 - b0_new

    it += 1
    if (w0==w1).all():
        break
    else:
        w0 = w1
        b0 = b1
        learning_rate = learning_rate/2

当循环运行时,我得到w和b的大值。它们没有正确收敛 循环出错的地方因此导致更高的值以及如何解决它。

2 个答案:

答案 0 :(得分:2)

在上述情况下,在对StandardScaler进行处理之前使用xi可获得良好的效果,并使用w1而不是w0_random

from sklearn.preprocessing import StandardScaler
import numpy as np
bos['PRICE'] = boston.target
X = bos.drop('PRICE', axis = 1)
Y = bos['PRICE']
df_sample =X[:100]
price =Y[:100]
xi_1=[]
price_1=[]
N = len(df_sample)
for j in range(N):
    scaler = StandardScaler()
    scaler.fit(df_sample) 
    xtrs = scaler.transform(df_sample)
    xi_1.append(xtrs)
    yi=np.asmatrix(price)
    price_1.append(yi)
#print(price_1)
#print(xi_1)
xi=xi_1   
price=price_1
r= 1
m_deriv = 0
b_deriv = 0
learning_rate = 1
it = 1
w0_random = np.random.rand(13)
w0 = np.asmatrix(w0_random).T
b = np.random.rand()
b0 = np.random.rand() 
while True:
   for i in range(N):
       # -2x * (y-(mx +b))
       w1=w0
       b1=b0
       m_deriv = np.dot(-2*xi[i].T , (price[i] - np.dot(xi[i] , w1) + b1))
       # -2(y - (mx + b))
       b_deriv = -2*(price[i] - (np.dot(xi[i] , w1) + b1))
   w0_new = m_deriv * learning_rate
   b0_new = b_deriv * learning_rate
   w1 = w0 - w0_new
   b1 = b0 - b0_new
   it += 1
   if (w0==w1).all():
       break
   else:
       w0 = w1
       b0 = b1
       learning_rate = learning_rate/2
print("m_deriv=",m_deriv)
print("b_driv",b_deriv) 

答案 1 :(得分:1)

每次迭代后,您都不会更新w系数。在你的内循环中,你总是使用w0_random,而你应该在你的情况下使用更新的权重w1。您需要在每次迭代后存储更新的值w1,以便在下一次迭代中使用它们来计算导数。

我还建议您将数据标准化为mean=0std=1,以避免大数字。

算法收敛主要是因为学习率在一些迭代后变得非常小,因此默认为w1==w0-learing_rate*diff*derivative。它不会收敛,因为它找到了当前形式的解决方案。

相关问题