python打卡day48

python 复制代码
import torch
python 复制代码
# 生成一个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])

python 复制代码
# 生成一个形状为(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])

python 复制代码
# 标量与张量相加(广播)
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])

python 复制代码
# 不同形状张量相加
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])

python 复制代码
# 标量与张量相乘(广播)
result = tensor_a * 2  # 标量2会被广播成[[2,2],[2,2]]
print("\n标量广播乘法:\n", result)

标量广播乘法:

tensor(\[2, 4,

6, 8])

python 复制代码
# 不同形状张量相乘
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])

@浙大疏锦行

相关推荐
ShineWinsu12 分钟前
对于Coze—AI:SDK的解析
人工智能·python·ai·sdk·项目·coze·字节跳动
右耳朵猫AI33 分钟前
Python周刊2026W38 | 标准流编码修复、PEP 845/846 草案、解析器提速 10%、集合字典二次复杂度
python·ai·数据科学
微软技术分享37 分钟前
大模型网络结构:模型接口测试用例参考
python
Bruce_Liuxiaowei2 小时前
Python 实例赋值遮蔽类属性:一个从不报错的静默陷阱
开发语言·python·语法糖
做运维的阿瑞2 小时前
Python 标准库汇总:分类速览与常用模块清单
linux·运维·python
why-geo2 小时前
Hermes Agent 与 Python 的会产生什么样的碰撞
人工智能·python·ai编程
正经教主2 小时前
【FDE系列】阶段2:Day 29:FastAPI 进阶 — Pydantic 模型与完整 CRUD 实战
人工智能·python·fde
gCode Teacher 格码致知2 小时前
Pandas教学-6:coerce详解
python·pandas
梦在远山后2 小时前
Electron 与 FastAPI 如何完成流式 Agent 对话
python·langchain·agent
大衛說2 小时前
12 · 文件 I/O 与序列化
python