import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#import data
# Create the model
定义误差和优化器
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
初始化变量
init_op = tf.initialize_all_variables()
saver = tf.train.Saver()
# Train the model and save the model to disk as a model.ckpt file
# file is stored in the same directory as this python script is started
"""
The use of 'with tf.Session() as sess:' is taken from the Tensor flow documentation
on on saving and restoring variables.
https://www.tensorflow.org/versions/master/how_tos/variables/index.html
"""
with tf.Session() as sess:
sess.run(init_op)
for i in range(1000):
save_path = saver.save(sess, "./model.ckpt")
print ("Model saved in file: ", save_path)
from tensorflow.examples.tutorials.mnist import input_data
#import data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
读取MNIST_data,数据集在官网http://yann.lecun.com/exdb/mnist/
变量在定义时要初始化,但是如果有些变量刚开始我们并不知道它们的值,无法初始化,那怎么办呢?
那就用占位符来占个位置
# Create the model
x = tf.placeholder(tf.float32, [None, 784])
定义784*10的全0矩阵
W = tf.Variable(tf.zeros([784, 10]))
定义10个全0
b = tf.Variable(tf.zeros([10]))
softmax回归概率为0~1,神经元y=x*W+b
y = tf.nn.softmax(tf.matmul(x, W) + b)定义误差和优化器
# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
初始化变量
init_op = tf.initialize_all_variables()
saver = tf.train.Saver()
# Train the model and save the model to disk as a model.ckpt file
# file is stored in the same directory as this python script is started
"""
The use of 'with tf.Session() as sess:' is taken from the Tensor flow documentation
on on saving and restoring variables.
https://www.tensorflow.org/versions/master/how_tos/variables/index.html
"""
with tf.Session() as sess:
sess.run(init_op)
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
60000行的训练数据集(mnist.train
)和10000行的测试数据集(mnist.test
)。这样的切分很重要,在机器学习模型设计时必须有一个单独的测试数据集不用于训练而是用来评估这个模型的性能,从而更加容易把设计的模型推广到其他数据集上(泛化)。
正如前面提到的一样,每一个MNIST数据单元有两部分组成:一张包含手写数字的图片和一个对应的标签。我们把这些图片设为“xs”,把这些标签设为“ys”。训练数据集和测试数据集都包含xs和ys
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})save_path = saver.save(sess, "./model.ckpt")
print ("Model saved in file: ", save_path)