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

[深度学习] 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)
原文地址:https://www.cnblogs.com/importGPX/p/11706317.html