[tensorflow2笔记六] keras实战演练

文章目录

  • 一、手写数字识别-mnist数据集
    • sequential方法
    • class方法
  • 二、FASHION数据集

一、手写数字识别-mnist数据集

sequential方法

import tensorflow as tf

# 1.加载数据
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 输入特征归一化(0-255)->(0-1)
x_train = x_train / 255.0
x_test = x_test / 255.0                 # 把输入特征的数值变小更适合神经网络吸收

# 2.搭建网络
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(),          # 把输入特征拉直为一维数组 748个数值
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

# 3.配置训练方法
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),  # 输出满足概率分布
              metrics=['sparse_categorical_accuracy'])

# 4.训练
model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
# 5.打印出网络结构和参数统计
model.summary()

class方法

# 1.导入库
import tensorflow as tf
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras import Model

# 2.准备数据集
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

# 3.搭建网络
class MnistModel(Model):
    def __init__(self):
        super(MnistModel, self).__init__()
        self.flatten = Flatten()
        self.d1 = Dense(128, activation='relu')
        self.d2 = Dense(10, activation='softmax')

    def call(self, x):
        x = self.flatten(x)
        x = self.d1(x)
        y = self.d2(x)
        return y
model = MnistModel()

# 4.配置参数
model.compile(optimizer='adam',
              loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),
              metrics=['sparse_categorical_accuracy'])
# 5.训练
model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test), validation_freq=1)
# 6.打印网络结构
model.summary()

二、FASHION数据集

与MNIST数据集唯一不同:

# 1.加载数据
fashion = tf.keras.datasets.fashion_mnist
(x_train, y_train), (x_test, y_test) = fashion.load_data()

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