03使用tensorflow实现逻辑回归(mnist数据集)

利用基本的mlp实现逻辑回归(mnist数据集)

import tensorflow as tf
import numpy
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
rng = numpy.random

# 设置训练参数
learning_rate = 0.01
training_epochs = 25
batch_size = 100
display_step = 1

# 加载训练数据,第一次加载时需要下载数据集到下面自行创建的目录中
# mnist数据集中为28x28x1,单通道数据集
mnist = input_data.read_data_sets("MNIST_DATA/", one_hot=True)

# 占位节点,None 表示将每一个批次输入的图片个数
X = tf.placeholder(tf.float32, [None, 784])
Y = tf.placeholder(tf.float32, [None, 10])

# 单层网络,只有10个节点
W = tf.Variable(tf.zeros([784, 10]), name="weight")
b = tf.Variable(tf.zeros([10]), name="bias")

# 输出
pred = tf.nn.softmax(tf.matmul(X, W) + b)

# 损失函数
cost = tf.reduce_mean(-tf.reduce_sum(Y*tf.log(pred), reduction_indices=1))
# 优化器
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)

# 初始化参数
init = tf.global_variables_initializer()

# 进入图
with tf.Session() as sess:
    # 图初始化
    sess.run(init)

    # 训练图
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples / batch_size)

        for i in range(total_batch):
            batch_xs, batch_ys = mnist.train.next_batch(batch_size)

            _, c = sess.run([optimizer, cost], feed_dict={X: batch_xs, Y: batch_ys})

            avg_cost += c / total_batch

        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 for 3000 examples
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print("Accuracy:", accuracy.eval({X: mnist.test.images[:3000], Y: mnist.test.labels[:3000]}))
# Epoch: 0025 cost= 0.333732169
# Optimization Finished!
# Accuracy: 0.8883333

你可能感兴趣的:(03使用tensorflow实现逻辑回归(mnist数据集))