前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用 MNIST 集入门 Tensoflow(1)

使用 MNIST 集入门 Tensoflow(1)

作者头像
coding01
发布2021-02-24 11:17:33
3590
发布2021-02-24 11:17:33
举报
文章被收录于专栏:Coding01Coding01Coding01
本文 1077.5字,需要 2.69 分钟

在入门之前,我们需要开发工具,本文使用 JupyterLab,可以用 conda 或者 pip 方式安装。

// conda 方式
conda install -c conda-forge jupyterlab

// or pip 方式
pip install jupyterlab

conda 源更新比较缓慢,推荐还是用 pip。

启用:

jupyter-lab

为了在不同的 conda 虚拟环境下使用 jupyterlab,可以安装插件 nb_conda_kernels

conda install -n tf2 nb_conda_kernels

下面就可以运行一个 hello world 和开发 Tensorflow了。

引用

import matplotlib.pyplot as plt
from typing import Dict, Text

import numpy as np
import tensorflow as tf

import tensorflow_datasets as tfds
import tensorflow_recommenders as tfrs
import os
import ssl

os.environ['HTTP_PROXY'] = 'http://0.0.0.0:8888'
os.environ['HTTPS_PROXY'] = 'http://0.0.0.0:8888'
ssl._create_default_https_context =  ssl._create_unverified_context

下载 MNIST 数据集

# MNIST data.
mnist_train = tfds.load(name="mnist", split="train", data_dir = os.path.join(os.getcwd(), "data"))

效果:

<PrefetchDataset shapes: {image: (28, 28, 1), label: ()}, types: {image: tf.uint8, label: tf.int64}>

图片格式主要是 28*28,我们可以写个代码将数据集保存为图片,看看图片效果。

转为图片

for mnist_example in mnist_train.take(1):  # 只取一个样本
    image, label = mnist_example["image"], mnist_example["label"]
    plt.imshow(image.numpy()[:, :, 0].astype(np.float32), cmap=plt.get_cmap("gray"))
    print("Label: %d" % label.numpy())

说明数据我们已经拿到手,有了数据,我们可以开始往下进行。

获取训练集和测试集

(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data(
    path = os.path.join(os.getcwd(), "data/mnist.npz")
)

初始化和灰度化

统一图片大小和灰度化:

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)
x_test = x_test.reshape(x_test.shape[0], 28, 28, 1)
input_shape = (28, 28, 1)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')

x_train /= 255
x_test /= 255

print('x_train shape: ', x_train.shape)
print('Number of images in x_train', x_train.shape[0])
print('Number of images in x_test', x_test.shape[0])

建立自然网络模型

# Importing the required Keras modules containing model and layers
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Dropout, Flatten, MaxPooling2D
# Creating a Sequential Model and adding the layers
model = Sequential()
model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten()) # Flattening the 2D arrays for fully connected layers
model.add(Dense(128, activation=tf.nn.relu))
model.add(Dropout(0.2))
model.add(Dense(10,activation=tf.nn.softmax))

编译模型

model.compile(optimizer='adam', 
              loss='sparse_categorical_crossentropy', 
              metrics=['accuracy'])
model.fit(x=x_train,y=y_train, epochs=10)

model.evaluate(x_test, y_test)

测试

image_index = 5555
plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))
print(pred.argmax())
image_index = 6666
plt.imshow(x_test[image_index].reshape(28, 28),cmap='Greys')
pred = model.predict(x_test[image_index].reshape(1, 28, 28, 1))
print(pred.argmax())

总结

初步学习使用 MNIST 数据集做训练和对手写数字的识别测试,开启 tensorflow 的入门。

THE MNIST DATABASE of handwritten digits[1]

Image Classification in 10 Minutes with MNIST Dataset[2]

参考

[1] THE MNIST DATABASE of handwritten digits http://yann.lecun.com/exdb/mnist/

[2] Image Classification in 10 Minutes with MNIST Dataset https://towardsdatascience.com/image-classification-in-10-minutes-with-mnist-dataset-54c35b77a38d

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-01-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 coding01 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档