Skip to main content
 首页 » 编程设计

python之从 tensorflow 获取 top-k 预测

2025年05月04日31lautakyan007

我在机器学习方面相对较新,尤其是在实现算法方面。我正在使用 python 和 tensorflow 库来实现一个神经网络来训练一个大约有 20 个类的数据集。我能够成功训练并获得预测,但我有一个问题,

Is it possible to get top k classes along with their probabilities using tensorflow instead of just a single prediction?

如果可能,如何做到这一点?感谢您的指导。

更新 01: 我正在添加我正在做的事情的代码。因此,我构建了一个具有 3 层的神经网络,分别具有 tanh、sigmoid 和 sigmoid 作为隐藏层的激活函数和输出层的 softmax。训练和预测代码如下:

y_pred = None 
    with tf.Session() as sess: 
        sess.run(init) 
        for epoch in range(training_epochs):             
            # running the training_epoch numbered epoch 
            _,cost = sess.run([optimizer,cost_function],feed_dict={X:tr_features,Y:tr_labels}) 
            cost_history = np.append(cost_history,cost) 
        # predict results based on the trained model 
        y_pred = sess.run(tf.argmax(y_,1),feed_dict={X: ts_features}) 

现在 y_pred 是 ts_features 的每个测试示例的类标签列表。但不是为每个测试示例获得 1 个单一类别标签,我希望为每个示例获得前 k 个预测,每个 k-预测都伴随某种概率。

请您参考如下方法:

使用 tf.nn.top_k() :

top_k_values, top_k_indices = tf.nn.top_k(predictions, k=k) 

如果 predictions 是每个类别的概率向量(即 predictions[i] = 类别 i 的预测概率),则 top_k_values 将包含 predictions 中的 k 最高概率,top_k_indices 将包含这些概率的索引,即相应的类。


假设在您的代码中,y_ 是每个类的预测概率向量:

k = 3  # replace with your value 
# Instead of `y_pred`: 
y_k_probs, y_k_pred = sess.run( 
    tf.nn.top_k(y_, k=k), feed_dict={X: ts_features})