【发布时间】:2020-01-22 16:30:08
【问题描述】:
很长一段时间后,我仍然无法在没有任何错误的情况下运行我的 nn。这个玩具 nn 的准确度是惊人的 1-2%(隐藏层中的 60 个神经元,100 个 epoch,0.3 学习率,tanh 激活,通过 TF 下载的 MNIST 数据集)——所以基本上它根本没有学习。看了这么久的视频/关于反向传播的帖子后,我仍然无法修复它。
所以我的错误必须在标有两条##### 行的部分之间。我认为我对衍生品的总体理解很好,但我无法将这些知识与反向传播联系起来。
如果反向传播基础是正确的,那么错误一定是axis = 0/1,因为我也无法理解,如何确定我将在哪个轴上工作。
另外,我有一种强烈的感觉,dZ2 = A2 - Y 可能是错的,应该是dZ2 = Y - A2,但是在更正之后,nn 开始只猜一个数字。
(是的,反向传播本身我没有写,我在网上找到的)
#importing data and normalizing it
#"x_test" will be my X
#"y_test" will be my Y
import tensorflow as tf
(traindataX, traindataY), (testdataX, testdataY) = tf.keras.datasets.mnist.load_data()
x_test = testdataX.reshape(testdataX.shape[0], testdataX.shape[1]**2).astype('float32')
x_test = x_test / 255
y_test = testdataY
y_test = np.eye(10)[y_test]
#Activation functions:
def tanh(z):
a = (np.exp(z)-np.exp(-z))/(np.exp(z)+np.exp(-z))
return a
###############################################################################START
def softmax(z):
smExp = np.exp(z - np.max(z, axis=0))
out = smExp / np.sum(smExp, axis=0)
return out
###############################################################################STOP
def neural_network(num_hid, epochs,
learning_rate, X, Y):
#num_hid - number of neurons in the hidden layer
#X - dataX - shape (10000, 784)
#Y - labels - shape (10000, 10)
#inicialization
W1 = np.random.randn(784, num_hid) * 0.01
W2 = np.random.randn(num_hid, 10) * 0.01
b1 = np.zeros((1, num_hid))
b2 = np.zeros((1, 10))
correct = 0
for x in range(1, epochs+1):
#feedforward
Z1 = np.dot(X, W1) + b1
A1 = tanh(Z1)
Z2 = np.dot(A1, W2) + b2
A2 = softmax(Z2)
###############################################################################START
m = X.shape[1] #-> 784
loss = - np.sum((Y * np.log(A2)), axis=0, keepdims=True)
cost = np.sum(loss, axis=1) / m
#backpropagation
dZ2 = A2 - Y
dW2 = (1/m)*np.dot(A1.T, dZ2)
db2 = (1/m)*np.sum(dZ2, axis = 1, keepdims = True)
dZ1 = np.multiply(np.dot(dZ2, W2.T), 1 - np.power(A1, 2))
dW1 = (1/m)*np.dot(X.T, dZ1)
db1 = (1/m)*np.sum(dZ1, axis = 1, keepdims = True)
###############################################################################STOP
#parameters update - gradient descent
W1 = W1 - dW1*learning_rate
b1 = b1 - db1*learning_rate
W2 = W2 - dW2*learning_rate
b2 = b2 - db2*learning_rate
for i in range(np.shape(Y)[1]):
guess = np.argmax(A2[i, :])
ans = np.argmax(Y[i, :])
print(str(x) + " " + str(i) + ". " +"guess: ", guess, "| ans: ", ans)
if guess == ans:
correct = correct + 1;
accuracy = (correct/np.shape(Y)[0]) * 100
【问题讨论】:
-
好的,感谢您的提示,但您能帮我进行反向传播吗?
-
反向传播非常很难做到正确。除非你真的需要这样做,否则我强烈建议使用那些已经花费无数时间对其进行调整以使其在各个方面都正确的人制作的软件包(不能保证它在各个方面实际上都是正确的,但至少它会起作用,大多数时候)。
标签: python neural-network backpropagation