简单的手写图片识别

#载入数据集

#载入数据集
mnist = input_data.read_data_sets('MNIST_data',one_hot=True)

#每批次放进100个
batch_size = 50
#计算一共有多少批次
n_batch = mnist.train.num_examples // batch_size

#定义两个placeholder 属性的个数是固定的  样本数是变化的
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10]) 
#两个None对应位置是一样的

#创建第一个隐层神经网络
W_1 = tf.Variable(tf.random_normal([784,40])*0.01)
b_1 = tf.Variable(tf.zeros([40]))
Wx_plus_b_1 = tf.matmul(x,W_1)+b_1
#虽然与ng讲的是相反的 但是这里维度是相对应乘起来的,多以没啥问题
#行数是样本数  一行里面有784个feature  所以列是784 列    最后维度要对应上
prediction_L1 = tf.nn.tanh(Wx_plus_b_1)

#创建第二隐层
W_2 = tf.Variable(tf.random_normal([40,20])*0.01)
b_2 = tf.Variable(tf.zeros([20]))
Wx_plus_b_2 = tf.matmul(prediction_L1,W_2)+b_2
prediction_L2 = tf.nn.tanh(Wx_plus_b_2)

#创建输出层
W_3 = tf.Variable(tf.random_normal([20,10])*0.01)
b_3 = tf.Variable(tf.zeros([10]))
Wx_plus_b_3 = tf.matmul(prediction_L2,W_3)+b_3
prediction = tf.nn.softmax(Wx_plus_b_3)

#二次代价函数
loss = tf.reduce_mean(tf.square(y-prediction))
#使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)

#初始化变量
init = tf.global_variables_initializer()

#
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
#tf.equal(x,y) 看x,y是否一样  一样就true
# argmax的0就是纵向的元素中最大的那个的索引
# 1 就是每行横向的元素中最大的那个元素的索引
# 0轴就是竖向,1就是横向 但是要分清元素还是层级
#arg会返回一个array
#最终返回布尔类型列表

#求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
#tf.cast 是将布尔类型转化为浮点型

#创建会话
with tf.Session() as sess:
    sess.run(init)
    for epoch in range(145):
        for batch in range(n_batch):
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys})
            
        acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})
        #利用训练集上的数据来劲训练,用测试级来进行
        print('Iter'+ str(epoch)+',testing accuracy'+str(acc))

通过修改参数,权值的初始化方式,学习率,迭代周期,增加隐层,已经将准确率达到0.95以上

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值