import torch
# 生成一個3x3的標準正態分布隨機張量
random_tensor = torch.randn(3, 3)
print("隨機張量:\n", random_tensor)
隨機張量:
?tensor([[-0.9343, -0.3254, ?0.6991],
? ? ? ? [-1.7157, ?1.7171, -0.4322],
? ? ? ? [ 0.6004, -1.1050, -0.2178]])
# 生成一個形狀為(2, 4)的隨機張量
random_tensor_2 = torch.randn(2, 4)
print("\n2x4隨機張量:\n", random_tensor_2)
2x4隨機張量:
?tensor([[-0.0638, -0.6070, ?0.0341, -0.5346],
? ? ? ? [-2.1379, -0.5141, ?0.0484, ?0.0098]])
# 標量與張量相加(廣播)
tensor_a = torch.tensor([[1, 2], [3, 4]])
scalar = 5
result = tensor_a + scalar # 標量5會被廣播成[[5,5],[5,5]]
print("\n標量廣播加法:\n", result)
標量廣播加法:
?tensor([[6, 7],
? ? ? ? [8, 9]])
# 不同形狀張量相加
tensor_b = torch.tensor([[10], [20]]) # 形狀(2,1)
result = tensor_a + tensor_b # tensor_b會被廣播成[[10,10],[20,20]]
print("\n不同形狀張量加法:\n", result)
不同形狀張量加法:
?tensor([[11, 12],
? ? ? ? [23, 24]])
# 標量與張量相乘(廣播)
result = tensor_a * 2 # 標量2會被廣播成[[2,2],[2,2]]
print("\n標量廣播乘法:\n", result)
標量廣播乘法:
?tensor([[2, 4],
? ? ? ? [6, 8]])
# 不同形狀張量相乘
tensor_c = torch.tensor([100, 200]) # 形狀(2,)
result = tensor_a * tensor_c # tensor_c會被廣播成[[100,200],[100,200]]
print("\n不同形狀張量乘法:\n", result)
不同形狀張量乘法:
?tensor([[100, 400],
? ? ? ? [300, 800]])
@浙大疏錦行