【Day48】
DAY 48 随机函数与广播机制
知识点回顾:
- 随机张量的生成:torch.randn函数
- 卷积和池化的计算公式(可以不掌握,会自动计算的)
- pytorch的广播机制:加法和乘法的广播机制
ps:numpy运算也有类似的广播机制,基本一致
作业:自己多借助ai举几个例子帮助自己理解即可
import torch
import torch.nn as nn# 生成标量(0维张量)
scalar = torch.randn(())
print(f"标量: {scalar}, 形状: {scalar.shape}")# 生成向量(1维张量)
vector = torch.randn(5) # 长度为5的向量
print(f"向量: {vector}, 形状: {vector.shape}")# 生成矩阵(2维张量)
matrix = torch.randn(3, 4) # 3行4列的矩阵
print(f"矩阵:{matrix},矩阵形状: {matrix.shape}")# 生成3维张量(常用于图像数据的通道、高度、宽度)
tensor_3d = torch.randn(3, 224, 224) # 3通道,高224,宽224
print(f"3维张量形状: {tensor_3d.shape}")# 生成4维张量(常用于批量图像数据:[batch, channel, height, width])
tensor_4d = torch.randn(2, 3, 224, 224) # 批量大小为2,3通道,高224,宽224
print(f"4维张量形状: {tensor_4d.shape}")# torch.rand() 生成在 [0, 1) 范围内均匀分布的随机数
x = torch.rand(3, 2) # 生成3x2的张量
print(f"均匀分布随机数: {x}, 形状: {x.shape}")# torch.randint() 生成指定范围内的随机整数
x = torch.randint(low=0, high=10, size=(3,)) # 生成3个0到9之间的整数
print(f"随机整数: {x}, 形状: {x.shape}")# torch.normal() 生成指定均值和标准差的正态分布随机数
mean = torch.tensor([0.0, 0.0])
std = torch.tensor([1.0, 2.0])
x = torch.normal(mean, std) # 生成两个正态分布随机数
print(f"正态分布随机数: {x}, 形状: {x.shape}")# 一维张量与二维张量相加
a = torch.tensor([[1, 2, 3], [4, 5, 6]]) # 形状: (2, 3)
b = torch.tensor([10, 20, 30]) # 形状: (3,)# 广播后:b被扩展为[[10, 20, 30], [10, 20, 30]]
result = a + b
print(result)# 输出维度测试
# 生成输入张量 (批量大小, 通道数, 高度, 宽度)
input_tensor = torch.randn(1, 3, 32, 32) # 例如CIFAR-10图像
print(f"输入尺寸: {input_tensor.shape}")
标量: -0.85379958152771, 形状: torch.Size([])
向量: tensor([0.5027, 1.4197, 1.0714, 0.0436, 2.6530]), 形状: torch.Size([5])
矩阵:tensor([[ 1.5927, 1.3624, 1.0813, 0.6308],[ 1.3860, 2.5055, -0.8512, 0.7769],[-3.2656, 1.2633, -0.8792, -1.8409]]),矩阵形状: torch.Size([3, 4])
3维张量形状: torch.Size([3, 224, 224])
4维张量形状: torch.Size([2, 3, 224, 224])
均匀分布随机数: tensor([[0.8363, 0.3158],[0.2642, 0.9451],[0.8439, 0.4370]]), 形状: torch.Size([3, 2])
随机整数: tensor([4, 9, 0]), 形状: torch.Size([3])
正态分布随机数: tensor([-0.6898, 2.8864]), 形状: torch.Size([2])
tensor([[11, 22, 33],[14, 25, 36]])
输入尺寸: torch.Size([1, 3, 32, 32])
浙大疏锦行