小白tensorflow学习中遇到的问题

来源:互联网 发布:java实施是做什么的 编辑:程序博客网 时间:2024/06/05 10:16

1.野生图片输入网络

im = matplotlib.image.imread(path)#im=rgb2gray(im)im=np.reshape(im,(1,28,28,3))im=tf.image.convert_image_dtype(im,tf.float32)#print(im)regularizer=tf.contrib.layers.l2_regularizer(0.1)y=inference.inference(im,0,regularizer)

2.查看张量中的数据
with tf.Session() as sess:    sess.run(tf.initialize_all_variables())    print(sess.run(y))

3.多次调用

for _ in range(batch_size):    label_index=random.randrange(n_class)    label_name=list(image_lists.keys())[label_index]    image_index=random.randrange(65536)    prediciton=classify(image_lists, label_name, label_index, 'training')

classify在for中多次使用,这时涉及的变量需要设置reuse

 with tf.variable_scope('layer1-conv1',reuse=tf.AUTO_REUSE):


4.grountruth是数组的话,不能直接和张量求交叉熵,需要用占位符

    tensor_ground=tf.placeholder(tf.float32,[None,5],name='gg')    logits, groundtruths = get_set_groundtruths(image_lists, category)    cross_entropy=tf.nn.softmax_cross_entropy_with_logits(labels=tensor_ground,logits=logits)    cross_entropy_mean=tf.reduce_mean(cross_entropy)    train_step=tf.train.GradientDescentOptimizer(0.01)\                 .minimize(cross_entropy_mean)    with tf.Session() as sess:        sess.run(tf.global_variables_initializer())        sess.run(cross_entropy,feed_dict={tensor_ground:groundtruths})


5.会话窗口中插入预测函数时,显示某层权值没有初始化问题~个人认为初始化操作是初始化,在会话窗口前出现的变量,因为在打开会话窗口前要保证调用一次前向传播

get_set_groundtruths(image_lists, 'training')with tf.Session() as sess:    init=tf.global_variables_initializer()    sess.run(init)    for i in range(2):      logits, ground_truths = get_set_groundtruths(image_lists, 'training')

6.在使用tf.equal计算正确率的时候,equal判断出错的问题

ground = tf.placeholder(tf.float32, [None, 5], name='cm')pre, truths = get_set_groundtruths(image_lists, 'testing',1)erro=tf.equal(tf.argmax(pre,1),tf.argmax(ground,1))accuracy =tf.reduce_mean(tf.cast(erro,tf.float32))
print(sess.run(accuracy,feed_dict={ground:truths}))
原因在于pre是[[……]]的格式,使用tf.argmax()并不是得到期望的最大值索引,而是[……]应改为pre[0],即
erro=tf.equal(tf.argmax(pre[0],1),tf.argmax(ground,1))
7.承接上面提到的问题,当我的测试batch不是1的时候,由于pre是[[……],[……],[……]……[……]]的形式,所以无法直接使用tf.argmax,必须先从每个小的[]里选出索引,因此
pre, truths = get_set_groundtruths(image_lists, 'testing',100)erro_pre=[]for j in range(100):          erro_pre.append(tf.argmax(pre[j],1))erro_pre = tf.reshape(erro_pre, (1, 100))
这样的得到的erro_pre是[[index],[index],[index]……[index]],接着我们再给他tf.reshape后得到[index,index,index……,index]
格式上就和tf.argmax(ground,1)一致了,这时才能使用tf.equal()
pre, truths = get_set_groundtruths(image_lists, 'testing',100)erro_pre=[]for j in range(100):         erro_pre.append(tf.argmax(pre[j],1))erro_pre = tf.reshape(erro_pre, (1, 100))erro=tf.equal(erro_pre[0],tf.argmax(ground,1))accuracy =tf.reduce_mean(tf.cast(erro,tf.float32))print(sess.run(accuracy,feed_dict={ground:truths}))print(sess.run(erro_pre[0]))print(sess.run(tf.argmax(ground,1),feed_dict={ground:truths}))




 
原创粉丝点击