Tensorflow 实现Softmax Regression手写数字识别

# -*- coding: utf-8 -*-
"""
Created on Sun Jul 21 23:01:29 2019

@author: hm
"""

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 导入数据
mnist = input_data.read_data_sets("C:\\Users\\hm\\Desktop\\shuju", one_hot=True)
'''
如果不用one_hot编码,则会报错:
ValueError: Cannot feed value of shape (100,) for 
Tensor 'Placeholder_21:0', which has shape '(?, 10)'

'''


'''
#分别是train  test  validation  datasets的大小
print(mnist.train.images.shape,mnist.train.labels.shape)
print(mnist.test.images.shape,mnist.test.labels.shape)
print(mnist.validation.images.shape,mnist.validation.labels.shape)
'''

sess = tf.InteractiveSession()
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)

y_ = tf.placeholder(tf.float32,[None,10])
loss = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),
                                     reduction_indices=[1]))

train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
tf.global_variables_initializer().run()

for i in range(1000):
    batch_xs,batch_ys = mnist.train.next_batch(100) #每次读取100个数据
    train_step.run({x:batch_xs,y_:batch_ys})


correct_prediction = tf.equal(tf.argmax(y,1),tf.arg_max(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels}))
#输出0.9161

##查看训练好的权重
import numpy as np
np.set_printoptions(threshold=np.inf) #tensorflow 打印张量时,输出不完全,总有省略号怎么办
print(W.eval())
print(b.eval())

 

注意:

(1)训练数据先用placehloder()占位,但是要注意相应的shape

(2)如果不用one_hot编码,则会报错:
ValueError: Cannot feed value of shape (100,) for Tensor 'Placeholder_21:0', which has shape '(?, 10)'

(3)本文是最简单的Tensorflow实现的小demo,旨在于了解相应的模型构造和训练。

(4)查看训练好的权重:直接print相应的权重变量,本文是W,b

但是,打印张量时,输出不完全,总有省略号或者只保留小数点前面几位数字,解决方法如下:
import numpy as np
np.set_printoptions(threshold=np.inf) #tensorflow print(W.eval())
print(b.eval())

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值