获取 TensorFlow 的概率

数据挖掘 机器学习 神经网络 深度学习 张量流 美国有线电视新闻网
2022-03-03 22:46:30

嗨,我正在使用此处的代码研究用于 cifar-10 图像分类的 tensorflow

1个回答

我想问你如何预测测试图像中每个类别的概率。

train.py的第 27 行,您有以下代码:

correct_prediction = tf.equal(y_pred_cls, tf.argmax(y, axis=1))

它试图找出预测值是否与真实值相同。您可以运行 y_pred_cls 来查看每个类对于您所需输入的概率。

我想使用代码来预测新数据标签的概率,如何保存和加载我们训练过的使用训练数据的模型。

为了保存您的模型及其权重,您可以查看此处正如您从那里看到的,您必须创建一个保护程序对象:

import tensorflow as tf

#Prepare to feed input, i.e. feed_dict and placeholders
w1 = tf.placeholder("float", name="w1")
w2 = tf.placeholder("float", name="w2")
b1= tf.Variable(2.0,name="bias")
feed_dict ={w1:4,w2:8}

#Define a test operation that we will restore
w3 = tf.add(w1,w2)
w4 = tf.multiply(w3,b1,name="op_to_restore")
sess = tf.Session()
sess.run(tf.global_variables_initializer())

#Create a saver object which will save all the variables
saver = tf.train.Saver()

#Run the operation by feeding input
print sess.run(w4,feed_dict)
#Prints 24 which is sum of (w1+w2)*b1 

#Now, save the graph
saver.save(sess, 'my_test_model',global_step=1000)

对于加载,您必须恢复它:

import tensorflow as tf

sess=tf.Session()    
#First let's load meta graph and restore weights
saver = tf.train.import_meta_graph('my_test_model-1000.meta')
saver.restore(sess,tf.train.latest_checkpoint('./'))


# Access saved Variables directly
print(sess.run('bias:0'))
# This will print 2, which is the value of bias that we saved


# Now, let's access and create placeholders variables and
# create feed-dict to feed new data

graph = tf.get_default_graph()
w1 = graph.get_tensor_by_name("w1:0")
w2 = graph.get_tensor_by_name("w2:0")
feed_dict ={w1:13.0,w2:17.0}

#Now, access the op that you want to run. 
op_to_restore = graph.get_tensor_by_name("op_to_restore:0")

print sess.run(op_to_restore,feed_dict)
#This will print 60 which is calculated 


编辑:其实代码有点奇怪,反正。以下部分:

tf.nn.softmax_cross_entropy_with_logits(logits=output, labels=y)

可以帮你。它输出每个类的概率。