1 Star 0 Fork 0

ninesun/nlp入门+实战

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
2.pytorch.py 2.60 KB
一键复制 编辑 原始数据 按行查看 历史
ninesun 提交于 2022-07-24 00:25 . 新增pytorch基础语法信息
import torch
import numpy as np
t1 = torch.tensor([[1, -1], [1, -1]])
print(t1)
t2 = torch.tensor(np.array([[1, 2, 3], [4, 5, 6]]))
print(t2)
t3_0 = torch.empty(3, 4) # 创建3行4列的空tensor,会用无用数据去填充
t3_1 = torch.ones([3, 4]) # 创建3行4列全为1的tensor
t3_2 = torch.zeros([3, 4]) # 创建3行4列全为0的tensor
t3_3 = torch.rand([3, 4]) # 创建3行4列随机值的tensor,随机区间为(0,1)
t3_4 = torch.randint(low=0, high=10, size=[3, 4]) # 创建3行4列随机整数的tensor,随机区间为(low,high)
t3_5 = torch.randn([3, 4]) # 创建3行4列随机数的tensor,随机值的均值为0,方差为1
t4 = torch.tensor(np.arange(1))
print(t4)
print(t4.item())
t5_1 = torch.randint(low=0, high=10, size=[3, 4])
t5_2 = t5_1.numpy()
print(t5_1)
print(t5_2)
t6 = torch.randint(low=0, high=10, size=[3, 4])
print(t6)
print(t6.size())
t7 = torch.randint(low=0, high=10, size=[3, 4])
print(t7)
print(t7.view(2, 6))
t8 = torch.randint(low=0, high=10, size=[3, 4])
print(t8)
print(t8.dim())
t9 = torch.randint(low=0, high=10, size=[3, 4])
print(t9)
print(t9.max())
t10 = torch.randint(low=0, high=10, size=[3, 4])
print(t10)
print(t10.t())
t11 = torch.randint(low=0, high=10, size=[3, 4])
print(t11)
print(t11[1, 3]) # 获取第二行第3列的值
t12 = torch.randint(low=0, high=10, size=[3, 4])
print(t12)
t12[1, 2] = 1000
print(t12)
t13 = torch.randn(2, 3); # 2行3列
print(t13)
t13 = torch.transpose(t13, 0, 1)
print(t13) # 将t13变为3行2列
t14 = np.array([[[1, 2, 3], [4, 5, 6]]])
t14 = torch.tensor(t14)
print(t14.size())
print(t14)
t15 = torch.randn([3, 4])
print(t15.dtype)
print("----------------------------------")
t16 = torch.randn([3, 4], dtype=torch.double)
print(t16.dtype)
print("----------------------------------")
t17 = torch.LongTensor([1, 2])
print(t17)
print("----------------------------------")
t18 = t17.new_ones(5, 3, dtype=torch.float)
t18_1 = torch.randn(5, 3)
print(t18)
print(t18_1)
print(t18 + t18_1)
print(torch.add(t18, t18_1))
print(t18.add(t18_1))
t18.add_(t18_1) # 带下划线的方法会对t18进行就地修改
print(t18)
print("----------------------------------")
t19 = torch.randn(3, 3)
print("t19:", t19)
print("t19+10=", t19 + 10)
print("----------------------------------")
if torch.cuda.is_available():
device = torch.device("cuda") # cuda device对象
y = torch.ones_like(t19, device=device) # 创建一个cuda的tensor
x = t19.to(device) # 使用方法把t19转化为cuda的tensor
z = x + y
print(z)
print(z.to("cpu", torch.double)) # .to方法也能够同时设置类型
else:
print("您的设备不支持gpu运算")
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/ninesuntec/nlp-entry-practice.git
git@gitee.com:ninesuntec/nlp-entry-practice.git
ninesuntec
nlp-entry-practice
nlp入门+实战
master

搜索帮助