Pytorch基本数据类型

一、数据类型对比

PythonPyTorch
IntIntTensor of size()
floatFloatTensor of size()
Int arrayIntTensor of size [d1,d2,…]
float arrayFloatTensor of size [d1,d2,…]
string

二、如何表达string

  1. One-hot in coding
    1. 例如:dog : [1 0],cat :[0 1]
    2. 对于复杂的编码来说,用One-hot进行编码会变得十分稀疏
  2. Embedding(待补)
    1. Word2vec
    2. glove

三、PyTorch数据类型

Data typedtypeCPU tensorGPU tensor
32位floattorch.float32 or torch.floattorch.FloatTensortorch.cuda.FloatTensor
64位floattorch.float64 or torch.doubletorch.DoubleTensortorch.cuda.DoubleTensor
32位int(signed)torch.int32 or torch.inttorch.IntTensortorch.cuda.IntTensor
64位int(signed)torch.float64 or torch.longtorch.LongTensortorch.cuda.LongTensor
8为int(unsigned)torch.uint8torch.ByteTensortorch.cuda.ByteTensor

四、Tensor常用函数

  1. a.type():返回数据类型
a = torch.rand(2,3) # 随机生成2行3列数据
print(a.type()) # 输出为torch.FloatTensor
  1. isinstance(obj,type):检查数据类型
#检查数据类型是否为FloatTensor
a = rand(1)
print(isinstance(a,torch.FloatTensor)) # true
a = a.cuda() #在gpu上跑数据
print(isinstance(a,torch.cuda.FloatTensor)) # true
  1. 标量dim=0
    1. torch.tensor():生成标量
    2. obj.shape:返回obj的维度大小
    3. len(obj.shape):返回dim
    4. obj.size():返回元素个数
#检查数据类型是否为FloatTensor
b = torch.tensor(1.3)
print(b.shape) #torch.Size([])
print(len(b.shape)) #0
print(b.size()) #torch.Size([])
  1. 向量dim=1
    1. torch.tensor([...]):生成标量
    2. np.ones(shape):生成全为1的向量
c = torch.tensor([1.1])
print(c) # tensor([1.1000])

d = torch.tensor([1.1,2.2])
print(d) # tensor([1.1000, 2.2000])

e = torch.FloatTensor(1) #random初始化
print(e) # tensor([0.])

f = torch.FloatTensor(5)
print(f) # tensor([0.0000e+00, 0.0000e+00, 1.4013e-45, 0.0000e+00, 1.4013e-45])

g = np.ones(2)
print(g) # [1. 1.]
print(torch.from_numpy(g)) # tensor([1., 1.], dtype=torch.float64)

h = torch.ones(2)
print(h.shape) # torch.Size([2])
  1. dim=2
    1. torch.rand(h,w):生成行h,列w
    2. size():0行,1列
    3. shape[]:返回维度的个数
i = torch.rand(2,3)
print(i) # tensor([[0.2588, 0.7782, 0.3236],
        #  [0.4545, 0.5833, 0.1202]])
print(i.shape) # torch.Size([2, 3])
print(i.size(0)) # 2
print(i.size(1)) # 3
print(i.shape[0]) # 2
print(i.shape[1]) # 3
  1. dim=3
    1. torch.rand(a,b,c)
    2. obj.numel():返回内存大小
    3. obj.dim():返回dim
j = torch.rand(1,2,3)
print(j)
# tensor([[[0.1600, 0.7410, 0.5799],
#         [0.9968, 0.0704, 0.9750]]])

print(j.shape) # torch.Size([1, 2, 3])
print(j[0])
# tensor([[0.1600, 0.7410, 0.5799],
#        [0.9968, 0.0704, 0.9750]])

print(list(j.shape)) # [1, 2, 3]

print(j.numel()) # 内存大小 = 6
print(j.dim()) #返回dim = 3
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值