在python代码中获取值错误

时间:2018-02-04 13:49:42

标签: python numpy machine-learning neural-network

我在函数nm_model中得到一个值错误但是在forward_propagation函数中A2的值是正确的我不明白为什么我会收到此错误。

import numpy as np
for i in range(0, num_iterations):

    # Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache".
    A2, cache = forward_propagation(X, parameters)

我在这里收到错误 这是我的错误

ValueError                                Traceback (most recent call last)
<ipython-input-132-7a346e8aefff> in <module>()
      1 X_assess, Y_assess = nn_model_test_case()
----> 2 parameters = nn_model(X_assess, Y_assess, 4, num_iterations=10000, print_cost=True)
      3 print("W1 = " + str(parameters["W1"]))
      4 print("b1 = " + str(parameters["b1"]))
      5 print("W2 = " + str(parameters["W2"]))

<ipython-input-131-e266bdc33aa9> in nn_model(X, Y, n_h, num_iterations, print_cost)
     33         ### START CODE HERE ### (≈ 4 lines of code)
     34         # Forward propagation. Inputs: "X, parameters". Outputs: "A2, cache".
---> 35         A2, cache = forward_propagation(X, parameters)
     36 
     37         # Cost function. Inputs: "A2, Y, parameters". Outputs: "cost".

<ipython-input-129-32057a9db96b> in forward_propagation(X, parameters)
     21     # Implement Forward Propagation to calculate A2 (probabilities)
     22     ### START CODE HERE ### (≈ 4 lines of code)
---> 23     Z1 = np.dot(W1, X) + b1
     24     A1 = np.tanh(Z1)
     25     Z2 = np.dot(W2, A1) + b2

ValueError: shapes (4,6) and (2,3) not aligned: 6 (dim 1) != 2 (dim 0)

2 个答案:

答案 0 :(得分:0)

在你的forward_propigation方法中,你获取数组W1和X的点积。这与使用2d数组的矩阵乘法相对应。这些数组的尺寸对于点积运算是不正确的,因此是错误的。

答案 1 :(得分:0)

错误是在初始化X.我使用X.size进行初始化,而不是当我尝试使用X.shape [0]时工作正常。