深度学习之数据加载

在 TensorFlow 中,keras.datasets 模块提供了常用经典数据集的自动下载、管理、加载与转换功能,并且提供了 tf.data.Dataset 数据集对象,方便实现多线程(Multi-thread)预处理(Preprocess),**随机打散(Shuffle)批训练(Train on batch)**等常用数据集功能
常用数据集:

  • Boston Housing 波士顿房价趋势数据集,用于 回归模型 训练与测试

  • CIFAR10/100 真实图片 数据集 ,用于图片分类任务

  • MNIST/Fashion_MNIST 手写数字图片数据集,用于图片分类任务

  • IMDB 情感分类任务数据集

1、#加载MNIST数据集
#load_data() 会返回相应格式的数据, (x,y)保留了用于训练数据的数据集 (x_test,y_test)保留了用于测试的测试集对象
#所有的数据都用numpy.array容器承载

(x,y),(x_test,y_test) = dataset.minist.load_data()

2、数据加载进入内存之后,,需要转换成Dataset对象,利用Dataset.from_tensor_slices将训练部分的数据转换成Dataset对象

train_db = tf.Dataset.frome_tensor_slices((x,y))

3、随机打散,将Dataset对象随,随机打散数据之间的顺序,防止每次训练时数据按照固定的顺序产生

train_db = train_db.shuffle(10000)#数字表示缓冲池的大小,一般设置一个较大的参数即可

4、批处理

train_db = rain_db.batch(128)#数字表示一次可以并行计算样本数据的大小

5、预处理 一般情况下,从keras。datasets中加载的数据集的格式都不能满足模型输入的要求,Dataset通过提供map(func)工具函数可以调用用户自定义的预处理逻辑

#6、循环训练 可以通过两种方式进行迭代

for step,(x,y) in enumerate(train_db): 或者 for x,y in train_db
每次返回的x,y对象即为批量样本和标签,当所有样本完成一次迭代之后,for循环终止退出;一个batch的数据训练成为一个step;通过多个step来完成整个训练集的一次迭代,叫做一个epoch.

for epoch in range(20): for step,(x,y) in enumerate(tran_db):

此外,也可以设置成: train_db = train_db.rapeat(20)

实战

一:简单版

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets


#加载数据集
(x,y),_ = datasets.mnist.load_data()
#将x的范围从 0-255 变成 0-1
x = tf.convert_to_tensor(x,dtype = tf.float32) / 255
y = tf.convert_to_tensor(y,dtype = tf.int32)
print(x.shape,y.shape,x.dtype,y.dtype)

#查看x 、y的最值
print(tf.reduce_min(x),tf.reduce_max(x))
print(tf.reduce_min(y),tf.reduce_max(y))
train_db = tf.data.Dataset.from_tensor_slices((x,y))
#rain_db = tf.data.Dataset_from_tensor_slices((x,y)).batch(128)
train_db = train_db.batch(128)
train_iter = iter(train_db)
sample = next(train_iter)
print("batch:",sample[0].shape,sample[1].shape)


#创建权值
#w的形状 [dim_in,dim_out],b[dum_out]
#stddev方差为0.1
w1 = tf.Variable(tf.random.truncated_normal([784,256],stddev=0.1))
b1 = tf.Variable(tf.zeros([256]))
w2 = tf.Variable(tf.random.truncated_normal([256,128],stddev=0.1))
b2 = tf.Variable(tf.zeros([128]))
w3 = tf.Variable(tf.random.truncated_normal([128,10],stddev=0.1))
b3 = tf.Variable(tf.zeros([10]))
lr = 1e-2
#前向运算
for epoch in range(10):
    for step,(x,y) in enumerate(train_db):
        #x的形状为[128,28,28] y为[128,]
        #这个操作将会使x的shape从[b,28,28]变成[b,28*28]
        x = tf.reshape(x,[-1,28*28])
        with tf.GradientTape() as tape:
            h1 = x @w1 + b1
            h1 = tf.nn.relu(h1)
            h2 = h1 @ w2 + b2
            h2 = tf.nn.relu(h2)
            out = h2 @ w3 +b3

            y_onehot = tf.one_hot(y,depth = 10)
            #mse = mean(sum(y-out)^2)
            loss = tf.square(y_onehot - out)
            loss = tf.reduce_mean(loss)
        grads = tape.gradient(loss,[w1,b1,w2,b2,w3,b3])
        #原地更新
        w1.assign_sub(lr * grads[0])
        b1.assign_sub(lr * grads[1])
        w2.assign_sub(lr * grads[2])
        b2.assign_sub(lr * grads[3])
        w3.assign_sub(lr * grads[4])
        b3.assign_sub(lr * grads[5])

        """w1 = w1 - lr *grads[0]
        b1 = b1 - lr *grads[1]
        w2 = w2 - lr *grads[2]
        b2 = b2 - lr *grads[3]
        w3 = w3 - lr *grads[4]
        b3 = b3 - lr *grads[5]
         """
        if step %100 ==0:
            print(epoch,step,"loss",float(loss))

二、简单版之二

import  tensorflow as tf
from    tensorflow import keras
from    tensorflow.keras import datasets, layers, optimizers
#%%
import  matplotlib
from    matplotlib import pyplot as plt
# Default parameters for plots
matplotlib.rcParams['font.size'] = 20
matplotlib.rcParams['figure.titlesize'] = 20
matplotlib.rcParams['figure.figsize'] = [9, 7]
matplotlib.rcParams['font.family'] = ['STKaiTi']
matplotlib.rcParams['axes.unicode_minus']=False 

#对数据进行预处理的函数
def preprocess(x, y): 
    print(x.shape,y.shape)
    x = tf.cast(x, dtype=tf.float32) / 255.
    x = tf.reshape(x, [-1, 28*28])
    y = tf.cast(y, dtype=tf.int32)
    y = tf.one_hot(y, depth=10)
    return x,y

#划分训练集、测试集
(x, y), (x_test, y_test) = datasets.mnist.load_data()
print('x:', x.shape, 'y:', y.shape, 'x test:', x_test.shape, 'y test:', y_test)
#进行批处理
batchsz = 512
train_db = tf.data.Dataset.from_tensor_slices((x, y))
train_db = train_db.shuffle(1000)
train_db = train_db.batch(batchsz)
#训练数据进行预处理
train_db = train_db.map(preprocess)
train_db = train_db.repeat(20)
#对测试数据进行预处理
test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))
test_db = test_db.shuffle(1000).batch(batchsz).map(preprocess)
x,y = next(iter(train_db))
print('train sample:', x.shape, y.shape)

def main():

    # learning rate
    lr = 1e-2
    accs,losses = [], []
    #后面要用到梯度下降,必须是variable类型的
    w1, b1 = tf.Variable(tf.random.normal([784, 256], stddev=0.1)), tf.Variable(tf.zeros([256]))

    w2, b2 = tf.Variable(tf.random.normal([256, 128], stddev=0.1)), tf.Variable(tf.zeros([128]))

    w3, b3 = tf.Variable(tf.random.normal([128, 10], stddev=0.1)), tf.Variable(tf.zeros([10]))

    for step, (x,y) in enumerate(train_db):
        x = tf.reshape(x, (-1, 784))

        with tf.GradientTape() as tape:

            # layer1.
            h1 = x @ w1 + b1
            h1 = tf.nn.relu(h1)
            # layer2
            h2 = h1 @ w2 + b2
            h2 = tf.nn.relu(h2)
            # output
            out = h2 @ w3 + b3
            # out = tf.nn.relu(out)

            # compute loss
            # [b, 10] - [b, 10]
            #计算平方损失函数
            loss = tf.square(y-out)
            # [b, 10] => scalar
            loss = tf.reduce_mean(loss)
        grads = tape.gradient(loss, [w1, b1, w2, b2, w3, b3]) 
        #下面是初级写法
        w1.assign_sub(lr * grads[0])
        b1.assign_sub(lr * grads[1])
        w2.assign_sub(lr * grads[2])
        b2.assign_sub(lr * grads[3])
        w3.assign_sub(lr * grads[4])
        b3.assign_sub(lr * grads[5])
        '''
        for p, g in zip([w1, b1, w2, b2, w3, b3], grads):
            p.assign_sub(lr * g)
        '''
        # 每80就print
        if step % 80 == 0:
            print(step, 'loss:', float(loss))
            losses.append(float(loss))
         #计算当前训练结果下的效果
        if step %80 == 0:
            total, total_correct = 0., 0
            for x, y in test_db:
                # layer1.
                h1 = x @ w1 + b1
                h1 = tf.nn.relu(h1)
                # layer2
                h2 = h1 @ w2 + b2
                h2 = tf.nn.relu(h2)
                # output
                out = h2 @ w3 + b3
                # [b, 10] => [b]
                pred = tf.argmax(out, axis=1)
                # convert one_hot y to number y
                y = tf.argmax(y, axis=1)
                # bool type
                correct = tf.equal(pred, y)
                # bool tensor => int tensor => numpy
                total_correct += tf.reduce_sum(tf.cast(correct, dtype=tf.int32)).numpy()
                total += x.shape[0]

            print(step, 'Evaluate Acc:', total_correct/total)
            accs.append(total_correct/total)

    plt.figure()
    x = [i*80 for i in range(len(losses))]
    plt.plot(x, losses, color='C0', marker='s', label='训练')
    plt.ylabel('MSE')
    plt.xlabel('Step')
    plt.legend()
    plt.savefig('train.jpg')

    plt.figure()
    plt.plot(x, accs, color='C1', marker='s', label='测试')
    plt.ylabel('准确率')
    plt.xlabel('Step')
    plt.legend()
    plt.savefig('test.jpg')

if __name__ == '__main__':
    main()

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值