TensorFlow学习1——MNIST入门

import tensorflow as tf
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)


       
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值