TensorFlow之构建逻辑回归模型

import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow .examples .tutorials .mnist import input_data
#使用MNIST数据集-10个手写体数据,对其进行分类
print("Download and Extract MNIST dataset")
mnist=input_data .read_data_sets ('data/',one_hot= True)
'''
print(" type of 'mnist' is %s"%(type(mnist)))
print (" number of train data is %d"%(mnist.train.num_examples))
print (" number of teat data id %d"%(mnist.test.num_examples))
'''
trainimg=mnist.train.images
trainlabel=mnist.train.labels
testimg=mnist.test.images
testlabel=mnist.test.labels
print ("MNIST loaded")

print(trainimg.shape)
print(trainlabel.shape)
print(testimg.shape)
print(testlabel.shape)

x=tf.placeholder("float",[None,784])#folat类型,每张图像用None表示无穷,用None进行填充
y=tf.placeholder("float",[None,10])
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
#逻辑回归解决二分类问题,将之变形为softmax
actv=tf.nn.softmax(tf.matmul(x,W)+b)
#损失函数
cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(actv), axis=1))
'''
reduce_sum应该理解为压缩求和,用于降维
reduce_sum ( 
    input_tensor , 
    axis = None , 
    keep_dims = False , 
    name = None , 
    reduction_indices = None
 )
input_tensor:要减少的张量.应该有数字类型.
axis:要减小的尺寸.如果为None(默认),则缩小所有尺寸.必须在范围[-rank(input_tensor), rank(input_tensor))内.0-列求和,1-行求和
keep_dims:如果为true,则保留长度为1的缩小尺寸.
name:操作的名称(可选).
reduction_indices:axis的废弃的名称.
'''
#梯度下降进行优化
learning_rate=0.01
optm=tf.train.GradientDescentOptimizer (learning_rate ).minimize(cost)
#找出每个样本的最大预测值与真正所属是否相同
pred=tf.equal(tf.argmax(actv,1),tf.argmax(y,1))
'''
tf.argmax(input, axis=None, name=None, dimension=None)--返回最大值的索引,从0开始
input:输入值
axis:0表示按列计算每列最大数的下标,1表示按行计算每行最大数的下标
name:名称
dimension:和axis功能一样,默认axis取值优先

equal(x, y, name=None)
equal,相等的意思。顾名思义,就是判断,x, y 是不是相等,它的判断方法不是整体判断,而是逐个元素进行判断,如果相等就是 True,不相等,就是 False。
由于是逐个元素判断,所以 x,y 的维度要一致。
'''
#
accr=tf.reduce_mean(tf.cast(pred,"float"))
'''
cast(   x,    dtype,    name=None)
将x的数据格式转化成dtype.例如,原来x的数据格式是bool, 
那么将其转化成float以后,就能够将其转化成0和1的序列。反之也可以
'''
init =tf.global_variables_initializer()

#逻辑框架已经完成。
training_epochs=50#所有的样本迭代50次
batch_size=100#每进行一次迭代要选择多少样本
display_step=5#展示
sess=tf.Session()
sess.run(init)
for epoch in range(training_epochs ):
    avg_cost=0
    num_batch=int(mnist.train.num_examples/batch_size )
    for i in range(num_batch):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        sess.run(optm, feed_dict={x: batch_xs, y: batch_ys})#梯度下降求解
        feeds = {x: batch_xs, y: batch_ys}
        avg_cost += sess.run(cost, feed_dict=feeds) / num_batch#算损失值,打印出来便于观察
    if epoch % display_step ==0:#每5个epoch打印一次
        feeds_train={x:batch_xs ,y:batch_ys }
        feeds_test={x:mnist.test.images,y:mnist.test.labels}
        train_acc=sess.run(accr,feed_dict= feeds_train)
        test_acc=sess.run(accr,feed_dict= feeds_test )
        print("Epoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f"%(epoch,training_epochs ,avg_cost ,train_acc ,test_acc ))
print("DONE")

结果:
Epoch: 000/050 cost: 1.176304688 train_acc: 0.860 test_acc: 0.854
Epoch: 005/050 cost: 0.440919038 train_acc: 0.950 test_acc: 0.894
Epoch: 010/050 cost: 0.383335552 train_acc: 0.940 test_acc: 0.905
Epoch: 015/050 cost: 0.357295629 train_acc: 0.890 test_acc: 0.909
Epoch: 020/050 cost: 0.341504634 train_acc: 0.920 test_acc: 0.913
Epoch: 025/050 cost: 0.330532011 train_acc: 0.950 test_acc: 0.914
Epoch: 030/050 cost: 0.322363376 train_acc: 0.940 test_acc: 0.916
Epoch: 035/050 cost: 0.315996517 train_acc: 0.920 test_acc: 0.917
Epoch: 040/050 cost: 0.310741446 train_acc: 0.880 test_acc: 0.919
Epoch: 045/050 cost: 0.306367814 train_acc: 0.900 test_acc: 0.918

你可能感兴趣的:(TensorFlow之构建逻辑回归模型)