tensorflow实现mnist分类InvalidArgumentError

发布于 2022-09-12 03:27:22 字数 3019 浏览 20 评论 0

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
import os
import scipy.misc

mnist=input_data.read_data_sets('MNIST_data/',one_hot=True)
'''
for i in range(20):

image_array=mnist.train.images[i,:]
image_array=image_array.reshape(28,28)
save_dir='MNIST_data/raw/'
if os.path.exists(save_dir) is False:
    os.makedirs(save_dir)
filename=save_dir+'mnist_train_%d.jpg' %i
scipy.misc.toimage(image_array,cmin=0,cmax=1).save(filename)

'''
x=tf.placeholder(tf.float32,shape=[None,784])
y=tf.placeholder(tf.float32,shape=[None,10])
x_image=tf.reshape(x,[-1,28,28,1])
def weight_variable(shape):

return tf.Variable(tf.truncated_normal(shape,stddev=0.1))

def bias_variable(shape):

return tf.Variable(tf.constant(0.1,shape=shape))

def conv2d(x,w):

return tf.nn.conv2d(x,w,strides=[1,1,1,1],padding='SAME')

def max_pool_2(value):

return tf.nn.max_pool(value,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')

w_conv1=weight_variable([5,5,1,32])
b_conv1=bias_variable([32])
h_conv1=tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)
h_pool=max_pool_2(h_conv1)

w_conv2=weight_variable([5,5,32,64])
b_conv2=bias_variable([64])
h_conv2=tf.nn.relu(conv2d(h_conv1,w_conv2)+b_conv2)
h_pool2=max_pool_2(h_conv2)

w_fc1=weight_variable([7764,1024])
b_fc1=bias_variable([1024])
h_pool2_flat=tf.reshape(h_pool2,[-1,7764])
h_fcl1=tf.nn.relu(tf.matmul(h_pool2_flat,w_fc1)+b_fc1)

keep_prob=tf.placeholder(tf.float32)
h_fcl1_drop=tf.nn.dropout(h_fcl1,keep_prob)
w_fc2=weight_variable([1024,10])
b_fc2=bias_variable([10])
z=tf.matmul(h_fcl1_drop,w_fc2)+b_fc2

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=z))
learning_rate=0.01
optimizer=tf.train.AdamOptimizer(learning_rate=0.01).minimize(cost)

correct_prediction=tf.equal(tf.argmax(z,1),tf.argmax(y,1))
train_step=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

sess=tf.InteractiveSession()
sess.run(tf.global_variables_initializer())

with tf.Session() as sess:

sess.run(tf.global_variables_initializer())
for i in range(20000):
    batch=mnist.train.next_batch(50)
    if i % 100 ==0:
        train_accuracy=train_step.eval(feed_dict={x:batch[0],y:batch[1],keep_prob: 1.0})
        print("step %d, training accuracy %g"%(i, train_accuracy))
    train_step.run(feed_dict={x: batch[0], y: batch[1], keep_prob: 0.5})

print ("test accuracy %g"%train_step.eval(feed_dict={
    x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0}))

InvalidArgumentError (see above for traceback): Incompatible shapes: [200] vs. [50]

 [[Node: Equal_3 = Equal[T=DT_INT64, _device="/job:localhost/replica:0/task:0/device:CPU:0"](ArgMax_6, ArgMax_7)]]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文