当前位置:网站首页>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的版本不匹配。
边栏推荐
- Era5 reanalysis data download strategy
- 电机控制反Park变换和反Clarke变换公式推导
- Item 10: Prefer scoped enums to unscoped enums.
- Descriptor implements ORM model
- EDCircles: A real-time circle detector with a false detection control 翻译
- resulttype和resultmap的区别和应用场景
- OCR文字識別方法綜述
- [concept] Web basic concept cognition
- 适合程序员学习的国外网站推荐
- Polymorphic day02
猜你喜欢

IPv6 jobs

Résumé des méthodes de reconnaissance des caractères ocr
![[kubernetes series] learn the exposed application of kubernetes service security](/img/61/4564230feeb988886fe595e3125ef4.png)
[kubernetes series] learn the exposed application of kubernetes service security

Exness foreign exchange: the governor of the Bank of Canada said that the interest rate hike would be more moderate, and the United States and Canada fell slightly to maintain range volatility

Tomb. Weekly update of Finance (February 7 - February 13)

适合程序员学习的国外网站推荐

Selenium share

NR modulation 1

下一个行业风口:NFT 数字藏品,是机遇还是泡沫?

MySQL advanced notes
随机推荐
Arabellacpc 2019 (supplementary question)
OCR文字识别方法综述
Résumé des méthodes de reconnaissance des caractères ocr
Map sorts according to the key value (ascending plus descending)
IPv6 comprehensive experiment
适合程序员学习的国外网站推荐
【概念】Web 基础概念认知
JS音乐在线播放插件vsPlayAudio.js
XSS challenges bypass the protection strategy for XSS injection
Some problem records of AGP gradle
Descriptor implements ORM model
svg拖动点裁剪图片js特效
深入刨析的指针(题解)
Era5 reanalysis data download strategy
Performance analysis of user login TPS low and CPU full
继承day01
Performance test method of bank core business system
Restful style
深度解析指针与数组笔试题
暑期刷题-Day3