当前位置:网站首页>Pytorch基础——(1)张量(tensor)的初始化
Pytorch基础——(1)张量(tensor)的初始化
2022-07-06 03:18:00 【七上八下的黑】
导入pytorch库
import torch初始化张量
DEVICE = "cuda" if torch.cuda.is_available() else "cpu" # 设置运行的设备
x = torch.tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.float32, device=DEVICE, requires_grad=True)其他初始化方法
1.产生0-1之间均匀分布的2x3的张量
x = torch.rand((2, 3))
print(x)2.产生0-1之间正态分布的2x3的张量
x = torch.randn((2, 3))
print(x)3. 产生3-10之间随机整数的2x3的张量
x = torch.randint(3, 10, (2, 3))
print(x)4.产生和input格式一样的张量
input = torch.rand((3, 3))
x = torch.rand_like(input)5.产生初始值为0,步长为1,不包含终止值的序列
x = torch.arange(start=0, end=10, step=1)![]()
6.产生初始值为0,终止值为9,总步数为11的序列
x = torch.linspace(start=0, end=9, steps=11)
7.产生对角线是0-1均匀分布的张量
x = torch.diag(torch.rand(5))
转换数据类型
我们常用numpy数据类型,但是它不能直接在torch中运算,因此需要转换数据类型。
import numpy as np
x = np.zeros((5, 5))
print(x)
print(x.dtype)
x_torch = torch.from_numpy(x) # 从numpy变成torch张量类型
print(x_torch)
print(x_torch.dtype)
x_back = x_torch.numpy() # 从torch张量变回numpy类型
print(x_back)
print(x_back.dtype)注意:
出现 Numpy is not available 报错时,是numpy和pytorch的版本不匹配。
边栏推荐
猜你喜欢
随机推荐
Linear programming matlab
Leetcode problem solving -- 108 Convert an ordered array into a binary search tree
深入探究指针及指针类型
[padding] an error is reported in the prediction after loading the model weight attributeerror: 'model' object has no attribute '_ place‘
Redis cache breakdown, cache penetration, cache avalanche
[ruoyi] set theme style
Custom attribute access__ getattribute__/ Settings__ setattr__/ Delete__ delattr__ method
StrError & PERROR use yyds dry inventory
Pelosi: Congress will soon have legislation against members' stock speculation
codeforces每日5題(均1700)-第六天
暑期刷题-Day3
Prototype design
Four logs of MySQL server layer
How to do function test well
Detailed use of dbutils # yyds dry goods inventory #
[risc-v] external interrupt
Advanced learning of MySQL -- Fundamentals -- isolation level of transactions
Idea push rejected solution
Crazy, thousands of netizens are exploding the company's salary
MySQL advanced notes
![BUUCTF刷题笔记——[极客大挑战 2019]EasySQL 1](/img/37/c38a933ce7fa5d2b8fa597965ffcb2.png)







