对于在Mxnet中使用GluonCV模型进行图像分类,我是通过网络转换图像来获得所有ImageNet类的预测概率。
def predict_probabilities(network, data):
"""
Should return the predicted probabilities of ImageNet classes for the given image.
:param network: pre-trained image classification model
:type network: mx.gluon.Block
:param data: batch of transformed images of shape (1, 3, 224, 224)
:type data: mx.nd.NDArray
:return: array of probabilities of shape (1000,)
:rtype: mx.nd.NDArray
"""
# YOUR CODE HERE
data=transform_image("")
pred_probas= network(data)
pred_probas=pred_probas[0]
return pred_probas
我必须满足这些论断。
assert pred_probas.shape == (1000,)
np.testing.assert_almost_equal(pred_probas.sum().asscalar(), 1, decimal=5)
assert pred_probas.dtype == np.float32
虽然我得到了这个错误。
AssertionError Traceback (most recent call last)
<ipython-input-10-70779066d528> in <module>
1 pred_probas =
predict_probabilities(network, transformed_test_output)
2 assert
pred_probas.shape == (1000,)
----> 3
np.testing.assert_almost_equal(pred_probas.sum().asscalar(), 1, decimal=5)
4 assert pred_probas.dtype == np.float32
/usr/local/lib/python3.7/dist-
packages/numpy/testing/_private/utils.py in assert_almost_equal(actual, desired,
decimal, err_msg, verbose)
599 pass
600 if abs(desired -
actual) >= 1.5 * 10.0**(-decimal):
--> 601 raise
AssertionError(_build_err_msg())
602
603
AssertionError:
Arrays are
not almost equal to 5 decimals
ACTUAL: 314.64026
DESIRED: 1
我怎样才能克服这个问题?
当你通过你的预训练网络对图像数据进行正向传递后,即:你必须将预测值映射到你的网络中。pred_probas= network(data)
你必须通过 softmax 将预测值映射到概率上。
prob = mx.nd.softmax(pred_probas)
然后返回 prob[0]
由于应用了 softmax,输出将在 0:1 的范围内,因此您的 np.testing.assert_almost_equal(pred_probas.sum().asscalar(), 1, decimal=5)
将满足 pred_probas.sum().asscalar()
将几乎等于1