Tensorflow-mnist 手写数字识别

1.加载数据MNIST_data,按照tensorflow官网的:

import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
总是报错,应该查到安装tensorflow后,input_data.py这个文件在tensorflow的路径在tutorials下的mnist中,因此按如下import文件:

from tensorflow.examples.tutorials.mnist import input_data
由于在线下载mnist总是显示下载超时,所以建议在http://yann.lecun.com/exdb/mnist/上直接下载训练数据,格式为gz:

train-images-idx3-ubyte.gz: training set images (9912422 bytes)
train-labels-idx1-ubyte.gz: training set labels (28881 bytes)
t10k-images-idx3-ubyte.gz:  test set images (1648877 bytes)
t10k-labels-idx1-ubyte.gz:  test set labels (4542 bytes)

然后查看input_data.py中的源代码:

# CVDF mirror of http://yann.lecun.com/exdb/mnist/
DEFAULT_SOURCE_URL = 'https://storage.googleapis.com/cvdf-datasets/mnist/'
def read_data_sets(train_dir,
                   fake_data=False,
                   one_hot=False,
                   dtype=dtypes.float32,
                   reshape=True,
                   validation_size=5000,
                   seed=None,
                   source_url=DEFAULT_SOURCE_URL):
  if fake_data:

    def fake():
      return DataSet(
          [], [], fake_data=True, one_hot=one_hot, dtype=dtype, seed=seed)

    train = fake()
    validation = fake()
    test = fake()
    return base.Datasets(train=train, validation=validation, test=test)

  if not source_url:  # empty string check
    source_url = DEFAULT_SOURCE_URL

  TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
  TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
  TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
  TEST_LABELS = 't10k-labels-idx1-ubyte.gz'

  local_file = base.maybe_download(TRAIN_IMAGES, train_dir,
                                   source_url + TRAIN_IMAGES)
  with gfile.Open(local_file, 'rb') as f:
    train_images = extract_images(f)

  local_file = base.maybe_download(TRAIN_LABELS, train_dir,
                                   source_url + TRAIN_LABELS)
  with gfile.Open(local_file, 'rb') as f:
    train_labels = extract_labels(f, one_hot=one_hot)

  local_file = base.maybe_download(TEST_IMAGES, train_dir,
                                   source_url + TEST_IMAGES)
  with gfile.Open(local_file, 'rb') as f:
    test_images = extract_images(f)

  local_file = base.maybe_download(TEST_LABELS, train_dir,
                                   source_url + TEST_LABELS)
  with gfile.Open(local_file, 'rb') as f:
    test_labels = extract_labels(f, one_hot=one_hot)

  if not 0 <= validation_size <= len(train_images):
    raise ValueError(
        'Validation size should be between 0 and {}. Received: {}.'
        .format(len(train_images), validation_size))

  validation_images = train_images[:validation_size]
  validation_labels = train_labels[:validation_size]
  train_images = train_images[validation_size:]
  train_labels = train_labels[validation_size:]


  options = dict(dtype=dtype, reshape=reshape, seed=seed)

  train = DataSet(train_images, train_labels, **options)
  validation = DataSet(validation_images, validation_labels, **options)
  test = DataSet(test_images, test_labels, **options)

  return base.Datasets(train=train, validation=validation, test=test)

将source_url关闭(因为这个的地址DEFAULT_SOURCE_URL='https://storage.googleapis.com/cvdf-datasets/mnist/',其总是打不开),提示直接本地加载mnist data,注意,代码中MNIST_data/文件夹中需要有下载好的gz格式训练数据:

mnist = input_data.read_data_sets("MNIST_data/", one_hot=True,source_url = False)

这样就加载完成了。

2.下面是简单模型softmax regression建立的源代码:

# coding: utf-8

# In[14]:


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


# In[6]:


mnist = input_data.read_data_sets("MNIST_data/", one_hot=True,source_url = False)


# In[23]:


import numpy
print(mnist.train.images.shape)


# In[26]:


x = tf.placeholder("float", [None, 784])    #用浮点数来表示张量形状,每一张图展平为784维的向量
W = tf.Variable(tf.zeros([784,10]))    # W 代表权重
b = tf.Variable(tf.zeros([10]))    # b 偏置量
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)    #在session中启动模型,变量
# 训练模型1000次
for i in range(1000):
  batch_xs, batch_ys = mnist.train.next_batch(100)
  sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})


# In[29]:


correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))    #找最大值的索引值-即结果1
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))




  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 基于TensorFlow的MNIST数字识别是一种机器学习技术,它可以通过训练模型来识别数字。MNIST是一个常用的数据集,包含了大量的数字图像和对应的标签。TensorFlow是一个流行的深度学习框架,可以用来构建和训练神经网络模型。通过使用TensorFlow,我们可以构建一个卷积神经网络模型,对MNIST数据集进行训练和测试,从而实现数字识别的功能。 ### 回答2: 随着机器学习技术的不断发展,MNIST数字识别已成为一个基础、常见的图像分类问题。TensorFlow是目前最流行的深度学习框架之一,广泛应用于图像处理、自然语言处理等领域,所以在TensorFlow上实现MNIST数字识别任务是非常具有代表性的。 MNIST数字识别是指从给定的数字图像中识别数字的任务。MNIST数据集是一个由数万张数字图片和相应标签组成的数据集,图片都是28*28像素的灰度图像。每一张图片对应着一个标签,表示图片中所代表的数字。通过对已经标记好的图片和标签进行训练,我们将构建一个模型来预测测试集中未知图片的标签。 在TensorFlow中实现MNIST数字识别任务,可以通过以下步骤完成: 1. 导入MNIST数据集:TensorFlow中的tf.keras.datasets模块内置了MNIST数据集,可以通过如下代码导入:(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() 2. 数据预处理:对数据进行标准化处理,即将灰度值范围从[0,255]缩放到[0,1]之间。同时将标签值进行独热编码,将每个数字的标签由一个整数转换为一个稀疏向量。采用以下代码完成数据预处理:train_images = train_images / 255.0 test_images = test_images / 255.0 train_labels = tf.keras.utils.to_categorical(train_labels, 10) test_labels = tf.keras.utils.to_categorical(test_labels, 10) 3. 构建模型:采用卷积神经网络(CNN)进行建模,包括卷积层、池化层、Dropout层和全连接层。建议采用可重复使用的模型方法tf.keras.Sequential()。具体代码实现为:model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3,3), activation='relu',input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D((2,2)), tf.keras.layers.Flatten(), tf.keras.layers.Dropout(0.5)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) 4. 编译模型:指定优化器、损失函数和评估指标。可采用Adam优化器,交叉熵损失函数和准确率评估指标。具体实现代码如下:model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) 5. 训练模型:采用train()函数进行模型训练,完成代码如下:model.fit(train_images, train_labels, epochs=5, validation_data=(test_images, test_labels)) 6. 评估模型:计算测试准确率,完成代码如下:test_loss, test_acc = model.evaluate(test_images, test_labels) print('Test accuracy:', test_acc) 以上就是基于TensorFlow的MNIST数字识别的简要实现过程。其实实现过程还可以更加复杂,比如调节神经元数量,添加卷积层数量等。总之采用TensorFlow框架实现MNIST数字识别是一个可行的任务,未来机器学习发展趋势将越来越向深度学习方向前进。 ### 回答3: MNIST数字识别是计算机视觉领域中最基础的问题,使用TensorFlow实现这一问题可以帮助深入理解神经网络的原理和实现,并为其他计算机视觉任务打下基础。 首先,MNIST数字数据集由28x28像素的灰度图像组成,包含了数字0到9共10个类别。通过导入TensorFlow及相关库,我们可以很容易地加载MNIST数据集并可视化: ``` import tensorflow as tf import matplotlib.pyplot as plt (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data() print("Training images:", train_images.shape) print("Training labels:", train_labels.shape) print("Test images:", test_images.shape) print("Test labels:", test_labels.shape) plt.imshow(train_images[0]) plt.show() ``` 在实现MNIST数字识别的神经网络模型中,最常用的是卷积神经网络(Convolutional Neural Networks,CNN),主要由卷积层、激活层、池化层和全连接层等组成。卷积层主要用于提取局部特征,激活层用于引入非线性性质,池化层则用于加速处理并减少过拟合,全连接层则进行最终的分类。 以下为使用TensorFlow搭建CNN实现MNIST数字识别的代码: ``` model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, kernel_size=(3,3), activation='relu', input_shape=(28,28,1)), tf.keras.layers.MaxPooling2D(pool_size=(2,2)), tf.keras.layers.Conv2D(64, kernel_size=(3,3), activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=(2,2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.5), tf.keras.layers.Dense(10, activation='softmax') ]) model.summary() model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) train_images = train_images.reshape((60000, 28, 28, 1)) train_images = train_images / 255.0 test_images = test_images.reshape((10000, 28, 28, 1)) test_images = test_images / 255.0 model.fit(train_images, train_labels, epochs=5, batch_size=64) test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print("Test accuracy:", test_acc) ``` 这段代码中使用了两个卷积层分别提取32和64个特征,池化层进行特征加速和降维,全连接层作为最终分类器输出预测结果。在模型训练时,使用Adam优化器和交叉熵损失函数进行训练,经过5个epoch后可以得到约99%的测试准确率。 总之,通过使用TensorFlow实现MNIST数字识别的经历,可以深切认识到深度学习在计算机视觉领域中的应用,以及如何通过搭建和训练神经网络模型来解决实际问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值