我正在嘗試繪制梯度下降的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)
損失 = 假設 - y
cost = np.sum(loss ** 2) / (2 * m)
cost_list.append(cost)
print("Iteration %d | Cost: %f" % (i, cost)
# 每個例子的平均梯度[/span]。
梯度 = np.dot(xTrans, loss) / m
# update # update
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。 應該如何編輯代碼呢
?uj5u.com熱心網友回復:
我用樣本資料試了一下你的代碼;
我試了一下你的代碼。
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 100
theta,cost_list=gradientDescent(x,y,bias,0.000001,len(df),numIterations)
plt.plot(list(range(numIterations)), cost_list, '-r')
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316561.html
標籤:
上一篇:梯度下降法收斂到初始值

