当前位置:网站首页>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的版本不匹配。
边栏推荐
- Tidb ecological tools (backup, migration, import / export) collation
- Audio audiorecord binder communication mechanism
- MPLS experiment
- Shell 传递参数
- Sign SSL certificate as Ca
- Modeling specifications: naming conventions
- JS regular filtering and adding image prefixes in rich text
- An article about liquid template engine
- [pointer training - eight questions]
- These are not very good
猜你喜欢
【SLAM】lidar-camera外参标定(港大MarsLab)无需二维码标定板
Who is the winner of PTA
codeforces每日5题(均1700)-第六天
【RISC-V】外部中断
【Kubernetes 系列】一文学会Kubernetes Service安全的暴露应用
[ruoyi] enable Mini navigation bar
[Li Kou] the second set of the 280 Li Kou weekly match
Web security SQL injection vulnerability (1)
【指针训练——八道题】
XSS challenges绕过防护策略进行 XSS 注入
随机推荐
three.js网页背景动画液态js特效
JS音乐在线播放插件vsPlayAudio.js
Some problem records of AGP gradle
Explore pointers and pointer types in depth
八道超经典指针面试题(三千字详解)
jsscript
resulttype和resultmap的区别和应用场景
[risc-v] external interrupt
SD卡报错“error -110 whilst initialising SD card
js凡客banner轮播图js特效
Handwriting database client
Single instance mode of encapsulating PDO with PHP in spare time
These are not very good
The next industry outlet: NFT digital collection, is it an opportunity or a foam?
Getting started with applet cloud development - getting user search content
SD card reports an error "error -110 whilst initializing SD card
Crazy, thousands of netizens are exploding the company's salary
Safety science to | travel, you must read a guide
建模规范:命名规范
教你用Pytorch搭建一个自己的简单的BP神经网络( 以iris数据集为例 )