我正在尝试绘制梯度下降的成本列表(cost_list)随Epoch的变化图,但当我尝试这样做时,我在基本的Python函数结构上遇到了困难。我附上了我正在尝试的代码结构。
def gradientDescent(x, y, theta, alpha, m, numIterations):
xTrans = x.T
cost_list=[]
for i in range(0, numIterations):
hypothesis = np.dot(x, theta)
loss = hypothesis - y
cost = np.sum(loss ** 2) / (2 * m)
cost_list.append(cost)
print("Iteration %d | Cost: %f" % (i, cost))
# 每个样本的平均梯度
gradient = np.dot(xTrans, loss) / m
# 更新
theta = theta - alpha * gradient
#a = plt.plot(i,theta)
return theta,cost_list
我正在尝试在每一步返回“cost_list”,创建一个成本列表,然后使用下面的代码行进行绘图。
theta,cost_list=gradientDescent(x,y,bias,0.000001,len(my dataframe),100)
plt.plot(list(range(numIterations)), cost_list, '-r')
但是它提示我错误,说numIterations未定义。代码应该做哪些可能的修改?
回答:
我使用样本数据尝试了你的代码;
df = pd.DataFrame(np.random.randint(1,50, size=(50,2)), columns=list('AB'))
x=df.A
y=df.B
bias = np.random.randn(50,1)
numIterations = 100
theta,cost_list=gradientDescent(x,y,bias,0.000001,len(df),numIterations)
plt.plot(list(range(numIterations)), cost_list, '-r')