【云计算】MNIST-Tensorflow基础知识入门
小标 2019-01-14 来源 : 阅读 710 评论 0

摘要:本文主要向大家介绍了【云计算】MNIST-Tensorflow基础知识入门,通过具体的内容向大家展现,希望对大家学习云计算有所帮助。

本文主要向大家介绍了【云计算】MNIST-Tensorflow基础知识入门,通过具体的内容向大家展现,希望对大家学习云计算有所帮助。

在TensorFlow中文社区学习的帖子,好久没写博客了,这个教程非常适合新手学习,附上链接如下:


MNIST是一个数字识别的数据集,笔记本一直是win10,就用spyder跑了一下,感觉很好。第一次的代码仿佛helloworld一样拥有新生儿纯洁的面孔,期间也出了很多莫名其妙的bug,话不多说,上code



# -*- coding: utf-8 -*-
"""
Created on Sun Aug 19 10:59:50 2018

@author: Keneyr
"""

import tensorflow as tf


from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets("G:/MINIST_data/", one_hot=True)

#tf.reset_default_graph()

#keep_prob = tf.placeholder(tf.float32)

# Sets a new default graph, and stores it in `g`.
with tf.Graph().as_default() as g: 
    
    x = tf.placeholder("float",[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("float",[None,10])
    cross_entropy = -tf.reduce_sum(y_*tf.log(y))
    
    train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
    
    init = tf.initialize_all_variables()
    sess = tf.Session()
    sess.run(init)
    #开始训练模型,循环训练1000次
    for i in range(1000):
        #随机抓取训练数据中的100个批处理数据点
        batch_xs,batch_ys = mnist.train.next_batch(100)
        #print(batch_xs)      
        sess.run(train_step,feed_dict={x:batch_xs,y_:batch_ys})
        
    #tf.argmax(y,1)返回的是模型对于任一输入x预测到的标签值
    #tf.argmax(y_,1) 代表正确的标签
    correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
    print(accuracy)
    print (sess.run(accuracy,feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
    


谁能告诉我为什么我的代码背景升级为黑色了,贼开心,难道这个是博客的等级有关系吗,这个跑出来的结果就是91%,还有另外一段代码也是一样,跑出来的效果也是91%。区别就在于,下面这个代码使用更加方便的InteractiveSession类。通过它,你可以更加灵活地构建你的代码。它能让你在运行图的时候,插入一些计算图,这些计算图是由某些操作(operations)构成的。这对于工作在交互式环境中的人们来说非常便利,比如使用IPython。如果你没有使用InteractiveSession,那么你需要在启动session之前构建整个计算图,然后启动该计算图。code如下:


# -*- coding: utf-8 -*-
"""
Created on Sun Aug 19 14:16:38 2018

@author: Keneyr
"""

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

mnist = input_data.read_data_sets("G:/MINIST_data/",one_hot=True)
#print (mnist)

sess = tf.InteractiveSession()
x = tf.placeholder("float",shape=[None,784])
y_ = tf.placeholder("float",shape=[None,10])

W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))

sess.run(tf.initialize_all_variables())
y = tf.nn.softmax(tf.matmul(x,W)+b)

cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

for i in range(1000):
    batch = mnist.train.next_batch(50)
    train_step.run(feed_dict={x:batch[0],y_:batch[1]})

correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))

print (accuracy.eval(feed_dict={x:mnist.test.images,y_:mnist.test.labels}))  


但是这两个代码的效率都不高,有一个用CNN训练的, 效果达到了99.2%,还是不错的,到底要选择什么样的梯度下降算法,选择什么样的网络,网络又该怎么设计,真的是谜一般的存在。难道深度学习这个东西就是黑灯瞎火的碰运气吗···


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

mnist = input_data.read_data_sets("G:/MINIST_data/", one_hot=True)
x = tf.placeholder("float",shape=[None,784])
y_ = tf.placeholder("float",shape=[None,10])
sess = tf.InteractiveSession()

'''
initialization functions
'''
def weight_variable(shape):
    initial = tf.truncated_normal(shape,stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    initial = tf.constant(0.1,shape=shape)
    return tf.Variable(initial)


'''
convolution maxpooling functions
'''
def conv2d(x,W):
    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
def max_pool_2x2(x):
    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')

'''
conv-relu-maxpooling
'''
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x,[-1,28,28,1])
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

'''
conv-relu-maxpooling
'''
W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

'''
fc
'''
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

'''
dropout
'''
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)

'''
softmax
'''
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

'''
train-evaluate
'''
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
sess.run(tf.initialize_all_variables())
for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
    print ("step %d, training accuracy %g"%(i, train_accuracy))
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

print ("test accuracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
    
sess.close()


          

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标大数据云计算大数据安全频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程