CS实验记录

[1]TensorFlow 实现 Softmax Regress

2019-07-16  本文已影响0人  sagfugetabf

时间: 2019-7-16 11:33:59


使用tensorflow实现机器学习算法的步骤

x不是一个特定的值,而是一个占位符placeholder,我们在TensorFlow运行计算时输入这个值。

我们希望能够输入任意数量的MNIST图像,每一张图展平成784维的向量。

我们用2维的浮点数张量来表示这些图,这个张量的形状是[None,784 ]。

这里的None表示此张量的第一个维度可以是任何长度的。

交叉熵公式
-\sum y' \log(y)

#导入数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot = True)

# 设置参数
import tensorflow as tf
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("float",[None,10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))
# 参数从0.01 改成0.1 效果成89%到92%
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# init = tf.initialize_all_variables()
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for i in range(5000):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
        if i % 200 == 1:
            print(
                sess.run(accuracy,
                         feed_dict={
                             x: mnist.test.images,
                             y_: mnist.test.labels
                         }))
    print(
        sess.run(accuracy,
                 feed_dict={
                     x: mnist.test.images,
                     y_: mnist.test.labels
                 }))

最后的结果是:

Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
Time:  1 0.5192
Time:  1001 0.9172
Time:  2001 0.9199
Time:  3001 0.9214
Time:  4001 0.9211
0.9244
上一篇 下一篇

猜你喜欢

热点阅读