tensorflow之逻辑回归

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36890572/article/details/82954340

逻辑回归

(1)手写数字介绍

  • 数据集下载网址:http://yann.lecun.com/exdb/mnist/ 
  • 数据分为训练集合测试集,数据对应有:特征及标签;
  • 为了方便实现分类,本文使用one-hot 编码方式;

(2)手写数字识别

  • 加载手写数字集;
  • 分批次训练,定义批次大小;
  • 定义占位符,用于输入x和结果y;
  • 定义网络结构,预测,计算误差,梯度下降优化;
  • 开始训练,定义准确率,分批次统计准确率;
# coding=utf-8
'''
手写数字识别:0-9的数字(进行one-hot编码)
数据集:
输入:训练 60000,测试 1000,维度:28*28,维度[60000,784],
输出:[60000,10]
softmax:将结果转化为概率,得出最终的预测分类
'''
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 1.加载数据
mnist = input_data.read_data_sets('data/MNIST_data',one_hot=True)
# 2.使用小批量训练,定义批次大小
batch_size = 100
# 计算训练次数
batch_num = mnist.train.num_examples//batch_size
# 3.定义占位符
x = tf.placeholder(tf.float32,[None,784])#输入的占位符
y = tf.placeholder(tf.float32,[None,10])#输出的占位符
# 4.定义网络结构
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
# 预测
predict = tf.nn.sigmoid(tf.matmul(x,W)+b)
# 代价函数
loss = tf.reduce_mean(tf.square(y-predict))
# 梯度下降
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
# 5.开始训练
init = tf.global_variables_initializer()
# 结果存储在布尔列表中(概率最大的位置是否相等)
correct_prediction = tf.equal(tf.arg_max(y,1),tf.arg_max(predict,1))
# 准确率(转为浮点后的均值)
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(21):
        for batch in range(batch_size):
            batch_x,batch_y = mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_x,y:batch_y})
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        print('Iter'+str(epoch)+',Test accuracy'+str(acc))

预测的最终准确率:Iter20,Test accuracy0.87

猜你喜欢

转载自blog.csdn.net/qq_36890572/article/details/82954340