欢迎关注”生信修炼手册”!
本文是对tensorflow官方入门教程的学习和翻译,展示了创建一个基础的神经网络模型来解决图像分类问题的过程。具体步骤如下
1. 加载数据
tensorflow集成了keras这个框架,提供了Fashion MNIST数据集,该数据集包含了10个类别共7万张服装图像,加载方式如下
>>> import tensorflow as tf
>>> from tensorflow import keras
>>> import numpy as np
>>> import matplotlib.pyplot as plt
>>> print(tf.__version__)
2.5.0
>>> fashion_mnist = keras.datasets.fashion_mnist
>>> (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-labels-idx1-ubyte.gz
32768/29515 [=================================] - 0s 1us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/train-images-idx3-ubyte.gz
26427392/26421880 [==============================] - 2s 0us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-labels-idx1-ubyte.gz
8192/5148 [===============================================] - 0s 1us/step
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/t10k-images-idx3-ubyte.gz
4423680/4422102 [==============================] - 0s 0us/step
>>> class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat','Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
>>> train_images.shape
(60000, 28, 28)
>>> train_images.shape
(60000, 28, 28)
>>> len(train_labels)
60000
>>> train_labels
array([9, 0, 0, ..., 3, 0, 5], dtype=uint8)
对这7万张图像,其中6万张用于训练模型,1万张用于评估模型效果,通过以下代码,可以查看具体的图像内容
>>> train_images = train_images / 255.0
>>> test_images = test_images / 255.0
>>> plt.figure(figsize=(10, 10))
<Figure size 1000x1000 with 0 Axes>
>>> for i in range(25):
... plt.subplot(5, 5, i + 1)
... plt.xticks([])
... plt.yticks([])
... plt.grid(False)
... plt.imshow(train_images[i], cmap=plt.cm.binary)
... plt.xlabel(class_names[train_labels[i]])
...
>>> plt.show()
可视化结果如下