神经网络:np阵列的整形

2024-05-02 12:17:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在学习这个神经网络教程:https://medium.com/analytics-vidhya/neural-networks-for-digits-recognition-e11d9dff00d5

该网络有1个隐藏层和25个神经元。我想尝试将隐藏层中不同数量的神经元改为10个。我尝试改变hidden_layer_size并塑造theta1theta2

最初theta1的大小是25x401,我把它改成了10x401 theta2的大小是10x26,我把它改成了10x11 small diagram

错误是: ValueError: cannot reshape array of size 3690 into shape (10,401)

如何重塑阵列以使网络正常运行?(隐藏层中的神经元数量可更改)

代码重塑用于:

def nnCostFunc(nn_params, input_layer_size, hidden_layer_size, num_labels, X, y, lmbda):
theta1 = np.reshape(nn_params[:hidden_layer_size*(input_layer_size+1)],
                    (hidden_layer_size, input_layer_size+1), 'F')
theta2 = np.reshape(
    nn_params[hidden_layer_size*(input_layer_size+1):], (num_labels, hidden_layer_size+1), 'F')

m = len(y)
ones = np.ones((m, 1))
a1 = np.hstack((ones, X))
a2 = sigmoid(a1 @ theta1.T)
a2 = np.hstack((ones, a2))
h = sigmoid(a2 @ theta2.T)

y_d = pd.get_dummies(y.flatten())

temp1 = np.multiply(y_d, np.log(h))
temp2 = np.multiply(1-y_d, np.log(1-h))
temp3 = np.sum(temp1 + temp2)

sum1 = np.sum(np.sum(np.power(theta1[:, 1:], 2), axis=1))
sum2 = np.sum(np.sum(np.power(theta2[:, 1:], 2), axis=1))

return np.sum(temp3 / (-m)) + (sum1 + sum2) * lmbda / (2*m)

Tags: 网络layera2inputsize数量npones