上述代码仍然报错:shapes (2,) and (3,) not aligned: 2 (dim 0) != 3 (dim 0)
时间: 2023-12-08 16:04:10 浏览: 26
这个错误是由于第二层全连接层的权重矩阵W2的形状与第一层全连接层的输出向量a1的形状不匹配导致的。W2的形状是(3,2),而a1的形状是(3,),两者的第一个维度不匹配。可以将a1的形状修改为(1,3)或者将W2的形状修改为(2,3)来解决这个错误。以下是两种修改方法的代码:
方法1:将a1的形状修改为(1,3)
```python
import numpy as np
def dense(a_in, W, b, g):
units = W.shape[0]
a_out = np.zeros(units)
for j in range(units):
w = W[j]
z = np.dot(w, a_in.T) + b[j]
a_out[j] = g(z)
return a_out
def sequential(x):
W1 = np.array([[1,-3,5], [2,4,-6]])
b1 = np.array([-1,1,2])
W2 = np.array([[-1,2], [3,-4], [-5,6]])
b2 = np.array([2,-2])
W3 = np.array([[-2,1], [3,-4]])
b3 = np.array([1,-2])
W4 = np.array([[3,-1]])
b4 = np.array([-2])
a_in = x.reshape((1,-1))
a1 = dense(a_in, W1, b1, np.tanh)
a1 = a1.reshape((1,-1))
a2 = dense(a1, W2, b2, np.tanh)
a3 = dense(a2, W3, b3, np.tanh)
a4 = dense(a3, W4, b4, np.tanh)
f_x = a4
return f_x
a_in = np.array([-2, 4])
print(sequential(a_in))
```
方法2:将W2的形状修改为(2,3)
```python
import numpy as np
def dense(a_in, W, b, g):
units = W.shape[0]
a_out = np.zeros(units)
for j in range(units):
w = W[j]
z = np.dot(w, a_in) + b[j]
a_out[j] = g(z)
return a_out
def sequential(x):
W1 = np.array([[1,-3,5], [2,4,-6]])
b1 = np.array([-1,1,2])
W2 = np.array([[-1,3,-5], [2,-4,6]])
b2 = np.array([2,-2])
W3 = np.array([[-2,1], [3,-4]])
b3 = np.array([1,-2])
W4 = np.array([[3,-1]])
b4 = np.array([-2])
a1 = dense(x, W1, b1, np.tanh)
a2 = dense(a1, W2, b2, np.tanh)
a3 = dense(a2, W3, b3, np.tanh)
a4 = dense(a3, W4, b4, np.tanh)
f_x = a4
return f_x
a_in = np.array([-2, 4])
print(sequential(a_in))
```