TensorFlow深度学习第五章-第5章 TensorFlow 进阶

1、应用张量合并与分割操作完成下列任务。

(1) 随机生成16*16的R、G、B单通道图片,并将它们合并为一张彩色图片

import tensorflow as tf
q=tf.random.normal([1,16,16,1],mean=125,stddev=20)
w=tf.random.normal([1,16,16,1],mean=125,stddev=20)
e=tf.random.normal([1,16,16,1],mean=125,stddev=20)
r=tf.concat([q,w,e],axis=3)
# r=tf.reduce_max(r)看他的最大值
print('1111111111111111111',r)

在这里插入图片描述

(2)随机生成一张16*16的彩色图片,并将它们拆分为3张单通道图片

import tensorflow as tf
x=tf.random.normal([16,16,3])
# result=tf.split(x,axis=2,num_or_size_splits=[1,16,16,1])
result=tf.unstack(x,axis=2)
print(result)

在这里插入图片描述

(3)张量A存储1班和2班级各10名同学的英语、数学成绩,张量B存储这些学生的语文和政治成绩,学生顺序与A相同,将这两个张量合并为一个张量来存储2个班级各10名同学所有成绩。

import tensorflow as tf
a=tf.random.uniform([2,10,2],maxval=100)
b=tf.random.uniform([2,10,2],maxval=100)
c=tf.concat([a,b],axis=2)
print('3333333333333333',c)

在这里插入图片描述

(4)张量A存储1班和2班级各10名同学的英语、数学、语文和政治成绩,张量B存储3班和4班各10名同学的这4门课程成绩,将这两个张量合并为一个张量来存储4个班级各10名同学所有成绩。

print(end='\n')
import tensorflow as tf
a=tf.random.uniform([2,10,4],maxval=100)
b=tf.random.uniform([2,10,4],maxval=100)
c=tf.concat([a,b],axis=0)
print('4444444444444444',c)

在这里插入图片描述

2、已知张量loss中存有10个样本的训练误差,求这组误差的最大值、最小值和均值。

import tensorflow as tf

x=tf.random.normal([10])
max=tf.reduce_max(x)
print(max)
min=tf.reduce_min(x)
print(min)
mean=tf.reduce_mean(x)
print(mean)

在这里插入图片描述

3、已知张量score存有2个班级各10名学生的英语、数学、语文和政治成绩,求所有成绩的最高分、最低分、平均分和得分总和。

import tensorflow as tf

score = tf.random.normal([2, 10, 4])
min = tf.reduce_min(score)
max = tf.reduce_max(score)
mean = tf.reduce_mean(score)
sum = tf.reduce_sum(score)
print(min)
print(score)

在这里插入图片描述

4、已知张量score存有2个班级各10名学生的英语、数学、语文和政治成绩,求所有学生语文成绩的最高分、最低分、平均分和得分总和。

import tensorflow as tf
score=tf.random.normal([2,10,4])
score_chinese=tf.gather(score,[2],axis=2)
print('score_chinese',score_chinese)
score_max_chinese=tf.reduce_max(score_chinese)
# print(score_max_chinese)
# pred=tf.argmax(score_max_chinese,axis=2)
print('score_max_chinese',score_max_chinese)

在这里插入图片描述

5、张量y存有10个样本的标签,张量y_pred存有这10个样本经网络模型测试的结果,计算网络模型的准确率。

# 5、张量y存有10个样本的标签,张量y_pred存有这10个样本经网
# 络模型测试的结果,计算网络模型的准确率。
import tensorflow as tf

y = tf.constant([1,2,3,5,6,4,7,8,9,15])
# y = tf.nn.softmax(y, axis=0)#输出转换为概率
# print(y)
y_pred = tf.argmax(y, axis=0)#选取预测值,最大值所在下标
print('y_pred------>', y_pred)
y = tf.random.uniform([10], dtype=tf.int64, maxval=10)
out = tf.equal(y_pred, y)  # 预测值与真实值比较
print(out)
out = tf.cast(out, dtype=tf.float32)  # 布尔型转 int 型
correct = tf.reduce_sum(out)  # 统计 True 的个数
print(correct)
print('准确率:------》',correct/10)

在这里插入图片描述

6、张量x存有10张16*16的彩色图片,将图片上下各扩充一行0、左右各扩充2列0,请给出扩充语句。

# 6、张量x存有10张16*16的彩色图片,将图片上下各扩充一行0、
# 左右各扩充2列0,请给出扩充语句。
#
# mode 可以取三个值,分别是"CONSTANT" ,“REFLECT”,“SYMMETRIC”
# mode=“CONSTANT” 填充0
# mode="REFLECT"映射填充,上下(1维)填充顺序和paddings是相反的,左右(零维)顺序补齐
# mode="SYMMETRIC"对称填充,上下(1维)填充顺序是和paddings相同的,左右(零维)对称补齐
import tensorflow as tf

x = tf.random.normal([10, 16, 16, 3])
y = tf.pad(x, [[0, 0], [1, 1], [2, 2], [0, 0]])
print(y)

在这里插入图片描述

7、张量x存有1张16*16的彩色图片,将图片像素值限幅在50到200之间,如何实现。

# 张量x存有1张16*16的彩色图片,将图片像素值限幅
# 在50到200之间,如何实现。
import tensorflow as tf
x = tf.random.normal([1, 16, 16, 3],mean=125,stddev=100)
print('x', x)
pic = tf.minimum(tf.maximum(x, 50), 200)  # 方法一
# pic=tf.clip_by_value(x,50,200)#方法二
print('pic---------->>', pic)

在这里插入图片描述

8、简要概况一下tf.gather、tf.gather_nd、tf.boolean_mask、tf.where使用要点。

在这里插入图片描述
在这里插入图片描述
tf.gather和tf.gather_nd都是从tensor中取出index标注的部分,不同之处在于,gather一般只使用一个index来标注,而gather_nd可以使用多个index。

9、理解tf.scatter_nd和tf.meshgrid函数调用的结果

indices= tf.constant([[2], [5], [1]])
updates= tf.constant([
    [[1,1], [2, 2]],

    [[3,3], [4, 4]],

    [[5,5], [6, 6]]
])
y =tf.scatter_nd(indices, updates, [8, 2, 2])
print(y)

在这里插入图片描述

a =tf.constant([0, 5, 10]) 
b =tf.constant([0, 5, 10, 15, 20])
A, B =tf.meshgrid(a,b)
print(A)
print(B)

在这里插入图片描述

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

10、运行mnist_tensor.py程序,理解程序执行过程。

#%%
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 
import  tensorflow as tf
from    tensorflow import keras
from    tensorflow.keras import datasets, layers, optimizers
import  os

os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
print(tf.__version__)


def preprocess(x, y): 
    # [b, 28, 28], [b]
    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))#构造Dataset
train_db = train_db.shuffle(1000)
train_db = train_db.batch(batchsz)
train_db = train_db.map(preprocess)
train_db = train_db.repeat(20)
# Step0: 准备要加载的numpy数据
# Step1: 使用 tf.data.Dataset.from_tensor_slices() 函数进行加载
# Step2: 使用 shuffle() 打乱数据
# Step3: 使用 map() 函数进行预处理
# Step4: 使用 batch() 函数设置 batch size 值
# Step5: 根据需要 使用 repeat() 设置是否循环迭代数据集,就是重复

#测试级
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)
# print(x[0], y[0])




#%%
def main():

    # learning rate
    lr = 1e-2
    accs,losses = [], []#准确率,损失值
    # 784 => 512
    w1, b1 = tf.Variable(tf.random.normal([784, 256], stddev=0.1)), tf.Variable(tf.zeros([256]))
    # 512 => 256
    w2, b2 = tf.Variable(tf.random.normal([256, 128], stddev=0.1)), tf.Variable(tf.zeros([128]))
    # 256 => 10
    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):
        # [b, 28, 28] => [b, 784]
        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])#计算梯度
        for p, g in zip([w1, b1, w2, b2, w3, b3], grads):#梯度更新
            p.assign_sub(lr * g)
        # print
        if step % 80 == 0:
            print(step, 'loss:', float(loss))
            losses.append(float(loss))
 
        if step %80 == 0:#测试集
            # evaluate/test
            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.svg')

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

if __name__ == '__main__':
    main()

注释:

  1. test_db = tf.data.Dataset.from_tensor_slices((x_test, y_test))
    思路:
    Step0: 准备要加载的numpy数据
    Step1: 使用 tf.data.Dataset.from_tensor_slices() 函数进行加载
    Step2: 使用 shuffle() 打乱数据
    Step3: 使用 map() 函数进行预处理
    Step4: 使用 batch() 函数设置 batch size 值
    Step5: 根据需要 使用 repeat() 设置是否循环迭代数据集
    该函数是dataset核心函数之一,它的作用是把给定的元组、列表和张量等数据进行特征切片。切片的范围是从最外层维度开始的。如果有多个特征进行组合,那么一次切片是把每个组合的最外维度的数据切开,分成一组一组的。
    假设我们现在有两组数据,分别是特征和标签,为了简化说明问题,我们假设每两个特征对应一个标签。之后把特征和标签组合成一个tuple,那么我们的想法是让每个标签都恰好对应2个特征,而且像直接切片,比如:[f11, f12] [t1]。f11表示第一个数据的第一个特征,f12表示第1个数据的第二个特征,t1表示第一个数据标签。那么tf.data.Dataset.from_tensor_slices就是做了这件事情:
    在这里插入图片描述

  2. p.assign_sub(lr * g)

https://blog.csdn.net/qq_36512295/article/details/100607483
w1.assign_sub(a)就是w1=w1-a
1.0中assign_sub前是tf,2.0中它的前面不是tf而是张量

  1. for p, g in zip([w1, b1, w2, b2, w3, b3], grads):#梯度更新在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值