关于Michael Nielsen著作中feedforward函数的功能困惑求解
Hey there! Let's unpack this confusing behavior you're seeing—it's all about input shapes, I promise!
The Core Issue: Input Shape Differences
Your feedforward function works exactly as intended, but the problem lies in how you're passing input when testing manually versus how the evaluate function uses the test data:
In the
evaluatefunction: Eachxfromtest_datais a flattened 1D array representing a single image. For example, if your input layer maps to 30 features,xwill have a shape like(30,). When you pass this tofeedforward:a = sigmoid(np.dot(w, a)+b)The output layer's weight matrix
wis shaped(10, 30)(10 classification neurons, 30 input features). The dot productnp.dot(w, a)produces a 1D array of shape(10,), which is exactly the 10-class output you expect.np.argmaxthen picks the index (0-9) of the highest activation, matching your classification goal.In your manual test: You're passing an
imagethat's a 2D array instead of a flattened 1D array. From your output being10×30, it looks like your inputimagehas a shape like(30, 30)—either 30 separate images each with 30 features, or an unflattened 30×30 image. When you runfeedforwardon this:np.dot(w, a)(withwas(10, 30)) will produce a(10, 30)array—each column corresponds to the 10-class output for one of the 30 input samples/features.- When you call
np.argmax(test)without specifying an axis, NumPy flattens the entire 2D array into a 1D array of 300 elements, so the index returned will be between 0-299 instead of 0-9.
How to Fix Your Manual Test
To get the expected 0-9 output when testing a single image:
- Flatten your input image into a 1D array first:
flattened_image = image.flatten() # or image.reshape(-1) test = net.feedforward(flattened_image) print(np.argmax(test)) # Now returns 0-9 as expected - If you're intentionally testing a batch of images, specify the axis in
np.argmaxto get per-sample results:# For a (10, 30) output array (30 samples, 10 classes each) predictions = np.argmax(test, axis=0) # Returns an array of 30 elements (0-9)
内容的提问来源于stack exchange,提问作者Guenterino

