本代码在Ubuntu下测试,MNIST_data下放MNIST四个压缩包。,Win下报“cannot import name ‘mnist’”。
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
sess = tf.InteractiveSession()
print (" tpye of 'mnist' is %s" % (type(mnist)))
print (" number of trian data is %d" % (mnist.train.num_examples))
print (" number of test data is %d" % (mnist.test.num_examples))
print ("What does the data of MNIST look like?")
trainimg = mnist.train.images
trainlabel = mnist.train.labels
testimg = mnist.test.images
testlabel = mnist.test.labels
print
print (" type of 'trainimg' is %s" % (type(trainimg)))
print (" type of 'trainlabel' is %s" % (type(trainlabel)))
print (" type of 'testimg' is %s" % (type(testimg)))
print (" type of 'testlabel' is %s" % (type(testlabel)))
print (" shape of 'trainimg' is %s" % (trainimg.shape,))
print (" shape of 'trainlabel' is %s" % (trainlabel.shape,))
print (" shape of 'testimg' is %s" % (testimg.shape,))
print (" shape of 'testlabel' is %s" % (testlabel.shape,))
print ("How does the training data look like?")
nsample = 5
randidx = np.random.randint(trainimg.shape[0], size=nsample)
for i in randidx:
curr_img = np.reshape(trainimg[i, :], (28, 28)) # 28 by 28 matrix
curr_label = np.argmax(trainlabel[i, :] ) # Label
plt.matshow(curr_img, cmap=plt.get_cmap('gray'))
plt.title("" + str(i) + "th Training Data "
+ "Label is " + str(curr_label))
print ("" + str(i) + "th Training Data "
+ "Label is " + str(curr_label))
plt.show()
# Batch Learning?
print ("Batch Learning? ")
batch_size = 100
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
print ("type of 'batch_xs' is %s" % (type(batch_xs)))
print ("type of 'batch_ys' is %s" % (type(batch_ys)))
print ("shape of 'batch_xs' is %s" % (batch_xs.shape,))
print ("shape of 'batch_ys' is %s" % (batch_ys.shape,))
运行结果:
tpye of 'mnist' is <class 'tensorflow.contrib.learn.python.learn.datasets.base.Datasets'>
number of trian data is 55000
number of test data is 10000
What does the data of MNIST look like?
type of 'trainimg' is <type 'numpy.ndarray'>
type of 'trainlabel' is <type 'numpy.ndarray'>
type of 'testimg' is <type 'numpy.ndarray'>
type of 'testlabel' is <type 'numpy.ndarray'>
shape of 'trainimg' is (55000, 784)
shape of 'trainlabel' is (55000, 10)
shape of 'testimg' is (10000, 784)
shape of 'testlabel' is (10000, 10)
How does the training data look like?
34952th Training Data Label is 5
50872th Training Data Label is 4
1890th Training Data Label is 4
54315th Training Data Label is 3
34219th Training Data Label is 8
Batch Learning?
type of 'batch_xs' is <type 'numpy.ndarray'>
type of 'batch_ys' is <type 'numpy.ndarray'>
shape of 'batch_xs' is (100, 784)
shape of 'batch_ys' is (100, 10)
期间会显示一些示例图片,例如