TensorFlow入门-数据集MNIST的下载及训练

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ll523587181/article/details/79641799

折腾了很久caffe, 无论是ubuntu还是windows都没下载成功 = = 算了算了转战TensorFlow。


第一次根据官网提供的python3地址下载时,报错说

tensorflow-0.5.0-cp27-none-linux_x86_64.whl is not a supported wheel on this platform.

后来发现是url地址问题,我用的python3.5,地址应该改为:

https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.12.1-cp35-cp35m-linux_x86_64.whl

成功下载。


MNIST数据集下载:

在MNIST官网上下载压缩包,放在项目.py文件目录下,无须解压:


input_data.py:

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# pylint: disable=unused-import
import gzip
import os
import tempfile

import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
# pylint: enable=unused-import

mnist_test.py:

import tensorflow as tf
import input_data


mnist = input_data.read_data_sets('./', one_hot=True)
print(mnist.train.images.shape)
print(mnist.train.labels.shape)

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_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for i in range(1000):
    x_batches , y_batches = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: x_batches, y_: y_batches})

correction_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correction_prediction, "float"))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

输出 0.9185



展开阅读全文

没有更多推荐了,返回首页