当前位置:网站首页>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的版本不匹配。
边栏推荐
- Performance test method of bank core business system
- OCR文字識別方法綜述
- [padding] an error is reported in the prediction after loading the model weight attributeerror: 'model' object has no attribute '_ place‘
- Microsoft Research, UIUC & Google research | antagonistic training actor critic based on offline training reinforcement learning
- Reverse repackaging of wechat applet
- jsscript
- SAP ALV颜色代码对应颜色(整理)
- Who is the winner of PTA
- [unity3d] GUI control
- XSS challenges bypass the protection strategy for XSS injection
猜你喜欢

Microsoft Research, UIUC & Google research | antagonistic training actor critic based on offline training reinforcement learning

XSS challenges绕过防护策略进行 XSS 注入

【Kubernetes 系列】一文學會Kubernetes Service安全的暴露應用

C # create self host webservice

Princeton University, Peking University & UIUC | offline reinforcement learning with realizability and single strategy concentration

NR modulation 1

codeforces每日5题(均1700)-第六天

Overview of OCR character recognition methods

C language judgment, ternary operation and switch statement usage

Research on cooperative control of industrial robots
随机推荐
JS regular filtering and adding image prefixes in rich text
SD卡报错“error -110 whilst initialising SD card
ERA5再分析资料下载攻略
真机无法访问虚拟机的靶场,真机无法ping通虚拟机
What are the principles of software design (OCP)
【SLAM】ORB-SLAM3解析——跟踪Track()(3)
手写数据库客户端
Codeforces 5 questions par jour (1700 chacune) - jour 6
[kubernetes series] learn the exposed application of kubernetes service security
【paddle】加载模型权重后预测报错AttributeError: ‘Model‘ object has no attribute ‘_place‘
如何做好功能测试
codeforces每日5題(均1700)-第六天
[ruoyi] set theme style
Four logs of MySQL server layer
MySQL Server层四个日志
svg拖动点裁剪图片js特效
My C language learning records (blue bridge) -- files and file input and output
An article about liquid template engine
[Li Kou] the second set of the 280 Li Kou weekly match
How to choose PLC and MCU?