《Pytorch深度学习和图神经网络(卷 1)》学习笔记——第四章

标量某个具体数字
向量是多个标量
矩阵是多个向量
张量是多个矩阵(元素属同一数据类型的多维矩阵)

torch.tensor可以转换成张量
torch.Tensor可以指定张量形状或内容,不初始化值,除非用torch.rand()

#NumPy数组转换成张量
anp=np.asarray([1,2])
print(anp)
#输出:[1 2]

a=torch.tensor(anp)或torch.from_numpy(anp)
print(a)
#输出:tensor([1, 2], dtype=torch.int32)


#指定形状
b=torch.Tensor(2,3)
print(b)
#输出: tensor([[5.7283e+16, 8.7861e-43, 5.7283e+16],
#           [8.7861e-43, 5.7296e+16, 8.7861e-43]])

#指定内容
b=torch.Tensor([2,3])
print(b)
#输出: tensor([2., 3.])

torch.is_tensor()张量判断
torch.numel()张量元素个数

张量默认32位浮点型,或64位整形(有无小数点),打印不显示
用张量.dtype查看类型
用张量.type(torch.类型Tensor)转换类型,或张量.类型()。

张量.shape 张量.size() 张量形状
anp.shape anp.size numpy形状

条件类型切片

x=[[1,10],[2,10]]
x_tensor=torch.Tensor(x)
x_numpy=np.asarray(x)
print(x_numpy,x_tensor)
#输出:[[ 1 10]
#       [ 2 10]] 
# tensor([[ 1., 10.],
#        [ 2., 10.]])

print(x_tensor[x_tensor>5])
#输出:tensor([10., 10.])

print(x_numpy[x_numpy>5])
#输出:[10 10]

NumPy数据转换成张量后不要进行
nparray+=1 要用 nparray=nparray+1 ,否则共用内存。

torch.randn()根据形状生成随机值

生成线性空间随机值

print(torch.arange(1,10,step=2))
print(torch.linspace(1,9,steps=5))
#输出:tensor([1, 3, 5, 7, 9])       int64
#      tensor([1., 3., 5., 7., 9.])  float32

数据维度变换

x=torch.tensor([[1,2,3]
                ,[4,5,6]
                ,[7,8,9]])
print(torch.reshape(x,(1,-1)))
print(x.reshape([1,-1]))
print(torch.view(x,(1,-1)))
#输出: tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9]])

将值为1的维度全部去掉,只去掉某个维度的加上dim=n

print(torch.tensor([[[[1,2,3]]]]))
print(torch.squeeze(torch.tensor([[[[1,2,3]]]],)))
#输出: tensor([[[[1, 2, 3]]]])
#       tensor([1, 2, 3])
print(torch.squeeze(torch.tensor([[[[1,2,3]]]]),dim=2))
#输出: tensor([[[1, 2, 3]]])

torch.cat()实现数据连接,dim=0以行为单位连接

# x=torch.tensor([[1,2]
#                 ,[3,4]])
# y=torch.tensor([[5,6]
#                 ,[7,8]])
# print(torch.cat([x,y],dim=0))
#输出: tensor([[1, 2],
#        [3, 4],
#        [5, 6],
#        [7, 8]])
# print(torch.cat([x,y],dim=1))
#输出:tensor([[1, 2, 5, 6],
#             [3, 4, 7, 8]])

torch.chunk()按照指定维度拆分几部分

# a=torch.tensor([[1,2,3]
#                 ,[4,5,6]
#                 ,[7,8,9]])
# print(torch.chunk(a,chunks=3,dim=0))
#输出(tensor([[1, 2, 3]]), tensor([[4, 5, 6]]), tensor([[7, 8, 9]]))

# print(torch.chunk(a,chunks=3,dim=1))
#输出(tensor([[1],
#            [4],
#            [7]]), 
#    tensor([[2],
#           [5],
#           [8]]), 
#    tensor([[3],
#           [6],
#           [9]]))

torch.gather()对张量数据进行检索
沿着维度0,按照index形状进行取值排列

x=torch.tensor([[1,2,3]
               ,[4,5,6]
               ,[7,8,9]
               ,[10,11,12]])
print(torch.gather(x,dim=0,index=torch.tensor([[0,1,3]
                                              ,[1,1,1]
                                              ,[2,2,2]
                                              ,[0,1,3]])))
#输出:tensor([[ 1,  5, 12],
#              [ 4,  5,  6],
#              [ 7,  8,  9],
#              [ 1,  5, 12]])

print(torch.gather(x,dim=1,index=torch.tensor([[0,1,2]
                                              ,[1,1,1]
                                              ,[2,2,2]
                                              ,[0,1,2]])))
#输出:tensor([[ 1,  2,  3],
#              [ 5,  5,  5],
#              [ 9,  9,  9],
#              [10, 11, 12]])             

torch.index_select()取出整列整行的数据

print(torch.index_select(x,dim=0,index=torch.tensor(2)))
#输出:tensor([[7, 8, 9]])
print(torch.index_select(x,dim=1,index=torch.tensor(2)))    
#输出:tensor([[ 3],
#              [ 6],
#              [ 9],
#              [12]])                             

按照指定阈值对张量进行过滤

x=torch.tensor([[1,2,3]
               ,[4,5,6]
               ,[7,8,9]
               ,[10,11,12]])
mask=x.ge(5) #大于等于5
print(mask)
print(torch.masked_select(x,mask))
#输出:tensor([[False, False, False],
#        [False,  True,  True],
#        [ True,  True,  True],
#        [ True,  True,  True]])
#tensor([ 5,  6,  7,  8,  9, 10, 11, 12])

找出非0索引

eye=torch.eye(4)
print(eye)
print(torch.nonzero(eye))
#输出:tensor([[1., 0., 0., 0.],
#        [0., 1., 0., 0.],
#        [0., 0., 1., 0.],
#        [0., 0., 0., 1.]])
#tensor([[0, 0],
#        [1, 1],
#        [2, 2],
#        [3, 3]])

根据条件从多张量取值

b=torch.tensor([[5,6,7],[2,8,0]])
c=torch.ones_like(b)
print(c)
print(torch.where(b>5,b,c))
#tensor([[1, 1, 1],
#        [1, 1, 1]])
#tensor([[1, 6, 7],
#        [1, 8, 1]])

根据阈值进行数据截断

x=torch.tensor([[[1,2,3],
                 [4,5,6],
                 [7,8,9]]])
print(torch.clamp(x,min=3,max=7))
#输出:tensor([[[3, 3, 3],
#               [4, 5, 6],
#               [7, 7, 7]]])

获取数据中最大值和最小值及其索引

x=torch.tensor([[1,2,3],
                 [4,5,6],
                 [7,8,9]])
print(torch.max(x,dim=0))
#torch.return_types.max(
#values=tensor([7, 8, 9]),
#indices=tensor([2, 2, 2]))
print(torch.max(x,dim=1))
#torch.return_types.max(
#values=tensor([3, 6, 9]),
#indices=tensor([2, 2, 2]))
print(torch.min(x,dim=0))
#torch.return_types.min(
#values=tensor([1, 2, 3]),
#indices=tensor([0, 0, 0]))
print(torch.max(x,dim=1))
#torch.return_types.max(
#values=tensor([3, 6, 9]),
#indices=tensor([2, 2, 2]))

不太明白grad_fn(x)求的什么玩意,x**2与x*x求y.grad_fn(x)结果都不一致

from torch.autograd import Variable
x=Variable(torch.tensor([2.]),requires_grad=True)
y=x**2
z=y*3
print(y.grad_fn(x)) 
print(z.grad_fn(x)) 
#tensor([8.], grad_fn=<MulBackward0>)
#(tensor([6.], grad_fn=<MulBackward0>), None)


from torch.autograd import Variable
x=Variable(torch.tensor([2.]),requires_grad=True)
y=x*x
z=y*3
print(y.grad_fn(x)) 
print(z.grad_fn(x)) 
#(tensor([4.], grad_fn=<MulBackward0>), tensor([4.], grad_fn=<MulBackward0>))
#(tensor([6.], grad_fn=<MulBackward0>), None)

用backward()自动求导

from torch.autograd import Variable
x=Variable(torch.tensor([2.]),requires_grad=True)
y=x**2
z=y*3
z.backward()
print(x.grad) # 2x2x3=12

定义模型结构的步骤与方法

class LogicNet(nn.Module):
    def __init__(self,inputdim,hiddendim,outputdim):#初始化网络结构
        super(LogicNet,self).__init__()
        # self.Linear1 = nn.Linear(inputdim,hiddendim) #定义全连接层
        # self.Linear2 = nn.Linear(hiddendim,outputdim)#定义全连接层
        self.add_module("Linear1",nn.Linear(inputdim,hiddendim))#等价写法
        self.add_module("Linear2",nn.Linear(hiddendim,outputdim))
        self.criterion = nn.CrossEntropyLoss() #定义交叉熵函数
model=LogicNet(2,3,2)
print(model)#等价model.eval()
for name,module in model.named_children():
    print(name,module)
#LogicNet(
#  (Linear1): Linear(in_features=2, out_features=3, bias=True)
#  (Linear2): Linear(in_features=3, out_features=2, bias=True)
#  (criterion): CrossEntropyLoss()
#)
#类似效果
#Linear1 Linear(in_features=2, out_features=3, bias=True)
#Linear2 Linear(in_features=3, out_features=2, bias=True)
#criterion CrossEntropyLoss()

从模型中获取参数,前两条是L1的,后两条是L2的。
param.size()获取形状

for name,param in model.named_parameters():
    print(name,param)

#Linear1.weight 
#Parameter containing:
#tensor([[-6.9422e-01,  4.7358e-01],
#        [ 2.9420e-01, -5.8486e-01],
#        [-4.8780e-01,  5.1695e-04]], requires_grad=True)
#Linear1.bias 
#Parameter containing:
#tensor([-0.4755,  0.3347,  0.2030], requires_grad=True)

#Linear2.weight 
#Parameter containing:
#tensor([[-0.1614, -0.0926, -0.2895],
#        [ 0.5527, -0.4828, -0.3293]], requires_grad=True)
#Linear2.bias 
#Parameter containing:
#tensor([ 0.1613, -0.1190], requires_grad=True)

model.state_dict()获取模型Parameter和buffer参数,但不能获取Variable

params=model.state_dict()
print(params)
#OrderedDict([
#('Linear1.weight', tensor([[-0.1427, -0.4139],
#        [ 0.6661,  0.2446],
#        [-0.4138,  0.2357]])), 
#('Linear1.bias', tensor([ 0.6566, -0.3813, -0.3115])), 
#('Linear2.weight', tensor([[-0.4086, -0.4664,  0.4307],
#        [ 0.1386,  0.5670, -0.1505]])), 
#('Linear2.bias', tensor([0.3785, 0.1274]))])
print(params['Linear1.weight'])
#tensor([[-0.1427, -0.4139],
#        [ 0.6661,  0.2446],
#        [-0.4138,  0.2357]])

保存和载入模型参数

torch.save(model.state_dict(),'model.pth')
print(model.load_state_dict(torch.load('./model.pth')))
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch是一种深度学习框架,它提供了丰富的工具和函数,使得构建和训练神经网络变得更加简单和高效。它被广泛应用于计算机视觉、自然语言处理等领域。 深度学习是一种机器学习方法,其目标是通过模拟人脑神经网络的工作原理来实现各种人工智能任务。深度学习模型通常由许多层神经元组成,每一层都通过学习将输入转换为输出,最终实现复杂的模式识别和预测。 神经网络是一种扩展了传统神经网络的模型,用于处理数据。数据是由节点和边组成的数据结构,常用于表示社交网络、推荐系统等领域的关系。传统的神经网络无法直接处理数据,而神经网络通过引入积等操作,使神经网络能够有效地处理数据,从而提高了对结构的建模能力。 深度学习神经网络在很多领域都取得了显著的进展。例如,在计算机视觉中,深度学习模型可以通过大量的像数据进行训练,实现物体识别、像生成等任务。而神经网络则可以用于分析社交网络中的用户关系、预测交通网络中的交通流量等。它们的电子版提供了对应的理论和实践指导,帮助学者和工程师更好地理解和应用这些技术。 总而言之,PyTorch深度学习神经网络的电子版提供了学习和实践深度学习神经网络的材料,对于研究者和开发者来说是非常有价值的资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值