softmax回归,多分类问题
W*x+b
import tensorflow as tf
import numpy as np
#回归
x = tf.placeholder(tf.float32, [None, 784]) #图像
W = tf.Variable(tf.zeros([784, 10])) #权重
b = tf.Variable(tf.zeros([10])) #偏差
y = tf.nn.softmax(tf.matmul(x, W) + b) #matmul乘
#损失
#交叉熵
y_ = tf.placeholder(tf.float32, [None, 10]) #正确答案
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) #交叉熵公式
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) #梯度学习优化
sess = tf.InteractiveSession() #启动
tf.global_variables_initializer().run() #初始化
for _ in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) #调参
#现在w,b的值已经改变
#评估模型
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) #比较对应值10行,相等的返回true
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #将Boolean值转化成浮点数,求平均得出正确率
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) #测试数据正确性