使用tensorflow读取mnist
import tensorflow
as tf
import matplotlib
.pyplot
as plt
''' 读取MNIST数据方法一'''
from tensorflow
.examples
.tutorials
.mnist
import input_data
mnist
= input_data
.read_data_sets
('MNIST_data',one_hot
=True)
'''1)获得数据集的个数'''
train_nums
= mnist
.train
.num_examples
validation_nums
= mnist
.validation
.num_examples
test_nums
= mnist
.test
.num_examples
print('MNIST数据集的个数')
print(' >>>train_nums=%d' % train_nums
,'\n',
'>>>validation_nums=%d'% validation_nums
,'\n',
'>>>test_nums=%d' % test_nums
,'\n')
'''2)获得数据值'''
train_data
= mnist
.train
.images
val_data
= mnist
.validation
.images
test_data
= mnist
.test
.images
print('>>>训练集数据大小:',train_data
.shape
,'\n',
'>>>一副图像的大小:',train_data
[0].shape
)
'''3)获取标签值label=[0,0,...,0,1],是一个1*10的向量'''
train_labels
= mnist
.train
.labels
val_labels
= mnist
.validation
.labels
test_labels
= mnist
.test
.labels
print('>>>训练集标签数组大小:',train_labels
.shape
,'\n',
'>>>一副图像的标签大小:',train_labels
[1].shape
,'\n',
'>>>一副图像的标签值:',train_labels
[0])
'''4)批量获取数据和标签【使用next_batch(batch_size)】'''
batch_size
= 100
batch_xs
,batch_ys
= mnist
.train
.next_batch
(batch_size
)
print('使用mnist.train.next_batch(batch_size)批量读取样本\n')
print('>>>批量读取100个样本:数据集大小=',batch_xs
.shape
,'\n',
'>>>批量读取100个样本:标签集大小=',batch_ys
.shape
)
'''5)显示图像'''
plt
.figure
()
for i
in range(100):
im
= train_data
[i
].reshape
(28,28)
im
= batch_xs
[i
].reshape
(28,28)
plt
.imshow
(im
,'gray')
plt
.pause
(0.0000001)
plt
.show
()
next_batch()函数:
其中,mnist.train.next_batch() 函数包含一个参数 BATCH_SIZE,表示随即从训练集中抽取 BATCH_SIZE 个样本输入神经网络,并将样本的像素值和标签分别赋给 xs 和 ys。
在本例中,BATCH_SIZE 设置为200,表示一次将200个样本的像素值和标签分别赋值给 xs 和 ys ,故 xs 的形状为(200,784),对应的ys的形状为(200,10)。
基于批处理的代码实现
import numpy
as np
x
,t
= get_data
()
network
= init_network
batch_size
= 100
accuracy_cnt
= 0
for i
in range(0, len(x
), batch_size
)
x_batch
= x
[i
:i
+batch_size
]
y_batch
= predict
(network
, x_batch
)
p
= np
.argmax
(y_batch
, axis
=1)
accuracy_cnt
+= np
.sum(p
== t
[i
:i
+batch_size
])
print("Accuracy" + str(float(accuracy_cnt
) / len(x
)))