【发布时间】:2016-06-15 14:59:45
【问题描述】:
我正在尝试使用梯度下降来训练一些权重,但是我没有取得太大的成功。
我一开始的学习率lr 为 0.01,而我的成本实际上飞涨,这让我感到惊讶。我只能假设它还不足以找到任何局部最小值。将其更改为 0.0000000000001 使其稳定并足够缓慢地下降。
迭代 998 |费用:2444.995584
迭代 999 |费用:2444.995577
迭代 1000 |费用:2444.995571
最终权重:5.66633309647e-07 | 4.32179246434e-09
但是,这些权重或我绘制它们的方式有问题:
import numpy as np
import matplotlib.pyplot as plt
def gradient_descent(x, y, w, lr, m, iter):
xTrans = x.transpose()
for i in range(iter):
prediction = np.dot(x, w)
loss = prediction - y
cost = np.sum(loss ** 2) / m
print("Iteration %d | Cost: %f" % (i + 1, cost))
gradient = np.dot(xTrans, loss) / m # avg gradient
w = w - lr * gradient # update the weight vector
return w
# generate data from uniform distribution -10. +10 and linear function
x = np.arange(1, 200, 2)
d = np.random.uniform(-10, 10, x.size)
y = .4 * x + 3 + d
# number of training samples
m = y.size
# add a column of ones for bias values
it = np.ones(shape=(m, 2))
it[:, 1] = x
m, n = np.shape(it)
# initialise weights to 0
w = np.zeros(n)
iter = 1000 # number of iterations
lr = 0.0000000000001 # learning rate / alpha
trained_w = gradient_descent(it, y, w, lr, m, iter)
result = trained_w[1] * x + trained_w[0] # linear plot of our predicted function
print("Final weights: %s | %s" % (trained_w[1], trained_w[0]))
plt.plot(x, y, 'gx')
plt.plot(x, result)
plt.show()
【问题讨论】:
标签: python python-3.x numpy matplotlib machine-learning