进行模型的构建
先是线性模型
import tensorflow as tf from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets from mnist import model data = read_data_sets('MNIST_data', one_hot=True) with tf.variable_scope('regression'): x = tf.placeholder(tf.float32, [None, 784]) y, variables = model.regression(x) _y = tf.placeholder('float', [None, 10]) cross_entropy = -tf.reduce_sum(_y * tf.log(y)) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(_y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
1.线性模型:
# Y = W * x + b
def regression(x):
W = tf.Variable(tf.zeros([784, 10], name='W')) # 784 * 10的二维数组
b = tf.Variable(tf.zeros([10]), name='b') # 一维数组里面放10个值
y = tf.nn.softmax(tf.matmul(x, W) + b) # softmax做简单的线性运算
return y, [W, b]
2. 定义完模型之后引入模型和训练:
# create model
with tf.variable_scope('regression'): # 命名
x = tf.placeholder(tf.float32, [None, 784]) # x:待用户输入,用一个占位符,placeholder的第一个参数是类型,第二个是张量,其中的784是和model中对应
y, variables = model.regression(x)
# train
y_ = tf.placeholder('float', [None, 10])
cross_entropy = -tf.reduce_sum(y_ * tf.log(y)) # 训练的交叉熵
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) # 训练步骤,GradientDescentOptimizer(0.01):一个优化器,设置步长为0.01
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) # 预测
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 准确率,tf.cast(correct_prediction, tf.float32):转换格式