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}")
相关推荐
过期的秋刀鱼!3 分钟前
带替换的采样
人工智能·python·算法·决策树·机器学习
Python私教5 分钟前
AI Agent 可观测性不只是日志:一套可回放的多步执行链
人工智能·后端·python
Python私教18 分钟前
模型越强越不需要 Skills?我把 AI 编程能力拆成 4 层
人工智能·后端·python
databook29 分钟前
如何快速构建一个数据科学应用?从零到上线
python·机器学习·scikit-learn
上下求索,莫负韶华35 分钟前
切面学习笔记
笔记·python·学习
2301_806709381 小时前
国内知名的生活水箱制造厂有哪些
python·生活
学掌门2 小时前
超级菜鸟怎么学习数据分析?
python·学习·数据分析
鸿芯微控科技2 小时前
压电纳米定位分辨率怎么测?噪声、带宽、最小可检测位移与Python分析
开发语言·python·噪声分析·压电执行器·纳米定位·位移测量
用户7783366132112 小时前
从 0 搭一个关键词排名监控:核心思路 + 可运行代码
后端·python·api
Fanta丶2 小时前
14.Python闭包、装饰器
python