python - 偏导数线性回归的随机梯度下降
问题描述
我通过考虑偏导数(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 的大值。它们没有正确收敛循环出错的地方,因此导致更高的值以及如何解决它。
解决方案
在上述情况下,使用StandardScaler
before processing onxi
会产生良好的效果并使用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)
推荐阅读
- python - 通过 FFT 计算数值导数 - SciPy
- asp.net-core - Razor foreach 将属性/变量名称放在 id、name 和 *for 呈现的 HTML 中的属性
- api - 我如何通过 Google Play Developer API 获取在我的应用中购买的所有产品的列表
- c - 我的程序在编译后第一次运行时运行缓慢,然后很快。如果我再次编译它,它在第一次运行时再次运行缓慢,而在其他运行时运行速度很快
- asp.net-mvc - 在 ASP.NET MVC 5 的 UseCookieAuthentication() 中使用 cookieless 或 session-cookie
- three.js - 三.js奇怪的工件重叠框和平面
- go - 带参数的 Dialogflow 响应
- wordpress - 如何在联系表格 7 中手动发送电子邮件
- javascript - 在对 Express node.js 应用程序进行单元测试时如何模拟 Redis?
- jointjs - 在快速框架中。使用 fromJSON 方法重新创建时,链接元素无法指向端口