神经网络-Day48

发布于:2025-06-09 ⋅ 阅读:(16) ⋅ 点赞:(0)
import torch
 
# 示例1:生成形状为 (3, 4) 的随机张量(2维)
tensor1 = torch.randn(3, 4)
print("tensor1 shape:", tensor1.shape)
print("tensor1内容:\n", tensor1)
 
# 示例2:生成形状为 (2, 3, 5) 的随机张量(3维,常用于图像批次)
tensor2 = torch.randn(2, 3, 5)  # 假设 batch_size=2,通道数=3,尺寸=5x5
print("\ntensor2 shape:", tensor2.shape)
print("tensor2内容:\n", tensor2)
 
# 示例3:生成指定数据类型的张量(如 float64)
tensor3 = torch.randn(2, 2, dtype=torch.float64)
print("\ntensor3 dtype:", tensor3.dtype)

# 张量A:形状 (3, 1),张量B:形状 (1, 4)
A = torch.tensor([[1], [2], [3]])  # shape (3, 1)
B = torch.tensor([[1, 2, 3, 4]])     # shape (1, 4)
C = A + B  # 广播后形状变为 (3, 4)
print("A + B 的结果:\n", C)
# 张量X:形状 (2, 3, 4),张量Y:形状 (4,)
X = torch.randn(2, 3, 4)  # shape (2, 3, 4)
Y = torch.tensor([1, 2, 3, 4])  # shape (4,) → 等价于 (1, 1, 4)
Z = X * Y  # 广播后Y形状变为 (1, 1, 4),与X的 (2, 3, 4) 兼容
print("X * Y 的形状:", Z.shape)
import numpy as np
 
# 数组A:形状 (3, 1),数组B:形状 (1, 4)
A = np.array([[1], [2], [3]])
B = np.array([[1, 2, 3, 4]])
C = A + B  # 结果与 PyTorch 示例1完全一致
print("Numpy A + B 的结果:\n", C)

import torch.nn as nn
 
# 输入:batch_size=1,通道数=1,尺寸=5x5
x = torch.randn(1, 1, 5, 5)  
# 卷积层:输入通道=1,输出通道=2,卷积核=3x3,步长=1,填充=0
conv_layer = nn.Conv2d(in_channels=1, out_channels=2, kernel_size=3)
output = conv_layer(x)  # 输出形状:(1, 2, 3, 3)(自动计算:(5-3+1)=3)
print("卷积输出形状:", output.shape)

# 池化层:核大小=2x2,步长=2
pool_layer = nn.MaxPool2d(kernel_size=2, stride=2)
pooled = pool_layer(output)  # 输出形状:(1, 2, 1, 1)(3//2=1)
print("池化输出形状:", pooled.shape)

@浙大疏锦行