单层神经网络——手写输入集识别

取自于TensorFlow实战 
 


 
  
import  tensorflow as tf
#定义tensorflow的CPU运算优先级
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
#导入MNIST手写数字集数据
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets('MNIST_data/',one_hot=True)
#确认导入成功
print(mnist.train.images.shape,mnist.train.labels.shape)
print(mnist.test.images.shape,mnist.test.labels.shape)
#定义交互式会话框
sess=tf.InteractiveSession()
#定义输入输出占位符
x=tf.placeholder(tf.float32,[None,784])
y_=tf.placeholder(tf.float32,[None,10])
#定义权重和偏置
w=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
#定义输出模型,y=x*w+b,多分类任务使用softmax为激活函数
y=tf.nn.softmax(tf.matmul(x,w)+b)
#定义损失函数为交叉熵
cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
#定义训练器为梯度下降法,学习率为0.5,使交叉熵最小化
train=tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
#初始化参数
tf.global_variables_initializer().run()
#定义训练循环:
    # 导入mini_batch数据,每次100组
    #将训练数据赋值给输入输出
for i in range(1000):
    batch_x,batch_y=mnist.train.next_batch(100)
    train.run({x:batch_x,y_:batch_y})
#定义模型预测正误判断模型,判断是否相等(模型输出中最大数据的index,输入标签中最大数据的index)
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
#定义准确率,将判断模型中的bool值转化为float32,对所有值求平均即为准确率
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
#用eval计算accuracy,输入输出为测试数据集
print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))


猜你喜欢

转载自blog.csdn.net/qq_41644087/article/details/80487149