pytorch基本使用_01

import torch
import numpy as np
# string 在torch中对string不支持,1 可以通过向量one-hot来进行分类
# 2 embedding word2vec glove
# type check
a = torch.randn(2, 3)
a.type()
# 'torch.FloatTensor'
type(a)
# <class 'torch.Tensor'>
isinstance(a, torch.FloatTensor)
# True
'''
标量 ->dimension 0 tensor=0
'''
a = torch.tensor(1.)
print(a)
# tensor(1.)
a.shape
# torch.Size([])
'''
向量 ->dimension 1 tensor=1
使用场景:bias,linear input
'''
a = torch.tensor([1.])
print(a)
# tensor([1.])
a.shape
# torch.Size([1])
torch.FloatTensor(2)
# 生成一个随机的torch.FloatTensor类型的一维张量(向量),这里2表示长度不是维度
data = np.ones(2)
a = torch.from_numpy(data)
# 从numpy中引入
'''
矩阵-> dimension 2 tensor=2
使用场景:带有batch的linear input
'''
a = torch.randn(2, 3)
print(a)
# tensor([[-0.6360,  0.4261,  0.1899],
#         [-0.5830,  1.3612,  0.4152]])
# 生成随机初始化的两行三列矩阵
a.shape
# torch.Size([2, 3])
# shape 可索引
a.shape[0]
# 2
a.shape[1]
# 3
'''
三维-> dimension 3 tensor=3
使用场景:RNN input batch
'''
a = torch.rand(1,2,3)
print(a)
# tensor([[[0.2800, 0.4040, 0.5966],
#          [0.9353, 0.3688, 0.9595]]])
a.shape
# torch.Size([1, 2, 3])
# shape 可索引
print(a.shape[0])
# 使用list()方法可以将tensor转化为列表
'''
四维-> dimension 4 tensor=4
使用场景:CNN[b,c,h,w]
'''
a = torch.rand(2, 1, 3, 4)
print(a)
# ensor([[[[0.4213, 0.0433, 0.7946, 0.1104],
#           [0.6130, 0.5273, 0.0487, 0.8266],
#           [0.0761, 0.2096, 0.3812, 0.7941]]],
#
#         [[[0.7658, 0.5500, 0.8646, 0.3867],
#           [0.3629, 0.7928, 0.3055, 0.9012],
#           [0.9158, 0.9801, 0.5993, 0.6423]]]])

'''
--------------------------------
'''
# function
a.numel()
# 计算大小
a.dim()
# 返回维度

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值