初识tensorflow

下载并安装 TensorFlow 2 软件包,需要使用高于 19.0 的 pip 版本(对于 macOS 则需要高于 20.3 的 pip 版本)。

# Requires the latest pip
pip install --upgrade pip
# Current stable release for CPU and GPU
pip install tensorflow
# Or try the preview build (unstable)
pip install tf-nightly

1. 基本图像分类

训练一个神经网络模型,实现对运动鞋和衬衫等服装图像进行分类。使用 Fashion MNIST 数据集,该数据集包含 10 个类别的 70,000 个灰度图像。这些图像以低分辨率(28x28 像素)展示了单件衣物,如下所示:

初识tensorflow_第1张图片

这里我们使用 6W 个图像来训练网络,使用 1W 个图像来评估网络学习对图像分类的准确率。

import tensorflow as tf
from tensorflow import keras
# import numpy as np
# import matplotlib.pyplot as plt

print(tf.__version__)
# 1.15.0

图像是 28x28 的 NumPy 数组,像素值介于 0 到 255 之间。标签是整数数组,介于 0 到 9 之间。这些标签对应于图像所代表的服装

初识tensorflow_第2张图片

在训练网络之前,必须对数据进行预处理。如果您检查训练集中的第一个图像,您会看到像素值处于 0 到 255 之间:

初识tensorflow_第3张图片

初识tensorflow_第4张图片

2. 实现手写数字识别

import tensorflow as tf

# 载入MNIST数据集
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 将样本从整数转换为浮点数
x_train, x_test = x_train / 255.0, x_test / 255.0
# 将模型的各层堆叠起来,搭建Sequential模型
model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])
# 为训练选择优化器和损失函数
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])
# 训练并验证模型
model.fit(x_train, y_train, epochs=50)
model.evaluate(x_test,  y_test, verbose=2)

这个图片分类器的准确度已经达到 98%。

初识tensorflow_第5张图片

你可能感兴趣的:(tensorflow,tensorflow)