首页 > 其他 > 详细

[深度学习] Pytorch学习(一)—— torch tensor

时间:2019-10-20 00:30:45      阅读:173      评论:0      收藏:0      [点我收藏+]

[深度学习] Pytorch学习(一)—— torch tensor

学习笔记 . 记录 分享 .

学习的代码环境:python3.6 torch1.3 vscode+jupyter扩展

#%%
import torch
print(torch.__version__)
# 查看CUDA GPU是否可用
a = torch.cuda.is_available()
print(a)

#%%
# torch.randperm
x = torch.randperm(6)
print(x)

#%%
# torch.view 
x = x.view(2,3)     # 相当于numpy的reshape
print(x)

#%%
# tensor.numpy()
# 以及下面的from_numpy,tensor与numpy数组都共享内存
a = torch.ones(2,2)
print(a)
b = a.numpy()
print(b)

#%%
# torch.from_numpy
import numpy as np
a = np.ones(3)
print(a)
b = torch.from_numpy(a)
print(b)

#%%
# troch.cat
xx = torch.cat((x,x),0)
xxx = torch.cat((x,x),1)
print(xx)
print(xxx)


#%%
# torch.tensor
scalar = torch.tensor(3.1415926)
print(scalar)
print(scalar.shape)

# 特别的 如果一个张量中只有一个元素,可用tensor.item方法
scalar.item()
# xx.item()     # 否则会报错
# ValueError: only one element tensors can be converted to Python scalars


#%%
f = x.float()
print(f)
print(f.dtype)
b = torch.HalfTensor(2,3)
b

#%%
# .cuda()
cpu_a = torch.rand(4,3)
print(cpu_a.type())
gpu_a = cpu_a.cuda()
print(gpu_a.type())
a = gpu_a.cpu()
print(a.type())


#%% 
# 与numpy的类似操作
# eg: max randn ... 但描述按哪个轴 用dim=
print(a)
m = torch.max(a,dim=1)
print(m[0])
print(m[1])


#%%
# 以_为结尾的,均会改变本身值
aa = torch.ones(3,4)
bb = torch.eye(3,4)
aa.add_(bb)
print(aa)

[深度学习] Pytorch学习(一)—— torch tensor

原文:https://www.cnblogs.com/importGPX/p/11706317.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!