記錄一個自己放的小錯誤,python程式設計的,要注意同名變數!!!
阿新 • • 發佈:2018-11-14
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import numpy as np import matplotlib.pyplot as plt tf.set_random_seed(1) np.random.seed(1) BATCH_SIZE = 50 LR = 0.001 mnist = input_data.read_data_sets('./mnist', one_hot=True) test_x=mnist.test.images[:2000] test_y=mnist.test.labels[:2000] print(mnist.train.images.shape)#(55000, 784) print(mnist.train.labels.shape)#(55000, 10) plt.imshow(mnist.train.images[1].reshape((28,28)),cmap='gray') plt.title('%i' % np.argmax(mnist.train.labels[1])) #plt.show() tf_x=tf.placeholder(tf.float32,[None, 28*28])/255 ########################%%% image=tf.reshape(tf_x, [-1, 28, 28, 1]) ########################%%% tf_y=tf.placeholder(tf.int32, [None, 10]) conv1=tf.layers.conv2d( inputs=image, filters=16, kernel_size=5, strides=1, padding='same', activation=tf.nn.relu ) #(28,28,16) pool1=tf.layers.max_pooling2d( inputs=conv1, pool_size=2, strides=2 ) #(14,14,16) conv2=tf.layers.conv2d(pool1, 32, 5, 1, 'same', activation=tf.nn.relu) #(14,14,32) pool2=tf.layers.max_pooling2d(conv2, 2, 2) #(7,7,32) flat=tf.reshape(pool2, [-1, 7*7*32]) output=tf.layers.dense(flat, 10) accuracy=tf.metrics.accuracy(labels=tf.argmax(tf_y, axis=1), predictions=tf.argmax(output, axis=1))[1] loss=tf.losses.softmax_cross_entropy(onehot_labels=tf_y, logits=output) train_op=tf.train.AdamOptimizer(LR).minimize(loss) init_op=tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) #b_x:(50, 784) , b_y: (50, 10) with tf.Session() as sess: sess.run(init_op) for step in range(600): b_x, b_y=mnist.train.next_batch(BATCH_SIZE) _, loss_=sess.run([train_op, loss], {tf_x:b_x, tf_y:b_y}) if step % 50 == 0: accuracy_, flat_representation=sess.run([accuracy, flat], {tf_x: test_x, tf_y: test_y}) print('Step: ', step, '| train loss: %.4f' % loss_, '| test accuracy: %.2f' % accuracy_) '''sess=tf.Session() sess.run(init_op) for step in range(600): b_x, b_y = mnist.train.next_batch(BATCH_SIZE) _, loss_ = sess.run([train_op, loss], {tf_x: b_x, tf_y: b_y}) if step % 50 == 0: accuracy_, flat_representation = sess.run([accuracy, flat], {tf_x: test_x, tf_y: test_y}) print('Step:', step, '| train loss: %.4f' % loss_, '| test accuracy: %.2f' % accuracy_)
程式設計的時候,我把accuracy_寫成了accuracy,loss_寫成了loss,不小心與上面的operation同名了,總是出現下面的錯誤
TypeError: Fetch argument 2.2956235 has invalid type <class 'numpy.float32'>, must be a string or Tensor. (Can not convert a float32 into a Tensor or Operation.)
找了好一會兒都找不到,錯誤在哪,所以以後一定要注意這個問題。