tf.keras 代码练习--cifar10数据--带详细注释--tf2.0

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
from tensorflow import keras

def preprocess(x, y):
    # [0~255] => [-1, 1] 把数值变为-1 ~ 1 范围,效果较之前有提升
    x = 2*tf.cast(x, dtype=tf.float32) / 255 - 1.
    y = tf.cast(y, dtype=tf.int32)
    return x, y


batchsz = 128
# 加载数据 [50000, 32, 32, 3] [50000, 1]   加载过了的是numpy数据类型,要想使用GPU加速,需要转换为tensor类型,再转换为Dataset类型,是为了实现batch_size 实现并行
(x, y), (x_val, y_val) = datasets.cifar10.load_data()
# y的形状是[50000, 1],squeeze 删除所有为1的维度,可以通过axis指定删除特定为1的维度 [50000, 1] => [5000]
y = tf.squeeze(y)
y_val = tf.squeeze(y_val)
y = tf.one_hot(y, depth=10)             # one_hot处理 [50k, 10]
y_val = tf.one_hot(y_val, depth=10)     # [10k, 10]
print('datasets:', x.shape, y.shape, x_val.shape, y_val.shape, x.min(), x.max())



# 构建数据集
train_db = tf.data.Dataset.from_tensor_slices((x, y))
#                  预处理(传入函数名) 打乱顺序       设置batch大小
train_db = train_db.map(preprocess).shuffle(10000).batch(batchsz)
test_db = tf.data.Dataset.from_tensor_slices((x_val, y_val))
test_db = test_db.map(preprocess).batch(batchsz)


# sample是为了查看数据形状
sample = next(iter(train_db))
print('batch:', sample[0].shape, sample[1].shape)


# 自定义线性层  必须继承layers.Layer
class MyDense(layers.Layer):

    # 实现2个函数 __init__  和 call。 给定输入参数 和 输出参数。
    def __init__(self, inp_dim, outp_dim):
        # 调用父类初始化方法
        super(MyDense, self).__init__()

        self.kernel = self.add_variable('w', [inp_dim, outp_dim])
        # self.bias = self.add_variable('b', [outp_dim])

    def call(self, inputs, training=None):
        # 前向
        x = inputs @ self.kernel
        return x

# 自定义网络     继承这个类    实现2个函数 __init__  call
class Mynetwork(keras.Model):

    def __init__(self):
        # 调用父类初始化方法
        super(Mynetwork, self).__init__()
        # 新建5个网络层
        self.fc1 = MyDense(32*32*3, 256)
        self.fc2 = MyDense(256, 128)
        self.fc3 = MyDense(128, 64)
        self.fc4 = MyDense(64, 32)
        self.fc5 = MyDense(32, 10)

    def call(self, inputs, training=None):
        # 前向传播过程       指定当前模式是training模式还是evaluate模式
        """

        :param inputs: [b, 32, 32, 3]
        :param training:
        :return:
        """
        x = tf.reshape(inputs, [-1, 32*32*3])
        # [b, 32*32*3] => [b, 256]
        x = self.fc1(x)
        x = tf.nn.relu(x)
        # [b, 256] => [b, 128]
        x = self.fc2(x)
        x = tf.nn.relu(x)
        # [b, 128] => [b, 64]
        x = self.fc3(x)
        x = tf.nn.relu(x)
        # [b, 64] => [b, 32]
        x = self.fc4(x)
        x = tf.nn.relu(x)
        # [b, 32] => [b, 10]
        x = self.fc5(x)

        return x


network = Mynetwork()
network.compile(optimizer=optimizers.Adam(lr=1e-3),
                loss=tf.losses.CategoricalCrossentropy(from_logits=True),
                metrics=['accuracy'])
#           训练集    训练的遍数   训练集                   每训练一个epoch数据,做一次测试
network.fit(train_db, epochs=15, validation_data=test_db, validation_freq=1)

# 先做一个测试,看看模型是否保存了
network.evaluate(test_db)
# 保存模型 单纯的保存权值
network.save_weights('ckpt/weights.ckpt')
# 删除网络对象
del network
print('saved to ckpt/weights.ckpt')


# 把网络创建的部分加载过来
network = Mynetwork()
network.compile(optimizer=optimizers.Adam(lr=1e-3),
                loss=tf.losses.CategoricalCrossentropy(from_logits=True),
                metrics=['accuracy'])
# 把权值更新到现在的权值
network.load_weights('ckpt/weights.ckpt')
print('load weight from file')
# 测试
network.evaluate(test_db)
boston_housing module: Boston housing price regression dataset. cifar10 module: CIFAR10 small images classification dataset. cifar100 module: CIFAR100 small images classification dataset. fashion_mnist module: Fashion-MNIST dataset. imdb module: IMDB sentiment classification dataset. mnist module: MNIST handwritten digits dataset. reuters module: Reuters topic classification dataset. import tensorflow as tf from tensorflow import keras fashion_mnist = keras.datasets.fashion_mnist (x_train, y_train), (x_test, y_test) = fashion_mnist.load_data() mnist = keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() cifar100 = keras.datasets.cifar100 (x_train, y_train), (x_test, y_test) = cifar100.load_data() cifar10 = keras.datasets.cifar10 (x_train, y_train), (x_test, y_test) = cifar10.load_data() imdb = keras.datasets.imdb (x_train, y_train), (x_test, y_test) = imdb.load_data() # word_index is a dictionary mapping words to an integer index word_index = imdb.get_word_index() # We reverse it, mapping integer indices to words reverse_word_index = dict([(value, key) for (key, value) in word_index.items()]) # We decode the review; note that our indices were offset by 3 # because 0, 1 and 2 are reserved indices for "padding", "start of sequence", and "unknown". decoded_review = ' '.join([reverse_word_index.get(i - 3, '?') for i in x_train[0]]) print(decoded_review) boston_housing = keras.datasets.boston_housing (x_train, y_train), (x_test, y_test) = boston_housing.load_data() reuters= keras.datasets.reuters (x_train, y_train), (x_test, y_test) = reuters.load_data() tf.keras.datasets.reuters.get_word_index( path='reuters_word_index.json' )
好的,我可以帮你完成这个问题。首先,我们需要导入必要的库,包括`tensorflow`,`numpy`以及`matplotlib`。代码如下: ```python import tensorflow as tf from tensorflow.keras.datasets import cifar10 import numpy as np import matplotlib.pyplot as plt ``` 接下来,我们需要加载CIFAR-10数据集并对其进行预处理,包括将像素值缩放到0到1之间,并将标签转换为one-hot编码。代码如下: ```python # 加载数据集 (train_images, train_labels), (test_images, test_labels) = cifar10.load_data() # 将像素值缩放到0到1之间 train_images = train_images / 255.0 test_images = test_images / 255.0 # 将标签转换为one-hot编码 train_labels = tf.keras.utils.to_categorical(train_labels, 10) test_labels = tf.keras.utils.to_categorical(test_labels, 10) ``` 接下来,我们可以定义模型并进行训练。这里我们使用了一个简单的卷积神经网络,包含一个卷积层,一个池化层和一个全连接层。代码如下: ```python # 定义模型 model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(10, activation='softmax') ]) # 编译模型 model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy']) # 训练模型 history = model.fit(train_images, train_labels, epochs=10, validation_data=(test_images, test_labels)) ``` 在训练完成后,我们可以使用`matplotlib`库绘制训练和验证准确率随时间变化的图表。代码如下: ```python # 绘制训练和验证准确率随时间变化的图表 acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] epochs = range(1, len(acc) + 1) plt.plot(epochs, acc, 'bo', label='Training accuracy') plt.plot(epochs, val_acc, 'b', label='Validation accuracy') plt.title('Training and validation accuracy') plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.legend() plt.show() ``` 完整的代码如下:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值