Day48 随机函数与广播机制

@浙大疏锦行

python 复制代码
import torch

# 0维标量
scalar = torch.randn(())
print(f"标量: {scalar}, 形状: {scalar.shape}")

# 1维向量
vector = torch.randn(4)
print(f"向量: {vector}, 形状: {vector.shape}")

# 2维矩阵
matrix = torch.randn(2, 3)
print(f"矩阵: {matrix}, 形状: {matrix.shape}")

# 3维张量(模拟单张 RGB 图像)
tensor_3d = torch.randn(3, 64, 64)
print(f"3维张量形状: {tensor_3d.shape}")

# 4维张量(模拟批量图像,batch=2)
tensor_4d = torch.randn(2, 3, 128, 128)
print(f"4维张量形状: {tensor_4d.shape}")

import torch

# torch.rand 示例
rand_tensor = torch.rand(2, 2)
print(f"均匀分布: {rand_tensor}, 形状: {rand_tensor.shape}")

# torch.randint 示例
int_tensor = torch.randint(low=1, high=100, size=(3,))
print(f"随机整数: {int_tensor}, 形状: {int_tensor.shape}")

# torch.normal 示例
mean = torch.tensor([5.0, 10.0])
std = torch.tensor([2.0, 3.0])
normal_tensor = torch.normal(mean, std)
print(f"自定义正态分布: {normal_tensor}, 形状: {normal_tensor.shape}")


import torch
import torch.nn as nn

input_tensor = torch.randn(4, 3, 64, 64)  # batch=4
print(f"输入尺寸: {input_tensor.shape}")

conv1 = nn.Conv2d(3, 32, kernel_size=5, stride=2, padding=2)
conv_output = conv1(input_tensor)
print(f"卷积后尺寸: {conv_output.shape}")  # 预期: [4, 32, 32, 32] (stride=2 减半)

pool = nn.MaxPool2d(2, 2)
pool_output = pool(conv_output)
print(f"池化后尺寸: {pool_output.shape}")  # 预期: [4, 32, 16, 16]

flattened = pool_output.view(pool_output.size(0), -1)
print(f"展平后尺寸: {flattened.shape}")  # 预期: [4, 8192] (32*16*16)

import torch

A = torch.randn(3, 2, 4)  # batch=3, 2x4 矩阵
B = torch.randn(1, 4, 3)  # batch=1, 4x3 矩阵
result = A @ B  # B 扩展 batch 到3,结果: (3, 2, 3)

print(f"A 形状: {A.shape}\nB 形状: {B.shape}\n结果形状: {result.shape}")
相关推荐
噜噜噜阿鲁~2 分钟前
python学习笔记 | 8.2、函数式编程-返回函数
笔记·python·学习
中二痞17 分钟前
下载Python 版本,环境变量变更以及PyCharm更换python版本
开发语言·python·pycharm
SilentSamsara20 分钟前
标准库精讲:collections/itertools/functools/pathlib 实战
开发语言·vscode·python·青少年编程·pycharm
小郑加油21 分钟前
python学习Day8-9天:函数(def)的基础运用
python·学习
2401_8242226921 分钟前
如何卸载并重装Oracle Grid_Deinstall脚本与ASM磁盘清理
jvm·数据库·python
qq_4142565724 分钟前
生产库如何利用Navicat实现配置特定触发器事件调度_提高管理效率
jvm·数据库·python
2301_7756398930 分钟前
mysql如何查看服务器支持的存储引擎_使用SHOW ENGINES命令
jvm·数据库·python
love530love31 分钟前
Python 3.12 解决 MediaPipe “no attribute ‘solutions‘” 终极方案:基于全版本硬核实测的避坑指南
开发语言·人工智能·windows·python·comfyui·mediapipe·solutions
爱码小白32 分钟前
Python 类五大方法 完整版学习笔记
开发语言·python
a7963lin32 分钟前
html标签怎样表示搜索框_input type=search语义优化【操作】
jvm·数据库·python