簡體   English   中英

ValueError: x 和 y 必須具有相同的第一維,但具有形狀 (101,) 和 (100,)

[英]ValueError: x and y must have same first dimension, but have shapes (101,) and (100,)

我正在嘗試運行學習率,並收到此錯誤值錯誤:ValueError:x 和 y 必須具有相同的第一維,但具有形狀 (101,) 和 (100,)。 如果我使 y 101,它會給出一條直線

def g(x):
    return x**4 - 4*x**2 +5

def dg(x):
    return 4*x**3 - 8*x

def gradient_descent(derivative_func, initial_guess,multiplier=0.01,precision=0.0001, max_iter=500):

    new_x= initial_guess
    precision= 0.0001
    x_list= []
    slope_list= []

    for n in range(max_iter):

        previous_x= new_x
        gradient= derivative_func(previous_x) #The slope of the graph(Error)
        new_x= previous_x - multiplier *gradient #The Learning rate
        step_size= abs(new_x - previous_x)
        x_list.append(new_x)
        slope_list.append(derivative_func(new_x))
       # print (step_size)
        if step_size < precision:
            break
    return new_x, x_list, slope_list

n=100
local_min, list_x, deriv_list= gradient_descent(derivative_func=dg,initial_guess=0.1, multiplier=0.0005,precision=0.0001,max_iter=n)



#Plotting Reduction in cost for each iteration
plt.figure(figsize=[15,5])

plt.xlim(0,n)
plt.ylim(0,50)
plt.xlabel('Nr. of Iterations', fontsize= 16)
plt.ylabel('Cost', fontsize=16)
plt.title('Effect of Learning Rate', fontsize=16, c= 'g')

#Getting X-axis values:

iteration_list1= list(range(0,n+1))
iteration_list= np.array(iteration_list1)

#Getting y-axis values

low_values= np.array(list_x) 

plt.plot(iteration_list, g(low_values),linewidth=6,c='green')
plt.show()

首先,您必須具有相同的數組維度,因此更改此行:

iteration_list1= list(range(0,n+1))

iteration_list1= list(range(0,n))

然后,我認為您應該刪除該行

plt.ylim(0,50)

讓圖書館設置最佳 y 比例。 您會看到一條“直線”,因為變化非常小。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM