- 首先准备训练和测试数据:http://yann.lecun.com/exdb/mnist/
train-images-idx3-ubyte.gz: training set images (9912422 bytes) 55000张图片
train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
t10k-images-idx3-ubyte.gz: test set images (1648877 bytes) 10000张图片
t10k-labels-idx1-ubyte.gz: test set labels (4542 bytes)
保存在MNIST_data文件夹中
每一张图片包含28像素X28像素。我们可以用一个数字数组来表示这张图片:
我们把这个数组展开成一个向量,长度是 28x28 = 784。
因此,在MNIST训练数据集中,mnist.train.images
是一个形状为 [55000, 784]
的张量
相对应的标签MNIST数据集的标签是介于0到9的数字, "one_hot"是除了某一位的数字是1以外其余各维度数字都是0。
比如,标签0将表示成([1,0,0,0,0,0,0,0,0,0,0])。因此, mnist.train.labels
是一个 [60000, 10]
的数字矩阵。
- 现在,我们准备好可以开始构建我们的模型啦!
①定义网络层:add_layer,这个例子就没有引入黑盒啦。输入为784,输出为10。
函数内:随机生成W(权重:weight)[784,10], 随机生成b(偏置:biases)[10]。
层与层之间是通过 进行运算。其中
就是激励函数。
②成本函数:为了训练我们的模型,我们首先需要定义一个指标来评估这个模型是好的。其实,在机器学习,我们通常定义指标来表示一个模型是坏的,这个指标称为成本(cost)或损失(loss),然后尽量最小化这个指标。但是,这两种方式是相同的。
一个非常常见的,非常漂亮的成本函数是“交叉熵”(cross-entropy)。
我们可以用 计算交叉熵。
③训练:利用SGD(随机梯度下降)不断降低Cost,使模型达到最优解。
④计算模型预测准确性:compute_accuracy
将预测图片生成的[1,10]矩阵中最高的序号与图片标签比较相等,最终求出比例。
'''
需要翻墙或者下载指定文件到MINST_data文件夹
下载数据50000个
'''
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot= True)
#添加层
def add_layer(inputs, in_size, out_size, activation_function=None):
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
Wx_plus_b = tf.matmul(inputs, Weights) + biases
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
#计算预测准确度
def compute_accuracy(v_xs, v_ys):
global prediction
y_pre = sess.run(prediction, feed_dict={xs: v_xs})
#将预测的结果和正确结果比较
correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
return result
#好处在于可以使用一部分数据
xs = tf.placeholder(tf.float32, [None, 784]) #28*28
ys = tf.placeholder(tf.float32, [None, 10])
#激励函数用softmax
prediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)
#交叉熵代价函数
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
#初始化所有tensorflow变量
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
# training
batch_xs, batch_ys = mnist.train.next_batch(100)#每次取100张图片进行训练
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
if i % 50 == 0:
# to see the step improvement
accuracy = compute_accuracy(
mnist.test.images, mnist.test.labels)
print("Epoches: %d / 1000:\n\taccuracy : %0.3f" %(i, accuracy))
测试结果:
tensorflow2.0写法如下:利用keras作为tensorflow的api
from tensorflow.keras.datasets import mnist
import tensorflow as tf
from tensorflow.keras import layers
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape, y_train.shape)
print(x_test.shape, y_test.shape)
x_train = x_train.reshape(60000, 784).astype('float32')/255.
x_test = x_test.reshape(10000, 784).astype('float32')/255.
inputs = tf.keras.Input(shape=(784,))
pred = layers.Dense(10, activation='softmax')(inputs)
model = tf.keras.Model(inputs=inputs, outputs=pred)
model.compile(optimizer=tf.keras.optimizers.SGD(lr=0.5),
loss='sparse_categorical_crossentropy',#目标张量是整形张量
metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=100, epochs=5)
test_score = model.evaluate(x_test, y_test)
print('test loss: %0.3f' %test_score[0])
print('test acc: %0.3f' %test_score[1])
测试结果如下: