Currently available mnist_dataset downloads

[in]
[Note] Change the value of the one_hot parameter as needed

import tensorflow as tf

# Import MINST data
tf.logging.set_verbosity(tf.logging.ERROR)#不显示错误信息
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=False,
                                  source_url='http://yann.lecun.com/exdb/mnist/')

[out]
insert image description here

For model training, it is often prompted that the data format of MNIST_DATA is incorrect. In this case, the data needs to be converted to onehot encoding.

# Start training
with tf.Session() as sess:
    sess.run(init)

    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            #print(type(batch_ys))
            batch_ys=tf.one_hot(batch_ys,10,on_value=1,off_value=None,axis=0)
            #将tensor向量转换为numpy数组
            sess.run(tf.global_variables_initializer())
            batch_ys = batch_ys.eval(session=sess).T
            #print(type(batch_ys))
            # Fit training using batch data
            _, c = sess.run([optimizer, cost], feed_dict={
    
    x: batch_xs,
                                                          y: batch_ys})
            
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            print ("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))

    print ("Optimization Finished!")

    # Test model
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    # Calculate accuracy for 3000 examples
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print ("Accuracy:", accuracy.eval({
    
    x: mnist.test.images[:3000], y: mnist.test.labels[:3000]}))

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326318668&siteId=291194637