当我呈现新的时,我试图从我的训练模型中打印每个类结果的预测概率原始数据。这是一个多类分类问题,有8个输出和21个输入。
当我呈现新数据时,我能够打印1个结果,例如:
"Example 0 prediction: 1 (15.0%)"
相反,我希望看到类似于下面的内容。其中,每个类别(0,1,2,3,4,6,Wide, Out)的概率为:
Example 0 prediction 0: (12.5%), prediction 1: (12.5%), prediction 2: (12.5%), prediction 3: (12.5%), prediction 4: (12.5%), prediction 6: (12.5%), prediction Wide: (12.5%), prediction Out: (12.5%)
请注意,我已经尝试搜索类似的问题,包括这里,这里和这里,以及咨询TensorFlow文档。然而,这些主要讨论对模型本身的改变,例如最后一层的softmax激活,分类交叉熵作为损失函数等,以便生成概率。
我已经包含了模型体系结构以及预测代码以实现完全可见性。
模型:
earlystopping = callbacks.EarlyStopping(monitor ="val_loss",
mode ="min", patience = 125,
restore_best_weights = True)
#define Keras
model = Sequential()
model.add(Dense(50, input_dim=21))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.5,input_shape=(50,)))
model.add(Dense(50))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.5,input_shape=(50,)))
model.add(Dense(8, activation='softmax'))
#compile the keras model
model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])
model.fit(X, dummy_y, validation_split=0.25, epochs=1000, batch_size=100, verbose=1, callbacks=[earlystopping])
_, accuracy3 = model.evaluate(X, dummy_y, verbose=0)
print('Accuracy: %.2f' % (accuracy3*100))
进行预测:
class_names = ['0', '1', '2','3','4','6','Wide','Out']
predict_dataset = tf.convert_to_tensor([
[1,5,1,0.459,0.322,0.041,0.002,0.103,0.032,0.041,14,0.404,0.284,0.052,0.008,0.128,0.044,0.037,0.043,54,0,],
[1,18,5,0.512,0.286,0,0,0.083,0.024,0.095,13,0.24,0.44,0.08,0,0.08,0.08,0,0.08,173,3],
[2,11,13,0.5,0.417,0,0,0.083,0,0.083,82,0.35,0.36,0.042,0.003,0.135,0.039,0.051,0.02,51,7]
])
predictions = model(predict_dataset, training=False)
for i, logits in enumerate(predictions):
class_idx = tf.argmax(logits).numpy()
p = tf.nn.softmax(logits)[class_idx]
name = class_names[class_idx]
print("Example {} prediction: {} ({:4.1f}%)".format(i, name,100*p))
输出:Example 0 prediction: 1 (15.0%)
Example 1 prediction: 1 (16.0%)
Example 2 prediction: 0 (16.9%)
我已经尝试改变使用TensorFlow的logits的for循环,但我仍然无法让它打印每个结果和相关的概率。
任何指导都是非常感谢的。
最后,我没有尝试实现For循环,而是直接打印numpy数组的每个结果。
不是最干净的方法,但它完成了任务。希望将来对别人有用。
predict_dataset = tf.convert_to_tensor([
[1,5,1,0.459,0.322,0.041,0.002,0.103,0.032,0.041,14,0.404,0.284,0.052,0.008,0.128,0.044,0.037,0.043,54,0,155]
])
predictions = model3(predict_dataset, training=False)
predictions2 = predictions.numpy()
prob_0 = predictions2[0,0]
prob_1 = predictions2[0,1]
prob_2 = predictions2[0,2]
prob_3 = predictions2[0,3]
prob_4 = predictions2[0,4]
prob_wide = predictions2[0,5]
prob_6 = predictions2[0,6]
prob_wicket = predictions2[0,7]
print(prob_0)
print(prob_1)
print(prob_2)
print(prob_3)
print(prob_4)
print(prob_wide)
print(prob_6)
print(prob_wicket)
输出0.28349978
0.32451397
0.06382967
0.0053077294
0.20397986
0.07999096
6.386134e-08
0.038877998