tensorflow入门,实现logistic回归训练minist数据集

思路比较简单,直接结合着注释看代码!

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#导入mnist数据
mnist = input_data.read_data_sets("../data/mnsit", one_hot=True)
# Parameters设置参数,进行批梯度下降
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1
# tf Graph Input
x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes
# Set model weights 
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Construct model 利用参数创建预测模型
pred = tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
entropy = tf.nn.softmax_cross_entropy_with_logits(labels = y, logits = pred)
cost = tf.reduce_mean(entropy)
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)#cost 可以看做是损失函数
# Initializing the variables
init = tf.global_variables_initializer()
# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    # Training cycle
    for epoch in range(training_epochs):
        avg_cost = 0. #float
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            #分批次获得数据
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value) # 这里返回一个[optimizer,cost]的list, 其中 _代表optimizer,cost代表bath cost的值
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs,  
                                                          y: batch_ys})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost))

    print("Optimization Finished!")

    # Test model 得到模型的准确性
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    # Calculate accuracy correct_prediction本来是bool型的tensor,Tensor("Equal_6:0", shape=(?,), dtype=bool) 将correct_prediction转换成浮点型
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,593评论 25 708
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,019评论 3 119
  • 1.用户模型 2.注册 3.登录和退出 4.更新、显示和删除用户 5.账户激活和密码重设 6.用户的微博 7.关注...
    Jayzen阅读 665评论 0 0
  • 我有个亲戚的儿子在新加坡留学、工作和取得国籍,无比成功;我还有一个同姓远亲的儿子高考时就被保送到复旦大学读书,...
    像鸟儿一样飞阅读 385评论 3 0
  • 记录下蓝牙开发: 先明确5个概念: 蓝牙连接的步骤就是建立中心设备,扫描外设,按硬件话说就是主机找从机。在外设中找...
    清风沐沐阅读 639评论 1 4