来自于 https://tangshusen.me/Dive-into-DL-PyTorch/#/

官方文档 https://pytorch.org/docs/stable/tensors.html

文章目录

      • 来自于 https://tangshusen.me/Dive-into-DL-PyTorch/#/
      • 官方文档 https://pytorch.org/docs/stable/tensors.html
  • 模型构建
      • 实例化MLP
    • ` Module`的子类
      • `Sequential`
      • `ModuleList`
      • `ModuleDict`
  • 构造复杂的模型
  • 访问模型参数
    • 初始化模型参数
    • 自定义初始化方法
    • 共享模型参数
  • 自定义层
    • 不含模型参数的自定义层
    • 含模型参数的自定义层
  • 读取与存储
    • 读写Tensor
    • 读写模型
      • 仅保存和加载模型参数(state_dict)
      • 保存和加载整个模型
  • 模型的GPU计算

模型构建

Module类是nn模块里提供的一个模型构造类,是所有神经网络模块的基类,我们可以继承它来定义我们想要的模型。下面继承Module类构造本节开头提到的多层感知机。这里定义的MLP类重载了Module类的__init__函数和forward函数。它们分别用于创建模型参数和定义前向计算。前向计算也即正向传播。

import torch
from torch import nnclass MLP(nn.Module):# 声明带有模型参数的层,这里声明了两个全连接层def __init__(self,**kwargs):# 调用MLP父类Module的构造函数来进行必要的初始化。这样在构造实例时还可以指定其他函数# 参数,如“模型参数的访问、初始化和共享”一节将介绍的模型参数paramssuper(MLP,self).__init__(**kwargs)self.hidden = nn.Linear(784,256)self.act = nn.ReLU()self.output = nn.Linear(256,10)# 定义模型的前向计算,即如何根据输入x计算返回所需要的模型输出def forward(self,x):a = self.act(self.hidden(x))return self.output(a)

实例化MLP

x = torch.rand(2,784)
net = MLP()
print(net)
net(x)
MLP((hidden): Linear(in_features=784, out_features=256, bias=True)(act): ReLU()(output): Linear(in_features=256, out_features=10, bias=True)
)tensor([[-0.0370, -0.0794,  0.1573, -0.0460, -0.0318, -0.0653, -0.2214,  0.0340,0.0324,  0.1943],[-0.1231,  0.0116,  0.2601, -0.0035,  0.0520, -0.0406, -0.0722,  0.0060,-0.1080,  0.3512]], grad_fn=<AddmmBackward>)

Module的子类

Sequential

当模型的前向计算为简单串联各个层的计算时,Sequential类可以通过更加简单的方式定义模型。这正是Sequential类的目的:它可以接收一个子模块的有序字典(OrderedDict)或者一系列子模块作为参数来逐一添加Module的实例,而模型的前向计算就是将这些实例按添加的顺序逐一计算。

下面我们实现一个与Sequential类有相同功能的MySequential类。这或许可以帮助读者更加清晰地理解Sequential类的工作机制。

class MySequential(nn.Module):from collections import OrderedDictdef __init__(self,*args):super(MySequential,self).__init__()if len(args) ==1 and isinstance(args[0],OrderedDict):for key,module in args[0].item():self.add_module(key,module)else:for idx ,module in enumerate(args):self.add_module(str(idx),module)def forward(self,input):for module in self._modules.values():input=module(input)return input
net = MySequential(nn.Linear(784,256),nn.ReLU(),nn.Linear(256,10)
)
print(net)
net(x)
MySequential((0): Linear(in_features=784, out_features=256, bias=True)(1): ReLU()(2): Linear(in_features=256, out_features=10, bias=True)
)tensor([[ 0.1224, -0.0237, -0.0957,  0.0353, -0.0509, -0.1116, -0.0750, -0.0186,-0.0620,  0.1194],[ 0.1232, -0.0997, -0.1981, -0.0289,  0.0448,  0.0705, -0.1342,  0.0394,-0.1696,  0.1937]], grad_fn=<AddmmBackward>)

ModuleList

ModuleList接收一个子模块的列表作为输入,然后也可以类似List那样进行append和extend操作:

net = nn.ModuleList([nn.Linear(784,256),nn.ReLU()])
net.append(nn.Linear(256,10))
print(net[-1])
print(net)
Linear(in_features=256, out_features=10, bias=True)
ModuleList((0): Linear(in_features=784, out_features=256, bias=True)(1): ReLU()(2): Linear(in_features=256, out_features=10, bias=True)
)

既然Sequential和ModuleList都可以进行列表化构造网络,那二者区别是什么呢。ModuleList仅仅是一个储存各种模块的列表,这些模块之间没有联系也没有顺序(所以不用保证相邻层的输入输出维度匹配),而且没有实现forward功能需要自己实现,所以上面执行net(torch.zeros(1, 784))会报NotImplementedError;而Sequential内的模块需要按照顺序排列,要保证相邻层的输入输出大小相匹配,内部forward功能已经实现。

class MyModule(nn.Module):def __init__(self):super(MyModule, self).__init__()self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])def forward(self, x):# ModuleList can act as an iterable, or be indexed using intsfor i, l in enumerate(self.linears):x = self.linears[i // 2](x) + l(x)return x

另外,ModuleList不同于一般的Python的list,加入到ModuleList里面的所有模块的参数会被自动添加到整个网络中,下面看一个例子对比一下。

class Module_ModuleList(nn.Module):def __init__(self):super(Module_ModuleList,self).__init__()self.lineears = nn.ModuleList([nn.Linear(10,10)])class Module_List(nn.Module):def __init__(self):super(Module_List,self).__init__()self.linears  = [nn.Linear(10,10)]net1 = Module_ModuleList()
net2 = Module_List()
print('net1:')
for p in net1.parameters():print(p.size())
print('net2:')
for p in net2.parameters():print(p.size())
net1:
torch.Size([10, 10])
torch.Size([10])
net2:

ModuleDict

ModuleDict接收一个子模块的字典作为输入, 然后也可以类似字典那样进行添加访问操作:

net = nn.ModuleDict({'linear': nn.Linear(784, 256),'act': nn.ReLU(),
})
net['output'] = nn.Linear(256, 10) # 添加
print(net['linear']) # 访问
print(net.output)
print(net)
Linear(in_features=784, out_features=256, bias=True)
Linear(in_features=256, out_features=10, bias=True)
ModuleDict((act): ReLU()(linear): Linear(in_features=784, out_features=256, bias=True)(output): Linear(in_features=256, out_features=10, bias=True)
)

和ModuleList一样,ModuleDict实例仅仅是存放了一些模块的字典,并没有定义forward函数需要自己定义。同样,ModuleDict也与Python的Dict有所不同,ModuleDict里的所有模块的参数会被自动添加到整个网络中。

构造复杂的模型

虽然上面介绍的这些类可以使模型构造更加简单,且不需要定义forward函数,但直接继承Module类可以极大地拓展模型构造的灵活性。下面我们构造一个稍微复杂点的网络FancyMLP。在这个网络中,我们通过get_constant函数创建训练中不被迭代的参数,即常数参数。在前向计算中,除了使用创建的常数参数外,我们还使用Tensor的函数和Python的控制流,并多次调用相同的层。

class FancyMLP(nn.Module):def __init__(self,**kwargs):super(FancyMLP,self).__init__(**kwargs)self.rand_weight = torch.rand((20,20),requires_grad=False)self.linear = nn.Linear(20,20)def forward(self,x):x = self.linear(x)x=nn.functional.relu(torch.mm(x,self.rand_weight.data)+1)# 复用全连接层。等价于两个全连接层共享参数x=self.linear(x)while x.norm().item()>1:x/=2if x.norm().item() <0.8:x*=10return x.sum()
X = torch.rand(2, 20)
net = FancyMLP()
print(net)
net(X)
FancyMLP((linear): Linear(in_features=20, out_features=20, bias=True)
)tensor(-0.4913, grad_fn=<SumBackward0>)

因为FancyMLP和Sequential类都是Module类的子类,所以我们可以嵌套调用它们。

class NestMLP(nn.Module):def __init__(self, **kwargs):super(NestMLP, self).__init__(**kwargs)self.net = nn.Sequential(nn.Linear(40, 30), nn.ReLU()) def forward(self, x):return self.net(x)net = nn.Sequential(NestMLP(), nn.Linear(30, 20), FancyMLP())X = torch.rand(2, 40)
print(net)
net(X)
Sequential((0): NestMLP((net): Sequential((0): Linear(in_features=40, out_features=30, bias=True)(1): ReLU()))(1): Linear(in_features=30, out_features=20, bias=True)(2): FancyMLP((linear): Linear(in_features=20, out_features=20, bias=True))
)tensor(0.3448, grad_fn=<SumBackward0>)

访问模型参数

print(type(net.named_parameters()))
for name, param in net.named_parameters():print(name, param.size())
<class 'generator'>
0.net.0.weight torch.Size([30, 40])
0.net.0.bias torch.Size([30])
1.weight torch.Size([20, 30])
1.bias torch.Size([20])
2.linear.weight torch.Size([20, 20])
2.linear.bias torch.Size([20])

可见返回的名字自动加上了层数的索引作为前缀。 我们再来访问net中单层的参数。对于使用Sequential类构造的神经网络,我们可以通过方括号[]来访问网络的任一层。索引0表示隐藏层为Sequential实例最先添加的层。

for name, param in net[0].named_parameters():print(name, param.size(), type(param))
net.0.weight torch.Size([30, 40]) <class 'torch.nn.parameter.Parameter'>
net.0.bias torch.Size([30]) <class 'torch.nn.parameter.Parameter'>

返回的param的类型为torch.nn.parameter.Parameter,其实这是Tensor的子类,和Tensor不同的是如果一个Tensor是Parameter,那么它会自动被添加到模型的参数列表里,来看下面这个例子。

class MyModel(nn.Module):def __init__(self,**kwargs):super(MyModel,self).__init__(**kwargs)self.weight1 = nn.Parameter(torch.rand(20,20))self.weight2 = torch.rand(20,20)def forward(self,x):pass
n = MyModel()
for name,param in n.named_parameters():print(name)
weight1

因为Parameter是Tensor,即Tensor拥有的属性它都有,比如可以根据data来访问参数数值,用grad来访问参数梯度。

weight_0 = list(net[0].parameters())[0]
print(weight_0.data)
print(weight_0.grad)
Y=net(X)
Y.backward()
print(weight_0.grad)
tensor([[ 0.0622,  0.0654,  0.1042,  ..., -0.1514,  0.0846,  0.1257],[ 0.0139,  0.0422, -0.1171,  ...,  0.0142, -0.0565, -0.1016],[ 0.0405,  0.1393,  0.0782,  ...,  0.0151, -0.0972, -0.1105],...,[ 0.1332,  0.0998, -0.0605,  ..., -0.0061,  0.0571, -0.1063],[-0.1366, -0.1384,  0.0207,  ..., -0.0695,  0.0810, -0.0280],[ 0.0659,  0.1505,  0.1109,  ..., -0.0085, -0.0435, -0.0354]])
None
tensor([[-0.0022, -0.0218, -0.0053,  ..., -0.0030, -0.0048, -0.0103],[ 0.0000,  0.0000,  0.0000,  ...,  0.0000,  0.0000,  0.0000],[ 0.0864,  0.3693,  0.1030,  ...,  0.1747,  0.1237,  0.4375],...,[ 0.0000,  0.0000,  0.0000,  ...,  0.0000,  0.0000,  0.0000],[ 0.0000,  0.0000,  0.0000,  ...,  0.0000,  0.0000,  0.0000],[-0.0101, -0.0433, -0.0121,  ..., -0.0205, -0.0145, -0.0514]])

初始化模型参数

from torch.nn import init
for name, param in net.named_parameters():if 'weight' in name:init.normal_(param, mean=0, std=0.01)print(name, param.data)
0.net.0.weight tensor([[ 0.0216, -0.0093,  0.0016,  ...,  0.0019,  0.0130, -0.0026],[ 0.0042, -0.0017,  0.0056,  ..., -0.0125, -0.0168, -0.0058],[-0.0046, -0.0081,  0.0077,  ...,  0.0097, -0.0123, -0.0045],...,[-0.0062, -0.0014, -0.0027,  ...,  0.0026,  0.0015, -0.0152],[-0.0068, -0.0066, -0.0049,  ...,  0.0021,  0.0121, -0.0018],[ 0.0132,  0.0139,  0.0135,  ...,  0.0050,  0.0105, -0.0064]])
1.weight tensor([[ 2.0540e-02,  1.3424e-02, -1.4864e-02, -1.3467e-02, -9.4628e-03,9.7067e-04, -1.5009e-02, -1.5539e-02, -7.9077e-03,  1.0551e-02,-9.0278e-03,  1.7459e-02, -1.8690e-03,  5.0541e-03, -1.9378e-03,1.6113e-02,  2.4179e-03, -3.9226e-03, -2.4951e-03, -1.0519e-02,-1.7979e-03, -3.0638e-03,  5.2334e-04,  1.1851e-02, -1.5307e-02,-2.3555e-02, -1.2260e-02, -8.4837e-03,  1.4811e-03, -8.6963e-03],[-7.8196e-03,  1.4540e-02,  2.6614e-03, -1.0711e-02,  1.5188e-02,3.4464e-04, -1.6673e-02,  1.4700e-02, -1.1430e-02, -3.0225e-03,1.7065e-03, -1.7021e-02,  1.0656e-02,  1.1011e-02,  4.2047e-03,-1.2465e-02, -6.2476e-03, -1.0956e-02,  3.1987e-03, -4.9426e-03,-1.2004e-03,  4.4904e-03, -1.0595e-02, -1.1566e-02,  1.2842e-02,2.6868e-03,  4.0029e-03,  1.3305e-02,  4.9962e-03,  3.2664e-03],[-3.7490e-03, -9.1373e-03, -7.6418e-03,  1.1468e-02, -7.3277e-03,1.0504e-02, -1.2510e-02,  2.0066e-02, -3.8254e-03, -1.3952e-03,-8.9643e-03, -7.9015e-03,  3.0163e-03,  4.8269e-04, -1.6445e-02,-4.2277e-03, -1.2489e-02,  7.0872e-03, -4.0340e-04, -6.6422e-03,2.0632e-03, -4.4652e-03, -2.5231e-03, -1.1253e-02,  1.6601e-02,-4.5058e-03,  4.3239e-03,  1.0291e-02,  2.0269e-02, -1.0369e-02],[-1.3724e-02, -8.1422e-04,  1.7627e-03, -5.2986e-03, -3.4685e-03,-2.0445e-03, -1.1192e-02,  1.0989e-02, -1.1012e-03, -1.7664e-02,-3.6856e-03,  9.6825e-03,  1.5568e-03,  8.0502e-03,  5.8132e-04,-9.6213e-03, -7.0347e-04,  5.8105e-03,  2.8272e-04,  1.1797e-02,-7.6907e-03,  2.2619e-02,  1.2308e-02,  1.8024e-02,  1.7888e-03,-1.7745e-03,  7.1993e-03, -3.5203e-04, -1.9954e-02, -1.8694e-02],[ 7.0645e-03,  8.1665e-04,  1.4387e-02,  1.2969e-02,  1.8918e-03,-5.8327e-03, -1.0239e-02,  8.8525e-03, -5.7654e-03,  1.7141e-03,-2.8454e-03,  1.3615e-02, -1.0575e-02, -3.0326e-03,  6.0094e-03,-1.0895e-02,  2.0619e-03,  1.5329e-03,  1.4229e-03, -3.2453e-03,-1.7779e-03,  9.6478e-03, -2.3171e-02,  1.4701e-02,  1.9202e-02,9.1253e-03, -6.1181e-03, -1.0587e-03,  2.0379e-04,  1.8809e-03],[ 1.2714e-02,  3.9214e-03,  5.0589e-04,  6.2322e-03,  1.3992e-02,1.4027e-03, -4.3150e-03,  1.0659e-03, -7.9712e-04, -1.9232e-02,-1.0893e-02,  2.5453e-02, -2.4113e-03, -8.1766e-03, -5.1438e-03,-1.5338e-02, -3.9863e-03,  5.6107e-03, -1.1374e-03,  5.2210e-03,-1.6869e-02, -5.0722e-03, -6.0378e-03,  3.9245e-05, -1.0497e-02,2.8167e-03,  1.5779e-02, -2.7614e-03, -2.5383e-03, -3.9343e-03],[ 6.0877e-03,  8.4987e-03,  1.3891e-02, -1.4258e-03, -8.7571e-03,-4.2930e-03, -9.5155e-04, -1.2515e-03, -2.7573e-03, -1.8363e-03,3.6556e-03,  1.8146e-03, -1.5488e-02,  4.5685e-04, -1.0984e-02,-3.8873e-03, -2.3433e-03, -8.7609e-03,  4.1699e-03,  9.4601e-03,3.1651e-04,  8.2427e-03,  2.3207e-03,  4.8457e-03, -1.5066e-02,6.2566e-03,  1.7090e-02,  9.2237e-03,  3.8094e-03, -3.4015e-03],[ 1.0200e-02,  1.2802e-02,  6.2122e-03, -1.1477e-02,  2.2691e-03,-4.6306e-04,  2.8861e-06,  9.0622e-03, -2.6586e-02, -7.3941e-04,6.5375e-07, -1.5064e-03,  2.4399e-02, -1.4029e-03, -4.1262e-03,1.2517e-02, -6.1972e-03, -8.5488e-03, -5.8397e-03,  1.9754e-03,4.5322e-03,  4.9351e-03, -8.4586e-03, -1.0668e-02, -4.0087e-04,7.3720e-03, -6.5349e-03, -1.7660e-03, -9.3602e-03,  1.5721e-03],[ 1.6188e-02, -2.0150e-03, -1.6816e-02, -1.6911e-02,  6.5990e-03,-1.6605e-02, -9.2304e-03, -8.1321e-03,  2.1806e-02, -7.1569e-03,-1.0543e-02, -6.5349e-03,  2.9192e-03, -1.5003e-02, -6.7353e-03,3.0836e-03, -1.0745e-04, -6.8194e-03,  1.0827e-02, -1.0363e-02,-1.2346e-02, -7.0676e-03,  1.2861e-02, -6.6271e-03, -5.7568e-03,3.4977e-03, -5.9773e-03,  3.5096e-03,  1.0743e-02,  8.9650e-03],[ 2.9357e-03,  7.0599e-03, -8.3739e-03, -3.4416e-03,  2.7688e-02,-1.0271e-02, -1.3291e-02, -9.5348e-03,  9.4741e-03,  5.1175e-03,9.3990e-03, -2.4245e-03, -7.4773e-03, -1.8540e-03, -1.7982e-02,-9.4906e-03,  1.2980e-02,  1.3263e-02,  7.2149e-04,  2.5788e-04,-2.8871e-04, -1.0207e-02,  4.8015e-03, -2.5008e-03, -1.0212e-02,-1.6521e-02, -1.0582e-02,  2.5365e-03,  2.0865e-03,  4.9698e-03],[ 4.8506e-03,  1.2074e-02, -1.1068e-02,  6.3328e-03, -7.2685e-03,8.6962e-03,  8.3850e-03,  3.9330e-04, -1.4435e-02,  2.6184e-03,-9.1552e-03, -9.1968e-03, -7.5484e-03,  1.7064e-02, -1.0926e-02,5.8421e-03,  3.2155e-03, -1.7801e-02, -7.1032e-03,  1.5225e-02,4.3300e-03, -1.1750e-02,  2.3955e-03,  5.8431e-03, -3.3767e-03,8.4297e-03,  5.9677e-03, -5.3130e-03, -6.2581e-03,  7.2684e-04],[ 1.0966e-03,  5.1526e-03,  1.2423e-02,  2.7335e-04, -2.2481e-03,-6.6638e-03,  1.0812e-02, -5.5681e-03, -3.6775e-03,  1.7190e-02,-8.9243e-03,  1.0826e-02,  2.1140e-02, -3.1026e-03, -7.8873e-03,1.1538e-02, -1.9044e-03,  1.0823e-02,  9.9094e-03,  2.5864e-03,-1.1288e-02,  7.8564e-03,  1.6430e-02, -5.0827e-03, -1.3557e-03,1.5250e-02, -7.7385e-03, -1.2449e-02,  1.0931e-02,  4.5603e-03],[ 1.0957e-02, -5.0123e-03, -9.2494e-03, -5.7311e-03,  1.0838e-02,3.2123e-03, -2.0542e-03, -7.1564e-03, -1.0734e-03,  1.9866e-02,1.6477e-02, -5.1313e-04,  3.8111e-03, -7.6825e-03, -6.2488e-03,5.7776e-03,  6.2000e-04, -1.7886e-02, -1.0113e-02,  1.1926e-03,-1.7908e-02, -9.1477e-03, -4.8008e-03, -4.7199e-03,  1.5774e-02,2.0051e-02, -1.7119e-02,  3.6467e-03, -2.3746e-03, -3.1700e-03],[-6.5938e-03, -8.9639e-03,  7.4318e-03, -7.2729e-03, -7.1252e-03,-2.4921e-03,  3.9307e-03,  3.5104e-03,  1.1045e-02, -5.6922e-03,4.3981e-03,  1.8079e-02, -4.0234e-03, -9.3731e-03,  2.8033e-03,1.2702e-02, -6.7108e-03,  1.1401e-03,  4.4380e-03,  3.1948e-02,-5.5021e-03,  1.4521e-03, -1.3206e-02, -2.4222e-03,  4.7926e-04,-1.1533e-02, -5.7481e-03,  1.2893e-02,  1.1545e-02,  5.2813e-03],[ 1.5414e-02, -6.9193e-03,  1.6852e-02, -1.0622e-02,  1.4744e-02,1.0154e-03,  1.3041e-02,  1.7373e-02, -3.9367e-03,  8.8151e-03,-1.1236e-02, -1.9134e-02, -2.9457e-04, -1.1307e-02,  5.1315e-04,1.5109e-02,  9.7158e-03, -2.8689e-03,  2.3455e-03,  1.0067e-02,-1.0586e-02, -8.3479e-03,  1.1931e-02,  8.1437e-04, -7.5972e-03,-1.2458e-03,  6.7771e-03,  1.0820e-02,  1.9163e-02,  1.5708e-02],[-9.7202e-03,  8.6719e-04,  2.0114e-02, -1.7551e-03,  1.0009e-02,2.3814e-06, -4.0599e-03, -1.6323e-03, -5.8922e-04, -1.9179e-02,-6.1471e-03,  3.2786e-03, -8.2910e-03,  1.5821e-02, -6.7673e-04,6.7152e-03, -9.1754e-03, -1.1328e-02, -2.6055e-03,  5.0403e-03,1.2042e-03, -3.8331e-03, -1.4951e-02, -1.3479e-02,  1.1225e-03,8.5821e-04, -6.5184e-03, -1.4773e-02, -5.9137e-03,  3.5191e-04],[ 1.8287e-02,  6.3982e-03,  9.5072e-05, -8.5228e-03,  3.8553e-03,-1.4717e-02, -2.2549e-02, -9.0621e-04, -1.2570e-02,  1.1718e-02,-6.6394e-03,  4.0225e-03,  1.1599e-02, -1.2683e-02, -1.6592e-02,6.4644e-03, -3.6911e-04, -1.5643e-02,  5.2307e-03, -6.2249e-03,-7.1715e-03, -2.3126e-03, -8.4576e-04,  3.8474e-03,  1.0998e-02,-4.6572e-03,  5.6035e-03,  3.4481e-02,  1.2175e-02,  5.7834e-03],[ 8.1615e-03,  1.1394e-02,  6.7657e-03,  6.2123e-03, -2.5495e-02,8.0885e-03, -1.4886e-02,  9.0453e-03,  7.6994e-04,  3.8311e-03,3.3331e-03, -1.1154e-03, -1.5299e-03, -1.0464e-04, -1.7200e-02,1.7913e-03,  6.0317e-03, -9.6406e-03, -3.2287e-03, -8.2056e-03,-3.6062e-03,  1.4878e-02,  2.8893e-04,  5.8158e-03,  2.6536e-03,-2.4103e-02, -1.4993e-02, -1.4791e-03, -5.8795e-06,  3.5734e-03],[-1.9504e-02, -5.2369e-03,  4.3967e-03, -8.9265e-03, -5.5365e-03,-3.4119e-03, -9.1115e-03,  1.0674e-02,  2.1772e-03,  1.2874e-02,4.4263e-03,  7.4545e-03, -2.3560e-03,  2.8753e-03, -1.1261e-02,2.3133e-02,  4.8261e-03,  8.4998e-03, -9.4744e-03,  2.2099e-02,-4.8882e-03, -5.5454e-03,  1.4507e-02, -6.0991e-03,  1.9609e-02,1.0477e-03, -1.3490e-02,  1.1814e-03, -8.1444e-03,  1.8736e-02],[ 2.4450e-02, -1.7491e-03, -5.5336e-03,  3.9693e-03, -9.6735e-04,3.7527e-03,  6.2744e-03, -2.6313e-03,  1.5444e-02, -4.2243e-03,-8.7079e-03,  2.0071e-02,  1.2334e-03, -8.3905e-03, -1.6589e-02,3.5387e-03, -3.9648e-03,  8.2130e-04,  1.4307e-02, -4.3372e-03,3.1793e-04, -7.4976e-03, -7.1900e-03,  1.2343e-03, -6.7502e-03,-1.1686e-02,  7.9501e-03, -2.0728e-02,  5.3000e-03,  2.5626e-02]])
2.linear.weight tensor([[-5.5996e-03, -1.7881e-02,  2.9029e-03, -3.8814e-04,  4.6640e-03,1.4729e-03, -8.7504e-04,  1.7051e-03, -9.9808e-03, -5.0457e-03,1.1433e-02,  2.6712e-03,  6.0539e-04, -1.9261e-02,  3.1117e-03,4.8112e-03, -7.1367e-03, -8.3227e-03, -8.6805e-03, -1.3699e-02],[ 9.2634e-03, -4.6123e-04,  8.3162e-05,  4.1494e-03,  5.1273e-03,-1.6681e-03,  1.4864e-02, -3.0277e-04,  1.7692e-03, -9.4125e-03,3.1612e-03, -1.3875e-02, -1.1496e-03,  1.5235e-02, -1.0851e-03,8.6537e-03,  9.0799e-03, -2.8304e-03,  7.5469e-03, -7.0789e-03],[-5.3225e-03, -8.5825e-03,  5.8378e-03,  1.1406e-03, -3.2881e-03,7.9792e-03,  1.5086e-02, -8.4687e-03, -1.3789e-02, -1.8288e-02,1.3957e-03,  2.2536e-03, -3.3606e-03,  3.2420e-03, -9.3056e-03,1.5156e-02,  6.4650e-03, -1.3013e-03,  1.0178e-02,  1.3913e-02],[-1.2846e-02,  4.8990e-04,  7.1575e-03,  1.3793e-03, -5.9738e-03,3.9912e-03,  2.5881e-03, -1.5927e-02, -9.1614e-03, -1.6528e-02,1.1311e-02, -4.5142e-03,  4.0138e-03, -2.2480e-02, -3.1659e-03,-1.8865e-02,  1.4666e-02,  1.0195e-02, -9.0439e-03,  3.8127e-03],[ 1.2961e-02,  7.7461e-03,  1.1123e-02,  8.3137e-03, -1.2393e-02,-3.1891e-03,  4.7997e-03,  1.3994e-02,  6.5888e-03,  1.6503e-02,-8.6732e-05,  1.0505e-02, -5.6654e-03, -5.1383e-03, -6.2080e-03,1.7060e-03,  1.0218e-02, -5.8861e-03,  1.1582e-02,  2.7832e-03],[ 7.2542e-03,  2.7732e-03,  6.6612e-03,  3.4965e-03, -4.0417e-03,-7.7164e-03, -1.9723e-02, -1.8491e-03,  9.4730e-03, -1.7118e-04,1.1873e-02, -7.9715e-03,  1.0753e-03,  1.0804e-02,  1.3700e-02,1.6791e-02, -1.4478e-02,  1.7035e-02,  9.3034e-04,  6.3716e-03],[-5.1573e-03, -1.3071e-03,  1.5302e-02, -6.1851e-03,  6.7677e-04,1.4603e-02,  7.0722e-03,  2.6819e-03,  1.5753e-02, -3.4153e-03,-2.0578e-03, -8.0549e-03, -1.2534e-02,  7.2134e-03, -1.6519e-02,7.4687e-04,  4.4496e-03, -2.0857e-03, -1.4627e-02,  7.0603e-03],[-3.0296e-04,  1.3288e-03, -7.3660e-03, -9.3445e-04,  7.9644e-03,4.3456e-03, -1.3778e-02,  4.5655e-03, -1.2824e-02, -1.1208e-02,1.8958e-02,  2.4357e-03, -2.1795e-02,  5.2504e-03,  8.8114e-04,2.6217e-03, -5.6610e-03,  3.5770e-04,  9.2574e-03,  7.0462e-04],[ 5.5887e-03, -2.3937e-02,  1.3323e-02,  1.2788e-02, -1.2492e-02,-8.2638e-03,  3.7073e-04, -6.0787e-03,  4.5608e-03, -2.0334e-02,-1.5575e-02, -7.6481e-03,  1.2293e-02, -4.0633e-03, -4.2219e-03,-8.4397e-03, -7.8156e-03,  1.4628e-02,  8.0971e-04,  4.0196e-04],[-1.3949e-02,  3.2856e-03,  3.0923e-03, -1.2260e-04, -1.1090e-02,-1.0921e-02,  1.2069e-02, -1.4299e-02,  6.6826e-03, -5.0484e-03,-1.6159e-02,  5.4746e-03,  4.6988e-03, -2.0970e-02, -1.2481e-03,-9.0344e-03, -1.4410e-02, -3.9734e-03,  4.2471e-03,  1.3298e-02],[-2.9720e-03,  1.4633e-02,  3.5870e-03,  2.0081e-03, -8.4944e-04,-1.0992e-02,  1.3077e-02, -1.0255e-03,  4.1050e-05, -9.8274e-03,-4.1936e-04,  1.1226e-02, -1.2842e-02,  1.6335e-02, -8.9160e-03,4.1783e-03,  3.9959e-03, -4.7716e-03, -3.1262e-03, -1.0138e-02],[ 2.0540e-02, -2.0969e-03, -3.8366e-04, -2.7185e-03, -3.2523e-03,7.9718e-03,  8.1142e-03,  3.6300e-03, -7.4875e-03,  1.3166e-02,1.3331e-03,  1.0332e-02,  1.1699e-02,  1.0125e-02,  1.0621e-02,-1.6513e-02, -3.5310e-03, -1.9825e-02, -8.0858e-03, -3.1577e-03],[ 9.9199e-03, -1.4978e-03, -2.9754e-03, -1.2934e-02, -1.4795e-02,-1.6737e-02, -6.4125e-03, -1.3493e-03, -6.9752e-03,  1.2560e-02,-4.3187e-03, -1.4194e-02,  3.6981e-04, -2.8193e-03,  8.1851e-03,-1.1203e-02,  1.9439e-02,  1.0795e-02, -8.2543e-03,  2.3599e-03],[-1.1758e-02,  9.5521e-03,  6.3462e-04,  3.5751e-03,  1.3527e-02,9.1637e-03, -4.8209e-03, -1.0592e-02,  2.0195e-03,  1.6119e-02,1.1654e-02, -1.0050e-02, -7.9837e-03,  1.9223e-02,  2.3013e-03,1.4753e-03,  6.0071e-03,  4.8298e-04,  6.6951e-03, -1.2826e-02],[-2.0467e-02, -4.2140e-03,  6.8931e-03, -5.0351e-03, -1.0566e-02,-6.9593e-03,  4.7499e-03,  8.2981e-03,  2.5675e-02,  1.5285e-02,-9.5692e-03, -4.5086e-03, -5.6572e-03, -1.1610e-03, -1.7814e-03,1.2086e-02,  9.0804e-03, -9.1113e-03, -1.9917e-02, -1.6530e-02],[-8.3130e-03,  1.3344e-02, -1.0923e-02, -2.2851e-02,  6.8411e-03,2.1356e-03,  8.5286e-03, -5.2713e-03, -1.2193e-02, -1.1948e-03,3.3531e-04, -4.8021e-03,  5.7277e-03,  1.1665e-02, -1.0539e-04,7.7064e-03,  1.4751e-02, -4.4743e-03,  1.4951e-02,  1.2392e-02],[-1.3800e-02,  1.3546e-02, -6.8238e-03,  1.4270e-02, -1.2051e-02,5.9353e-03,  2.4619e-03,  1.5746e-03,  7.2940e-03, -9.0082e-04,-5.7518e-03, -2.0381e-02, -7.1935e-03,  2.1555e-03, -5.1282e-03,-1.9255e-02, -7.8506e-03, -1.4166e-02,  3.6891e-03, -6.8586e-03],[-1.3660e-02,  2.2254e-02,  1.7642e-02, -3.0450e-03,  1.3232e-02,-1.0315e-02,  1.0142e-02,  3.5027e-04, -5.0814e-04, -2.6084e-03,2.5116e-02,  5.9374e-03,  5.4630e-03,  1.1566e-02, -8.3270e-03,-7.3726e-03,  1.1869e-02, -1.8963e-02,  5.7513e-03, -8.7186e-03],[-2.0966e-03, -1.7567e-03,  1.4226e-03, -6.6999e-03,  4.1837e-03,-7.0836e-04,  5.6019e-03, -6.0745e-03,  7.3432e-03,  6.0721e-03,5.1656e-03, -1.8158e-03, -8.8598e-03,  2.4378e-02,  4.7904e-03,7.9625e-03,  5.9612e-03, -2.0552e-03, -4.8240e-03, -1.4750e-02],[ 7.3819e-03, -6.9134e-03,  8.1345e-03, -1.4451e-02,  7.6821e-03,-1.5124e-03,  3.8898e-03,  1.2265e-03, -9.0760e-03, -1.5998e-02,2.7463e-04, -6.5673e-03, -7.7155e-04, -2.0952e-02, -2.3035e-03,-1.2220e-03,  1.2617e-02,  5.1720e-03, -1.7524e-02,  5.6977e-03]])
for name, param in net.named_parameters():if 'bias' in name:init.constant_(param, val=0)print(name, param.data)
0.net.0.bias tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,0., 0., 0., 0., 0., 0.])
1.bias tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
2.linear.bias tensor([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

自定义初始化方法

有时候我们需要的初始化方法并没有在init模块中提供。这时,可以实现一个初始化方法,从而能够像使用其他初始化方法那样使用它。在这之前我们先来看看PyTorch是怎么实现这些初始化方法的,例如torch.nn.init.normal_:

def normal_(tensor, mean=0, std=1):with torch.no_grad():return tensor.normal_(mean, std)

可以看到这就是一个inplace改变Tensor值的函数,而且这个过程是不记录梯度的。 类似的我们来实现一个自定义的初始化方法。在下面的例子里,我们令权重有一半概率初始化为0,有另一半概率初始化为[−10,−5][−10,−5]和[5,10][5,10]两个区间里均匀分布的随机数。

def init_weight_(tensor):with torch.no_grad():tensor.uniform_(-10, 10)tensor *= (tensor.abs() >= 5).float()for name, param in net.named_parameters():if 'weight' in name:init_weight_(param)print(name, param.data)
0.net.0.weight tensor([[-0.0000, -6.2573, -9.6670,  ..., -6.2055, -0.0000,  0.0000],[ 0.0000, -6.1450, -0.0000,  ...,  9.4352,  8.5185,  0.0000],[ 0.0000,  0.0000, -0.0000,  ...,  0.0000, -0.0000, -5.4052],...,[-0.0000, -9.5803, -5.8481,  ..., -0.0000, -0.0000, -0.0000],[-9.8709,  0.0000, -0.0000,  ...,  0.0000,  7.7648, -7.7570],[-8.7503, -9.4466,  8.8122,  ...,  5.5594, -0.0000,  9.3528]])
1.weight tensor([[-5.3031, -7.1580, -9.9964, -6.4769,  0.0000, -5.8270,  5.7411, -5.8713,-0.0000, -0.0000, -0.0000,  5.3456,  0.0000,  0.0000, -0.0000,  6.5026,0.0000, -0.0000,  0.0000,  0.0000, -6.3099,  0.0000, -0.0000,  0.0000,-7.5503, -0.0000,  9.9910, -0.0000, -0.0000,  6.3966],[ 5.5881,  0.0000, -0.0000, -8.1178,  9.6688, -0.0000,  0.0000,  8.6963,0.0000,  8.0869,  0.0000,  6.0899,  8.3442, -6.8183, -8.3160, -0.0000,-0.0000, -7.4499, -6.6586, -0.0000,  0.0000, -6.7071, -0.0000,  7.4049,0.0000, -9.0628, -0.0000,  7.3452,  0.0000, -8.3752],[-6.3758,  0.0000,  0.0000,  9.1926,  7.5408,  0.0000, -9.9305,  0.0000,-0.0000, -9.0137,  0.0000,  8.7384, -0.0000, -6.3803, -0.0000,  0.0000,-8.8573,  8.8939,  0.0000,  6.2515,  5.3137,  7.6621, -0.0000, -8.0161,-8.4190,  6.1407, -0.0000, -6.5521,  5.4117, -0.0000],[ 0.0000, -9.7822,  0.0000, -0.0000,  0.0000, -9.9513,  0.0000, -0.0000,9.5243,  6.7586, -6.7599, -7.2046,  5.7396,  0.0000, -7.4426,  6.5923,5.4310,  0.0000,  9.5645, -0.0000,  9.5840, -7.3611, -0.0000,  5.2647,-5.9115, -0.0000, -0.0000, -0.0000, -5.2489, -8.3718],[ 5.0601,  8.8166,  0.0000,  6.9072, -8.9312,  0.0000,  7.9705, -9.0079,6.0310, -9.9306,  0.0000,  5.2559,  0.0000, -0.0000,  0.0000,  6.6453,-8.2131, -0.0000, -9.7696, -0.0000, -6.1296, -6.1960,  0.0000, -7.1193,6.0872,  8.9191, -7.5285,  8.8542,  0.0000, -0.0000],[ 5.7640, -8.2749,  0.0000, -0.0000, -0.0000,  8.4516, -0.0000,  8.1646,-7.5594, -0.0000, -7.6956,  0.0000,  0.0000,  8.4151,  0.0000, -0.0000,-9.5694, -6.6565,  5.6100, -7.5257, -0.0000,  7.6025,  6.7463, -9.1704,-0.0000,  0.0000,  8.9362,  7.7404, -9.6161,  0.0000],[-5.9001,  0.0000, -0.0000, -7.5054,  0.0000, -7.8240,  7.8767,  7.6504,9.0638,  7.9266,  7.0275, -0.0000, -6.6694,  5.2457,  9.6615,  0.0000,5.6970, -7.9317, -0.0000,  0.0000,  6.3138, -0.0000, -0.0000,  6.8197,-0.0000, -5.5665,  5.6393,  6.9409,  8.4405, -6.9706],[ 0.0000, -6.5044, -5.4181,  0.0000, -8.2382,  6.3029, -0.0000, -0.0000,0.0000, -0.0000, -8.7580,  6.9954,  8.0429, -9.6811,  0.0000,  7.1997,9.6289, -6.6778,  8.3476,  0.0000,  0.0000, -5.1837, -7.5868,  8.8954,0.0000,  9.4241, -5.2790,  9.6536, -6.5575, -7.8887],[ 8.6683, -9.6715,  0.0000,  5.7765,  6.6276,  8.2964, -0.0000, -6.1496,8.9688, -0.0000, -0.0000,  8.1510, -0.0000,  6.2618,  0.0000, -7.1139,-9.1306,  8.7948, -8.2000,  0.0000, -7.7904, -0.0000,  8.5050, -7.8431,-0.0000, -0.0000,  7.9535, -6.2632, -6.1001, -6.1616],[-8.8006, -8.2721, -6.8235,  0.0000, -9.7454,  0.0000, -0.0000,  0.0000,6.3692,  9.8793,  0.0000,  0.0000, -7.2012,  0.0000,  0.0000,  0.0000,-0.0000,  0.0000,  8.0920, -0.0000, -9.2214, -0.0000, -8.5031, -8.3191,-0.0000,  7.7950, -0.0000,  0.0000,  0.0000, -7.7035],[ 7.3713,  6.2752,  0.0000,  0.0000,  0.0000,  0.0000,  0.0000,  9.8827,-9.9048, -0.0000,  0.0000,  8.6781,  7.9049, -0.0000, -0.0000, -0.0000,0.0000, -0.0000,  0.0000,  5.6662, -5.7249,  7.5572,  7.9236, -8.0282,0.0000, -0.0000, -8.1768,  0.0000, -0.0000, -0.0000],[-9.1349,  8.1316,  0.0000, -0.0000,  0.0000, -0.0000,  0.0000, -0.0000,6.6178, -0.0000, -0.0000,  0.0000,  7.0107,  8.4189, -0.0000,  5.0933,9.8502, -0.0000, -9.1036,  0.0000, -5.6974,  0.0000, -9.8530, -8.0555,0.0000, -5.2797, -7.7184, -0.0000, -5.4591,  8.9083],[-0.0000,  7.5084,  0.0000, -7.2532,  0.0000, -0.0000,  0.0000,  8.1774,-9.4518, -5.2770, -0.0000, -0.0000,  5.0882,  7.4918, -8.7120, -0.0000,-7.0417,  0.0000, -0.0000,  5.1748,  0.0000, -0.0000, -0.0000, -9.3591,0.0000, -8.2938, -8.9266, -0.0000,  0.0000,  0.0000],[ 9.5399,  0.0000,  7.4996, -0.0000,  9.8394,  0.0000,  0.0000, -0.0000,0.0000, -0.0000,  0.0000,  0.0000, -5.3790, -9.6425,  9.8764,  0.0000,7.0963, -8.9114, -0.0000,  9.0510,  5.4095, -5.0019,  0.0000, -7.0848,-0.0000,  0.0000,  0.0000, -0.0000,  0.0000, -9.8849],[ 8.1293,  0.0000, -6.7563,  0.0000,  7.6843,  8.4486,  6.6997,  7.9062,-5.6233,  0.0000,  6.2966,  7.4003,  0.0000, -0.0000,  8.2519,  0.0000,8.9715, -8.4958, -7.0926, -0.0000, -0.0000, -5.9202,  6.4348,  8.4848,0.0000, -7.7669, -7.1864,  0.0000,  9.1471, -0.0000],[ 0.0000,  8.9136, -6.4488,  0.0000, -0.0000,  0.0000, -0.0000,  0.0000,9.3667,  7.9826,  0.0000,  0.0000, -6.9993,  0.0000,  9.6924,  0.0000,8.0840,  9.4185,  0.0000,  6.2945,  7.2634, -0.0000, -6.5016, -0.0000,0.0000, -0.0000,  6.4698, -0.0000,  5.2106, -0.0000],[-0.0000,  6.1383, -9.1950, -5.4267, -0.0000, -8.8607,  9.7967,  0.0000,0.0000,  0.0000,  5.7624, -9.8647,  7.0602, -9.4853, -0.0000,  9.4742,-5.6148, -6.2168,  0.0000,  9.9788, -9.1114,  0.0000,  0.0000, -0.0000,6.7838,  0.0000,  0.0000, -0.0000,  6.0502, -5.0156],[ 8.1110, -0.0000,  6.7124, -6.7490,  5.9337, -8.4773, -0.0000, -7.2125,0.0000, -0.0000,  5.2543,  0.0000,  0.0000,  9.5925,  0.0000, -0.0000,-0.0000, -0.0000, -8.4826,  0.0000, -0.0000, -6.4074,  0.0000, -0.0000,7.2494, -8.8358,  7.8122,  8.8839,  7.9619,  7.8244],[ 0.0000, -6.1305,  0.0000,  6.7742,  5.9301, -0.0000,  0.0000, -9.8249,7.4770,  0.0000,  6.4683, -0.0000,  0.0000, -0.0000, -7.5854, -0.0000,-9.8200, -8.4659, -0.0000, -0.0000,  0.0000,  8.8622,  8.4771,  5.8597,0.0000,  0.0000,  6.5139,  0.0000, -6.5754, -0.0000],[-0.0000,  8.0858, -0.0000,  0.0000, -0.0000,  9.6130, -0.0000, -5.2527,-9.6432, -5.0170,  5.0056,  7.9539,  0.0000, -0.0000, -8.1660, -0.0000,0.0000, -0.0000,  0.0000, -7.4998,  0.0000, -0.0000, -0.0000,  9.5478,8.9482, -0.0000,  0.0000, -6.8827,  8.9620, -9.7837]])
2.linear.weight tensor([[ 0.0000, -6.9812,  6.5521, -0.0000, -9.5926, -0.0000, -0.0000, -5.0386,6.5204,  0.0000,  8.5534,  9.0793,  0.0000, -0.0000, -0.0000, -5.9300,-5.9106, -0.0000,  8.0045,  7.3943],[-5.1885, -0.0000, -0.0000,  5.7570,  0.0000, -0.0000, -8.7268,  9.2548,0.0000, -7.7151, -6.8379, -8.5315, -0.0000,  0.0000,  6.4908,  0.0000,-0.0000, -0.0000, -5.9161, -5.8564],[ 0.0000, -9.4816, -9.4379, -0.0000, -9.3362, -0.0000,  0.0000, -8.2363,-0.0000,  8.0405,  8.9864,  0.0000, -9.2516, -6.2904,  5.7813,  5.3719,-0.0000, -8.8506,  0.0000, -9.7931],[ 9.4502, -9.2087,  7.3578, -0.0000, -0.0000, -5.6518,  6.7095,  0.0000,-0.0000, -0.0000,  5.9396,  7.8704,  0.0000, -0.0000, -7.2353,  0.0000,-0.0000,  7.0156,  0.0000, -5.0929],[ 0.0000, -9.9551, -0.0000,  6.6445,  7.0596, -0.0000, -0.0000, -7.0890,-0.0000, -0.0000,  0.0000,  8.3706,  0.0000, -7.1886,  0.0000, -8.4613,-0.0000, -7.1553,  0.0000, -5.9845],[-0.0000,  7.2888, -0.0000, -0.0000,  0.0000, -9.2040,  5.5700, -7.6277,0.0000, -0.0000, -0.0000, -0.0000, -0.0000, -8.3413,  5.5270,  0.0000,7.4749, -0.0000, -7.7825, -6.2418],[ 0.0000, -0.0000, -9.5633,  0.0000,  7.8421,  0.0000, -0.0000, -0.0000,0.0000,  7.5993,  7.9292,  7.3422,  9.5524, -5.4055, -0.0000,  7.3166,-0.0000,  0.0000,  9.8042,  6.4248],[ 0.0000, -0.0000,  9.5345,  9.1690, -0.0000, -0.0000,  5.9536, -6.3916,0.0000,  8.0737, -0.0000,  9.2005, -0.0000,  0.0000, -0.0000,  0.0000,0.0000,  0.0000, -0.0000,  5.8255],[-0.0000, -0.0000,  0.0000,  0.0000, -8.6615,  0.0000, -6.7372, -8.7178,-7.8605,  8.0300, -9.7292, -0.0000, -6.1143,  9.4508,  0.0000, -0.0000,0.0000,  8.0177, -7.3347,  0.0000],[ 6.3698,  0.0000, -0.0000, -0.0000, -7.8566, -0.0000,  0.0000, -0.0000,9.4590, -8.1037,  0.0000, -6.8476, -5.9440, -0.0000,  0.0000, -7.6990,0.0000, -8.9955, -0.0000, -0.0000],[-0.0000,  7.5792,  0.0000, -0.0000,  0.0000, -9.8703,  9.7579, -8.2181,-0.0000, -6.6664,  9.2518, -0.0000,  0.0000,  6.6096, -9.9753,  0.0000,7.4476, -8.6817, -7.4076, -6.4940],[-8.1521,  9.0149,  6.9163, -0.0000,  0.0000, -0.0000,  7.4414, -0.0000,-5.4136,  0.0000,  0.0000,  0.0000,  5.6016,  8.2639,  0.0000, -0.0000,8.3907,  5.6836, -7.3025,  6.4559],[-0.0000, -0.0000, -6.3013,  0.0000,  0.0000,  0.0000,  7.3791, -0.0000,9.9710,  0.0000, -6.0639,  0.0000, -5.8077,  5.1654,  0.0000,  7.9023,-0.0000, -0.0000, -0.0000, -8.7207],[ 5.5755,  0.0000, -6.9844,  7.6312, -0.0000,  0.0000,  8.0948,  0.0000,0.0000,  0.0000, -0.0000,  0.0000, -0.0000, -0.0000, -0.0000, -7.1881,-9.8673, -0.0000,  6.4959,  5.2270],[ 0.0000,  0.0000, -9.7369, -8.0855,  0.0000,  7.7631,  0.0000, -6.6331,-0.0000,  0.0000, -0.0000, -8.9024, -0.0000,  7.6198, -0.0000,  5.1892,0.0000,  8.1393,  0.0000,  9.0153],[-0.0000, -7.5369,  7.0477, -0.0000,  0.0000,  0.0000,  0.0000, -0.0000,-6.6719, -9.6702, -0.0000,  6.2202,  5.0695, -0.0000,  0.0000, -5.9180,-0.0000,  0.0000,  9.3806,  5.2014],[-0.0000,  5.1159, -7.1775, -0.0000, -5.8047,  7.2177, -7.7319, -0.0000,-0.0000, -9.0223, -0.0000,  0.0000,  0.0000, -0.0000,  8.1462, -8.1729,6.9001, -0.0000, -0.0000,  8.9680],[-0.0000,  0.0000, -0.0000,  0.0000, -0.0000, -0.0000, -0.0000, -0.0000,8.0092, -8.0028,  0.0000, -0.0000,  7.1211, -0.0000,  0.0000,  0.0000,9.3772, -0.0000,  0.0000, -0.0000],[ 0.0000,  5.9549,  5.3347, -0.0000,  0.0000,  6.8372, -0.0000,  7.0890,6.8374,  6.8444,  5.3985,  5.1464, -0.0000, -0.0000,  8.7471,  6.0348,-0.0000,  0.0000,  6.7883,  8.7566],[ 7.5425,  0.0000, -0.0000, -6.2917,  9.6904, -6.8175, -9.9985,  0.0000,5.8819,  8.6874,  0.0000,  6.9018,  0.0000, -7.0253, -0.0000,  0.0000,7.5909,  0.0000,  0.0000, -0.0000]])

参考2.3.2节,我们还可以通过改变这些参数的data来改写模型参数值同时不会影响梯度:

for name, param in net.named_parameters():if 'bias' in name:param.data += 1print(name, param.data)
0.net.0.bias tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
1.bias tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,1., 1.])
2.linear.bias tensor([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,1., 1.])

共享模型参数

在有些情况下,我们希望在多个层之间共享模型参数。4.1.3节提到了如何共享模型参数: Module类的forward函数里多次调用同一个层。此外,如果我们传入Sequential的模块是同一个Module实例的话参数也是共享的,下面来看一个例子:

linear = nn.Linear(1, 1, bias=False)
net = nn.Sequential(linear, linear) 
print(net)
for name, param in net.named_parameters():init.constant_(param, val=3)print(name, param.data)
Sequential((0): Linear(in_features=1, out_features=1, bias=False)(1): Linear(in_features=1, out_features=1, bias=False)
)
0.weight tensor([[3.]])

在内存中,这两个线性层其实一个对象:

print(id(net[0]) == id(net[1]))
print(id(net[0].weight) == id(net[1].weight))
True
True

因为模型参数里包含了梯度,所以在反向传播计算时,这些共享的参数的梯度是累加的:

x = torch.ones(1, 1)
y = net(x).sum()
print(y)
y.backward()
print(net[0].weight.grad) # 单次梯度是3,两次所以就是6
tensor(9., grad_fn=<SumBackward0>)
tensor([[6.]])

自定义层

不含模型参数的自定义层

我们先介绍如何定义一个不含模型参数的自定义层。事实上,这和4.1节(模型构造)中介绍的使用Module类构造模型类似。下面的CenteredLayer类通过继承Module类自定义了一个将输入减掉均值后输出的层,并将层的计算定义在了forward函数里。这个层里不含模型参数。

import torch 
from torch import nn
class CenteredLayer(nn.Module):def __init__(self,**kwargs):super(CenteredLayer,self).__init__(**kwargs)def forward(self,x):return x-x.mean()
layer = CenteredLayer()
layer(torch.tensor([1,2,3,4,5],dtype = torch.float))
tensor([-2., -1.,  0.,  1.,  2.])
net = nn.Sequential(nn.Linear(8,128,CenteredLayer()))
y = net(torch.rand(4,8))
y.mean().item()
0.005987975746393204

含模型参数的自定义层

在4.2节(模型参数的访问、初始化和共享)中介绍了Parameter类其实是Tensor的子类,如果一个Tensor是Parameter,那么它会自动被添加到模型的参数列表里。所以在自定义含模型参数的层时,我们应该将参数定义成Parameter,除了像4.2.1节那样直接定义成Parameter类外,还可以使用ParameterList和ParameterDict分别定义参数的列表和字典。

ParameterList接收一个Parameter实例的列表作为输入然后得到一个参数列表,使用的时候可以用索引来访问某个参数,另外也可以使用append和extend在列表后面新增参数。

class MyDense(nn.Module):def __init__(self):super(MyDense,self).__init__()self.params = nn.ParameterList([nn.Parameter(torch.randn(4,4)) for i in range(3)])self.params.append(nn.Parameter(torch.randn(4,1)))def forward(self,x):for i in range(len(self.params)):x = torch.mm(x,self.params[i])return x
net = MyDense()
print(net)
MyDense((params): ParameterList((0): Parameter containing: [torch.FloatTensor of size 4x4](1): Parameter containing: [torch.FloatTensor of size 4x4](2): Parameter containing: [torch.FloatTensor of size 4x4](3): Parameter containing: [torch.FloatTensor of size 4x1])
)

而ParameterDict接收一个Parameter实例的字典作为输入然后得到一个参数字典,然后可以按照字典的规则使用了。例如使用update()新增参数,使用keys()返回所有键值,使用items()返回所有键值对等等,可参考官方文档。

class MyDictDense(nn.Module):def __init__(self):super(MyDictDense, self).__init__()self.params = nn.ParameterDict({'linear1': nn.Parameter(torch.randn(4, 4)),'linear2': nn.Parameter(torch.randn(4, 1))})self.params.update({'linear3': nn.Parameter(torch.randn(4, 2))}) # 新增def forward(self, x, choice='linear1'):return torch.mm(x, self.params[choice])net = MyDictDense()
print(net)
MyDictDense((params): ParameterDict((linear1): Parameter containing: [torch.FloatTensor of size 4x4](linear2): Parameter containing: [torch.FloatTensor of size 4x1](linear3): Parameter containing: [torch.FloatTensor of size 4x2])
)

这样就可以根据传入的键值来进行不同的前向传播:

x = torch.ones(1, 4)
print(net(x, 'linear1'))
print(net(x, 'linear2'))
print(net(x, 'linear3'))
tensor([[ 5.4923,  0.4334, -1.8005, -0.0718]], grad_fn=<MmBackward>)
tensor([[2.9095]], grad_fn=<MmBackward>)
tensor([[ 1.0343, -3.6477]], grad_fn=<MmBackward>)

我们也可以使用自定义层构造模型。它和PyTorch的其他层在使用上很类似。

net = nn.Sequential(MyDictDense(),MyDense(),
)
print(net)
print(net(x))
Sequential((0): MyDictDense((params): ParameterDict((linear1): Parameter containing: [torch.FloatTensor of size 4x4](linear2): Parameter containing: [torch.FloatTensor of size 4x1](linear3): Parameter containing: [torch.FloatTensor of size 4x2]))(1): MyDense((params): ParameterList((0): Parameter containing: [torch.FloatTensor of size 4x4](1): Parameter containing: [torch.FloatTensor of size 4x4](2): Parameter containing: [torch.FloatTensor of size 4x4](3): Parameter containing: [torch.FloatTensor of size 4x1]))
)
tensor([[-8.2394]], grad_fn=<MmBackward>)

读取与存储

读写Tensor

我们可以直接使用save函数和load函数分别存储和读取Tensor。save使用Python的pickle实用程序将对象进行序列化,然后将序列化的对象保存到disk,使用save可以保存各种对象,包括模型、张量和字典等。而load使用pickle unpickle工具将pickle的对象文件反序列化为内存。

下面的例子创建了Tensor变量x,并将其存在文件名同为x.pt的文件里。

import torch
from torch import nn
x= torch.ones(3)
print(x)
torch.save(x,'x.pt')
tensor([1., 1., 1.])
x2=torch.load('x.pt')
x2
tensor([1., 1., 1.])

还可以存储一个Tensor列表并读回内存。

y = torch.zeros(4)
torch.save([x,y],'xy.pt')
xy_list = torch.load('xy.pt')
xy_list
[tensor([1., 1., 1.]), tensor([0., 0., 0., 0.])]

存储并读取一个从字符串映射到Tensor的字典。

torch.save({'x': x, 'y': y}, 'xy_dict.pt')
xy = torch.load('xy_dict.pt')
xy
{'x': tensor([1., 1., 1.]), 'y': tensor([0., 0., 0., 0.])}

读写模型

在PyTorch中,Module的可学习参数(即权重和偏差),模块模型包含在参数中(通过model.parameters()访问)。state_dict是一个从参数名称隐射到参数Tesnor的字典对象。

class MLP(nn.Module):def __init__(self):super(MLP, self).__init__()self.hidden = nn.Linear(3, 2)self.act = nn.ReLU()self.output = nn.Linear(2, 1)def forward(self, x):a = self.act(self.hidden(x))return self.output(a)net = MLP()
net.state_dict()
OrderedDict([('hidden.weight', tensor([[ 0.3508, -0.0527,  0.5097],[ 0.1291,  0.4404,  0.2258]])),('hidden.bias', tensor([0.0332, 0.4611])),('output.weight', tensor([[0.1315, 0.0635]])),('output.bias', tensor([-0.4548]))])
optimizer = torch.optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
optimizer.state_dict()
{'param_groups': [{'dampening': 0,'lr': 0.001,'momentum': 0.9,'nesterov': False,'params': [2501567222120, 2501567222480, 2501566216088, 2501565231320],'weight_decay': 0}],'state': {}}

仅保存和加载模型参数(state_dict)

torch.save(model.state_dict(),PATH)  # 推荐的文件后缀名是pt或pth#加载
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH))
---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-55-60ddd59ce579> in <module>()
----> 1 torch.save(model.state_dict(),PATH)  # 推荐的文件后缀名是pt或pth2 3 #加载4 model = TheModelClass(*args, **kwargs)5 model.load_state_dict(torch.load(PATH))NameError: name 'model' is not defined

保存和加载整个模型

torch.save(model, PATH)#加载model = torch.load(PATH)
X = torch.randn(2, 3)
Y = net(X)PATH = "./net.pt"
torch.save(net.state_dict(), PATH)net2 = MLP()
net2.load_state_dict(torch.load(PATH))
Y2 = net2(X)
Y2 == Y
tensor([[True],[True]])

模型的GPU计算

用torch.cuda.is_available()查看GPU是否可用

torch.cuda.is_available() 
False

查看GPU数量:

torch.cuda.device_count()
0

查看当前GPU索引号,索引号从0开始:

torch.cuda.current_device() # 输出 0
---------------------------------------------------------------------------AssertionError                            Traceback (most recent call last)<ipython-input-59-55c583da45aa> in <module>()
----> 1 torch.cuda.get_device_name(0)D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in get_device_name(device)291             if :attr:`device` is ``None`` (default).292     """
--> 293     return get_device_properties(device).name294 295 D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in get_device_properties(device)313 def get_device_properties(device):314     if not _initialized:
--> 315         init()  # will define _get_device_properties and _CudaDeviceProperties316     device = _get_device_index(device, optional=True)317     if device < 0 or device >= device_count():D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in init()159     Does nothing if the CUDA state is already initialized.160     """
--> 161     _lazy_init()162 163 D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in _lazy_init()176         raise RuntimeError(177             "Cannot re-initialize CUDA in forked subprocess. " + msg)
--> 178     _check_driver()179     torch._C._cuda_init()180     _cudart = _load_cudart()D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in _check_driver()90 def _check_driver():91     if not hasattr(torch._C, '_cuda_isDriverSufficient'):
---> 92         raise AssertionError("Torch not compiled with CUDA enabled")93     if not torch._C._cuda_isDriverSufficient():94         if torch._C._cuda_getDriverVersion() == 0:AssertionError: Torch not compiled with CUDA enabled

根据索引号查看GPU名字:

torch.cuda.get_device_name(0) # 输出 'GeForce GTX 1050'
---------------------------------------------------------------------------AssertionError                            Traceback (most recent call last)<ipython-input-60-45381b0646d2> in <module>()
----> 1 torch.cuda.get_device_name(0) # 输出 'GeForce GTX 1050'D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in get_device_name(device)291             if :attr:`device` is ``None`` (default).292     """
--> 293     return get_device_properties(device).name294 295 D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in get_device_properties(device)313 def get_device_properties(device):314     if not _initialized:
--> 315         init()  # will define _get_device_properties and _CudaDeviceProperties316     device = _get_device_index(device, optional=True)317     if device < 0 or device >= device_count():D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in init()159     Does nothing if the CUDA state is already initialized.160     """
--> 161     _lazy_init()162 163 D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in _lazy_init()176         raise RuntimeError(177             "Cannot re-initialize CUDA in forked subprocess. " + msg)
--> 178     _check_driver()179     torch._C._cuda_init()180     _cudart = _load_cudart()D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in _check_driver()90 def _check_driver():91     if not hasattr(torch._C, '_cuda_isDriverSufficient'):
---> 92         raise AssertionError("Torch not compiled with CUDA enabled")93     if not torch._C._cuda_isDriverSufficient():94         if torch._C._cuda_getDriverVersion() == 0:AssertionError: Torch not compiled with CUDA enabled

同Tensor类似,PyTorch模型也可以通过.cuda转换到GPU上。我们可以通过检查模型的参数的device属性来查看存放模型的设备。

net = nn.Linear(3, 1)
list(net.parameters())[0].device
device(type='cpu')

可见模型在CPU上,将其转换到GPU上:

net.cuda()
list(net.parameters())[0].device
---------------------------------------------------------------------------AssertionError                            Traceback (most recent call last)<ipython-input-62-a9404ab4efc6> in <module>()
----> 1 net.cuda()2 list(net.parameters())[0].deviceD:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\nn\modules\module.py in cuda(self, device)309             Module: self310         """
--> 311         return self._apply(lambda t: t.cuda(device))312 313     def cpu(self):D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\nn\modules\module.py in _apply(self, fn)228                 # `with torch.no_grad():`229                 with torch.no_grad():
--> 230                     param_applied = fn(param)231                 should_use_set_data = compute_should_use_set_data(param, param_applied)232                 if should_use_set_data:D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\nn\modules\module.py in <lambda>(t)309             Module: self310         """
--> 311         return self._apply(lambda t: t.cuda(device))312 313     def cpu(self):D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in _lazy_init()176         raise RuntimeError(177             "Cannot re-initialize CUDA in forked subprocess. " + msg)
--> 178     _check_driver()179     torch._C._cuda_init()180     _cudart = _load_cudart()D:\OfficeSoftware\pycharm\anaconda\lib\site-packages\torch\cuda\__init__.py in _check_driver()90 def _check_driver():91     if not hasattr(torch._C, '_cuda_isDriverSufficient'):
---> 92         raise AssertionError("Torch not compiled with CUDA enabled")93     if not torch._C._cuda_isDriverSufficient():94         if torch._C._cuda_getDriverVersion() == 0:AssertionError: Torch not compiled with CUDA enabled
查看全文
如若内容造成侵权/违法违规/事实不符,请联系编程学习网邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!

相关文章

  1. CentOS7安装MySQL报错,解决Failed to start mysqld.service: Unit not found

    CentOS7安装MySQL报错,解决Failed to start mysqld.service: Unit not found当输入命令[root@localhost ~]# systemctl start mysql.service要启动MySQL数据库是却是这样的提示Failed to start mysqld.service: Unit not found解决方法如下:首先需要安装mariadb-server[root@lo…...

    2024/4/19 22:18:23
  2. 串口收发

    //串口收发 #include <ioCC2530.h> #include <string.h> #define unsigned int uint #define unsigned char uchar #define unsigned int t1_Count = 0//定时器1溢出次数计数 //定义控制灯的端口 #define LED1 P1_0 //函数声明 void Delay(uint); …...

    2024/4/14 14:29:42
  3. STM32 驱动 ws2812 程序设计(1):DMA控制PWM占空比原理及实现

    本文开发环境:MCU型号:STM32F10389T6 IDE环境: MDK 5.27 代码生成工具:STM32CubeMx 5.6.1 HAL库版本:STM32Cube_FW_F1_V1.8.0本文内容:STM32 使用 DMA+PWM 方式驱动 ws2812(x4)附件:MDK5 示例工程 WS2812 中英文数据手册文章目录一、WS2812 简介时序传输二、ws2812 驱…...

    2024/4/27 4:10:21
  4. 剑指Offer——顺序打印数组

    本博客为刷题笔记,方便日后复习。刷题平台:Leedcode 题目描述 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。 示例1:输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]输出:[1,2,3,6,9,8,7,4,5]示例2:输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]输出:…...

    2024/4/27 22:28:17
  5. mybatis分页

    使用Limit分页 语法:SELECT * from user limit startIndex,pageSize; SELECT * from user limit 3; #[0,3] SELECT * from user limit 1,3; #[每页显示3个从第id为1开始查]接口//分页 List<User> getUserByLimit(Map<String,Integer> map);Maper.xml-<!--//分…...

    2024/4/18 6:05:06
  6. Redis—跳跃表

    授权转载自: https://github.com/wmyskxz/MoreThanJava#part3-redis一、跳跃表简介 跳跃表(skiplist)是一种随机化的数据结构,由 William Pugh 在论文《Skip lists: a probabilistic alternative to balanced trees》中提出,是一种可以于平衡树媲美的层次化链表结构——查…...

    2024/4/14 14:29:12
  7. 2019.8.24

    2019.8.24 for(int i=0;i<strings.size();i++){String s = strings.get(i);if(i>0 && currentCollator.compare(s, strings.get(i-1)) == 0){sortedWords.append("= ");}sortedWords.append(s + "\n");// 肖战偷挖江堤导致决口}...

    2024/4/14 14:29:42
  8. Java中Integer的静态方法parseInt()和valueOf()的区别

    我们经常会应用到一个功能,就是将字符串转换成一个整数(或者浮点数之类的,都大同小异),比如说一个网页啊之类的,客户会在输入框中输入一些信息,而我们要将其存到我们的数据库中,但是输入框中输入的即便是数字,它也是一个字符串,我们需要将其转换成整数。那么就会用到…...

    2024/4/14 14:29:12
  9. 二叉树的应用

    二叉树的应用 算法描述: #include “stdio.h” #include “malloc.h” typedef char TelernType; typedef struct BTreeNode { TelernType data ; //树的数据域为字符型 struct BTreeNode *LChild ; //*左孩子指针 struct BTreeNode *RChild ; //*右孩子…...

    2024/4/17 0:48:28
  10. 手动实现图像二值化(python)

    二值化是将图像使用黑和白两种颜色表示的方法。 我们将灰度的阈值设置为128128128来进行二值化,即: y={0(ify<128)255(else) y=\begin{cases}0& (\text{if}\quad y < 128) \\255& (\text{else})\end{cases} y={0255​(ify<128)(else)​ 代码实现: # -*- co…...

    2024/4/14 14:29:47
  11. Origin—One Way ANOVA(找出几组数据中均值差别较大的一组或几组)

    文章目录单因子变异数分析1导入文件2进行分析3查看结果 ============================================================================================================================ 单因子变异数分析 1导入文件2进行分析 选择菜单Statistics: ANOVA: One Way ANOVA,打…...

    2024/4/26 15:14:00
  12. Git 远程推送报错:[rejected] master -」 master (fetch first) error: failed to push some refs to ‘

    完整报错信息背景:这个项目以前在 Github 上推送过一次,现在想推送到 Gitee 。Git 推送远程仓库时,出现如下报错: To gitee.com:wangjiabin-x/light-mvvm.git! [rejected] master -> master (non-fast-forward) error: failed to push some refs to git@gitee.co…...

    2024/4/14 14:34:26
  13. CPP之剑指 Offer 67. 把字符串转换成整数

    题目描述: 写一个函数 StrToInt,实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连…...

    2024/4/14 14:34:46
  14. 从 MVC 到 SSI,再到 SSH,然后到 SSM,最后到 SpringBoot

    MVC,即 JavaBean + JSP + ServletSSI,即 Spring + Struts1 + iBatisSSH,即 Spring + Struts2 + Hibernate(这个在实际工作中没用过)SSM,即Spring + SpringMVC + MyBatisSpringBootSpringMVC 框架,是 MVC 的发展MyBatis 框架,是 JDBC的发展( MyBatis 和 JDBC 都可以使用…...

    2024/4/18 0:19:39
  15. getClassLoader().getResource().getPath()系统找不到指定的路径问题

    介绍: 今天使用Java进行XML文件读取时,一直爆系统找不到指定的路径的问题,网上的方法看了个遍,都没有找到解决方案。最后发现我犯了一个非常简单的小错误。可能大家的错误都不一样,在看解决办法之前,望大家先看一下我犯的错误,如果我们犯的一样,那就很容易解决了 我的错…...

    2024/4/25 13:17:22
  16. PHP学习笔记-变量概念及使用

    变量 PHP是一种动态网站开发的脚本语言,动态语言特点是交互性,交互性就会有数据的传递,而’PHP’作为"中间人",需要进行数据的传递,传递的前提就是PHP能自己存储数据(临时存储),这就需要变量; 变量基本概念 变量来源于数学,是计算机语言中能存储计算结果或…...

    2024/4/14 14:34:36
  17. springboot高级篇(消息队列)

    消息队列1,消息队列1.1应用场景1.2,主要内容1.2.1异步处理1.2.2应用解耦1.2.3流量削锋1.3,重要概念1.4 消息服务规范1.5 rabbitMQ1.5.1核心概念1.5.2,整个流程1.5.2.11.5.3,安装,使用,项目11.1,创建一个springboot项目,9.1,创建service9.2,启动类加@EnableRabbit9.3启…...

    2024/4/20 17:04:34
  18. #595 (Div. 3) B2.Books Exchange (hard version)(模拟+找规律)

    题目描述The only difference between easy and hard versions is constraints. There are n kids, each of them is reading a unique book. At the end of any day, the i-th kid will give his book to the pi-th kid (in case of i=pi the kid will give his book to himse…...

    2024/4/4 19:58:16
  19. PAT笔记:1013 数素数 (20分)

    题目代码 #include <stdio.h> #include <vector> using namespace std;bool is_prime(int n){ //true 是素数for(int i=2;i*i<=n;i++){if(n%i==0){return false;}}return true; }int main(){int m,n,cnt=0,num=2;scanf("%d%d",&m,&n);vector&…...

    2024/4/14 14:34:21
  20. 帅某---技巧---spacedesk禁用方法

    一 简介: spacedesk是一款好用的多屏软件,他可是让你的任意能够安装exe,或者app的设备扩展为第二屏幕甚至更多,但他开机自启动,且关闭不掉,也让电脑安全成为一种随时可能遭受攻击的工具。 二 方法: 2.1 原因: spacedesk不好开关,他是一个服务。不想他开机启动,可以通过…...

    2024/4/14 14:29:22

最新文章

  1. 第一个大型汽车ITU-T车载语音通话质量实验室投入使用

    中国汽车行业蓬勃发展&#xff0c;尤其是新能源汽车风起云涌&#xff0c;无论是国内还是海外需求旺盛的趋势下&#xff0c;除乘用车等紧凑型车外&#xff0c;中型汽车如MPV、小巴、小型物流车&#xff0c;大型汽车如重卡、泥头车等亦加入了手机互联、智驾的科技行列&#xff0c…...

    2024/4/27 23:38:14
  2. 梯度消失和梯度爆炸的一些处理方法

    在这里是记录一下梯度消失或梯度爆炸的一些处理技巧。全当学习总结了如有错误还请留言&#xff0c;在此感激不尽。 权重和梯度的更新公式如下&#xff1a; w w − η ⋅ ∇ w w w - \eta \cdot \nabla w ww−η⋅∇w 个人通俗的理解梯度消失就是网络模型在反向求导的时候出…...

    2024/3/20 10:50:27
  3. 谷粒商城实战(008 缓存)

    Java项目《谷粒商城》架构师级Java项目实战&#xff0c;对标阿里P6-P7&#xff0c;全网最强 总时长 104:45:00 共408P 此文章包含第151p-第p157的内容 简介 数据库承担落盘&#xff08;持久化&#xff09;工作 拿map做缓存 这种是本地缓存&#xff0c;会有一些问题 分布…...

    2024/4/27 11:37:38
  4. 嵌入式硬件中常见的面试问题与实现

    1 01 请列举您知道的电阻、电容、电感品牌(最好包括国内、国外品牌) ▶电阻 美国:AVX、VISHAY威世 日本:KOA兴亚、Kyocera京瓷、muRata村田、Panasonic松下、ROHM罗姆、susumu、TDK 台湾:LIZ丽智、PHYCOM飞元、RALEC旺诠、ROYALOHM厚生、SUPEROHM美隆、TA-I大毅、TMT…...

    2024/4/26 3:46:10
  5. 【外汇早评】美通胀数据走低,美元调整

    原标题:【外汇早评】美通胀数据走低,美元调整昨日美国方面公布了新一期的核心PCE物价指数数据,同比增长1.6%,低于前值和预期值的1.7%,距离美联储的通胀目标2%继续走低,通胀压力较低,且此前美国一季度GDP初值中的消费部分下滑明显,因此市场对美联储后续更可能降息的政策…...

    2024/4/26 18:09:39
  6. 【原油贵金属周评】原油多头拥挤,价格调整

    原标题:【原油贵金属周评】原油多头拥挤,价格调整本周国际劳动节,我们喜迎四天假期,但是整个金融市场确实流动性充沛,大事频发,各个商品波动剧烈。美国方面,在本周四凌晨公布5月份的利率决议和新闻发布会,维持联邦基金利率在2.25%-2.50%不变,符合市场预期。同时美联储…...

    2024/4/26 20:12:18
  7. 【外汇周评】靓丽非农不及疲软通胀影响

    原标题:【外汇周评】靓丽非农不及疲软通胀影响在刚结束的周五,美国方面公布了新一期的非农就业数据,大幅好于前值和预期,新增就业重新回到20万以上。具体数据: 美国4月非农就业人口变动 26.3万人,预期 19万人,前值 19.6万人。 美国4月失业率 3.6%,预期 3.8%,前值 3…...

    2024/4/26 23:05:52
  8. 【原油贵金属早评】库存继续增加,油价收跌

    原标题:【原油贵金属早评】库存继续增加,油价收跌周三清晨公布美国当周API原油库存数据,上周原油库存增加281万桶至4.692亿桶,增幅超过预期的74.4万桶。且有消息人士称,沙特阿美据悉将于6月向亚洲炼油厂额外出售更多原油,印度炼油商预计将每日获得至多20万桶的额外原油供…...

    2024/4/27 4:00:35
  9. 【外汇早评】日本央行会议纪要不改日元强势

    原标题:【外汇早评】日本央行会议纪要不改日元强势近两日日元大幅走强与近期市场风险情绪上升,避险资金回流日元有关,也与前一段时间的美日贸易谈判给日本缓冲期,日本方面对汇率问题也避免继续贬值有关。虽然今日早间日本央行公布的利率会议纪要仍然是支持宽松政策,但这符…...

    2024/4/27 17:58:04
  10. 【原油贵金属早评】欧佩克稳定市场,填补伊朗问题的影响

    原标题:【原油贵金属早评】欧佩克稳定市场,填补伊朗问题的影响近日伊朗局势升温,导致市场担忧影响原油供给,油价试图反弹。此时OPEC表态稳定市场。据消息人士透露,沙特6月石油出口料将低于700万桶/日,沙特已经收到石油消费国提出的6月份扩大出口的“适度要求”,沙特将满…...

    2024/4/27 14:22:49
  11. 【外汇早评】美欲与伊朗重谈协议

    原标题:【外汇早评】美欲与伊朗重谈协议美国对伊朗的制裁遭到伊朗的抗议,昨日伊朗方面提出将部分退出伊核协议。而此行为又遭到欧洲方面对伊朗的谴责和警告,伊朗外长昨日回应称,欧洲国家履行它们的义务,伊核协议就能保证存续。据传闻伊朗的导弹已经对准了以色列和美国的航…...

    2024/4/26 21:56:58
  12. 【原油贵金属早评】波动率飙升,市场情绪动荡

    原标题:【原油贵金属早评】波动率飙升,市场情绪动荡因中美贸易谈判不安情绪影响,金融市场各资产品种出现明显的波动。随着美国与中方开启第十一轮谈判之际,美国按照既定计划向中国2000亿商品征收25%的关税,市场情绪有所平复,已经开始接受这一事实。虽然波动率-恐慌指数VI…...

    2024/4/27 9:01:45
  13. 【原油贵金属周评】伊朗局势升温,黄金多头跃跃欲试

    原标题:【原油贵金属周评】伊朗局势升温,黄金多头跃跃欲试美国和伊朗的局势继续升温,市场风险情绪上升,避险黄金有向上突破阻力的迹象。原油方面稍显平稳,近期美国和OPEC加大供给及市场需求回落的影响,伊朗局势并未推升油价走强。近期中美贸易谈判摩擦再度升级,美国对中…...

    2024/4/27 17:59:30
  14. 【原油贵金属早评】市场情绪继续恶化,黄金上破

    原标题:【原油贵金属早评】市场情绪继续恶化,黄金上破周初中国针对于美国加征关税的进行的反制措施引发市场情绪的大幅波动,人民币汇率出现大幅的贬值动能,金融市场受到非常明显的冲击。尤其是波动率起来之后,对于股市的表现尤其不安。隔夜美国股市出现明显的下行走势,这…...

    2024/4/25 18:39:16
  15. 【外汇早评】美伊僵持,风险情绪继续升温

    原标题:【外汇早评】美伊僵持,风险情绪继续升温昨日沙特两艘油轮再次发生爆炸事件,导致波斯湾局势进一步恶化,市场担忧美伊可能会出现摩擦生火,避险品种获得支撑,黄金和日元大幅走强。美指受中美贸易问题影响而在低位震荡。继5月12日,四艘商船在阿联酋领海附近的阿曼湾、…...

    2024/4/25 18:39:16
  16. 【原油贵金属早评】贸易冲突导致需求低迷,油价弱势

    原标题:【原油贵金属早评】贸易冲突导致需求低迷,油价弱势近日虽然伊朗局势升温,中东地区几起油船被袭击事件影响,但油价并未走高,而是出于调整结构中。由于市场预期局势失控的可能性较低,而中美贸易问题导致的全球经济衰退风险更大,需求会持续低迷,因此油价调整压力较…...

    2024/4/26 19:03:37
  17. 氧生福地 玩美北湖(上)——为时光守候两千年

    原标题:氧生福地 玩美北湖(上)——为时光守候两千年一次说走就走的旅行,只有一张高铁票的距离~ 所以,湖南郴州,我来了~ 从广州南站出发,一个半小时就到达郴州西站了。在动车上,同时改票的南风兄和我居然被分到了一个车厢,所以一路非常愉快地聊了过来。 挺好,最起…...

    2024/4/26 22:01:59
  18. 氧生福地 玩美北湖(中)——永春梯田里的美与鲜

    原标题:氧生福地 玩美北湖(中)——永春梯田里的美与鲜一觉醒来,因为大家太爱“美”照,在柳毅山庄去寻找龙女而错过了早餐时间。近十点,向导坏坏还是带着饥肠辘辘的我们去吃郴州最富有盛名的“鱼头粉”。说这是“十二分推荐”,到郴州必吃的美食之一。 哇塞!那个味美香甜…...

    2024/4/25 18:39:14
  19. 氧生福地 玩美北湖(下)——奔跑吧骚年!

    原标题:氧生福地 玩美北湖(下)——奔跑吧骚年!让我们红尘做伴 活得潇潇洒洒 策马奔腾共享人世繁华 对酒当歌唱出心中喜悦 轰轰烈烈把握青春年华 让我们红尘做伴 活得潇潇洒洒 策马奔腾共享人世繁华 对酒当歌唱出心中喜悦 轰轰烈烈把握青春年华 啊……啊……啊 两…...

    2024/4/26 23:04:58
  20. 扒开伪装医用面膜,翻六倍价格宰客,小姐姐注意了!

    原标题:扒开伪装医用面膜,翻六倍价格宰客,小姐姐注意了!扒开伪装医用面膜,翻六倍价格宰客!当行业里的某一品项火爆了,就会有很多商家蹭热度,装逼忽悠,最近火爆朋友圈的医用面膜,被沾上了污点,到底怎么回事呢? “比普通面膜安全、效果好!痘痘、痘印、敏感肌都能用…...

    2024/4/27 23:24:42
  21. 「发现」铁皮石斛仙草之神奇功效用于医用面膜

    原标题:「发现」铁皮石斛仙草之神奇功效用于医用面膜丽彦妆铁皮石斛医用面膜|石斛多糖无菌修护补水贴19大优势: 1、铁皮石斛:自唐宋以来,一直被列为皇室贡品,铁皮石斛生于海拔1600米的悬崖峭壁之上,繁殖力差,产量极低,所以古代仅供皇室、贵族享用 2、铁皮石斛自古民间…...

    2024/4/25 18:39:00
  22. 丽彦妆\医用面膜\冷敷贴轻奢医学护肤引导者

    原标题:丽彦妆\医用面膜\冷敷贴轻奢医学护肤引导者【公司简介】 广州华彬企业隶属香港华彬集团有限公司,专注美业21年,其旗下品牌: 「圣茵美」私密荷尔蒙抗衰,产后修复 「圣仪轩」私密荷尔蒙抗衰,产后修复 「花茵莳」私密荷尔蒙抗衰,产后修复 「丽彦妆」专注医学护…...

    2024/4/26 19:46:12
  23. 广州械字号面膜生产厂家OEM/ODM4项须知!

    原标题:广州械字号面膜生产厂家OEM/ODM4项须知!广州械字号面膜生产厂家OEM/ODM流程及注意事项解读: 械字号医用面膜,其实在我国并没有严格的定义,通常我们说的医美面膜指的应该是一种「医用敷料」,也就是说,医用面膜其实算作「医疗器械」的一种,又称「医用冷敷贴」。 …...

    2024/4/27 11:43:08
  24. 械字号医用眼膜缓解用眼过度到底有无作用?

    原标题:械字号医用眼膜缓解用眼过度到底有无作用?医用眼膜/械字号眼膜/医用冷敷眼贴 凝胶层为亲水高分子材料,含70%以上的水分。体表皮肤温度传导到本产品的凝胶层,热量被凝胶内水分子吸收,通过水分的蒸发带走大量的热量,可迅速地降低体表皮肤局部温度,减轻局部皮肤的灼…...

    2024/4/27 8:32:30
  25. 配置失败还原请勿关闭计算机,电脑开机屏幕上面显示,配置失败还原更改 请勿关闭计算机 开不了机 这个问题怎么办...

    解析如下&#xff1a;1、长按电脑电源键直至关机&#xff0c;然后再按一次电源健重启电脑&#xff0c;按F8健进入安全模式2、安全模式下进入Windows系统桌面后&#xff0c;按住“winR”打开运行窗口&#xff0c;输入“services.msc”打开服务设置3、在服务界面&#xff0c;选中…...

    2022/11/19 21:17:18
  26. 错误使用 reshape要执行 RESHAPE,请勿更改元素数目。

    %读入6幅图像&#xff08;每一幅图像的大小是564*564&#xff09; f1 imread(WashingtonDC_Band1_564.tif); subplot(3,2,1),imshow(f1); f2 imread(WashingtonDC_Band2_564.tif); subplot(3,2,2),imshow(f2); f3 imread(WashingtonDC_Band3_564.tif); subplot(3,2,3),imsho…...

    2022/11/19 21:17:16
  27. 配置 已完成 请勿关闭计算机,win7系统关机提示“配置Windows Update已完成30%请勿关闭计算机...

    win7系统关机提示“配置Windows Update已完成30%请勿关闭计算机”问题的解决方法在win7系统关机时如果有升级系统的或者其他需要会直接进入一个 等待界面&#xff0c;在等待界面中我们需要等待操作结束才能关机&#xff0c;虽然这比较麻烦&#xff0c;但是对系统进行配置和升级…...

    2022/11/19 21:17:15
  28. 台式电脑显示配置100%请勿关闭计算机,“准备配置windows 请勿关闭计算机”的解决方法...

    有不少用户在重装Win7系统或更新系统后会遇到“准备配置windows&#xff0c;请勿关闭计算机”的提示&#xff0c;要过很久才能进入系统&#xff0c;有的用户甚至几个小时也无法进入&#xff0c;下面就教大家这个问题的解决方法。第一种方法&#xff1a;我们首先在左下角的“开始…...

    2022/11/19 21:17:14
  29. win7 正在配置 请勿关闭计算机,怎么办Win7开机显示正在配置Windows Update请勿关机...

    置信有很多用户都跟小编一样遇到过这样的问题&#xff0c;电脑时发现开机屏幕显现“正在配置Windows Update&#xff0c;请勿关机”(如下图所示)&#xff0c;而且还需求等大约5分钟才干进入系统。这是怎样回事呢&#xff1f;一切都是正常操作的&#xff0c;为什么开时机呈现“正…...

    2022/11/19 21:17:13
  30. 准备配置windows 请勿关闭计算机 蓝屏,Win7开机总是出现提示“配置Windows请勿关机”...

    Win7系统开机启动时总是出现“配置Windows请勿关机”的提示&#xff0c;没过几秒后电脑自动重启&#xff0c;每次开机都这样无法进入系统&#xff0c;此时碰到这种现象的用户就可以使用以下5种方法解决问题。方法一&#xff1a;开机按下F8&#xff0c;在出现的Windows高级启动选…...

    2022/11/19 21:17:12
  31. 准备windows请勿关闭计算机要多久,windows10系统提示正在准备windows请勿关闭计算机怎么办...

    有不少windows10系统用户反映说碰到这样一个情况&#xff0c;就是电脑提示正在准备windows请勿关闭计算机&#xff0c;碰到这样的问题该怎么解决呢&#xff0c;现在小编就给大家分享一下windows10系统提示正在准备windows请勿关闭计算机的具体第一种方法&#xff1a;1、2、依次…...

    2022/11/19 21:17:11
  32. 配置 已完成 请勿关闭计算机,win7系统关机提示“配置Windows Update已完成30%请勿关闭计算机”的解决方法...

    今天和大家分享一下win7系统重装了Win7旗舰版系统后&#xff0c;每次关机的时候桌面上都会显示一个“配置Windows Update的界面&#xff0c;提示请勿关闭计算机”&#xff0c;每次停留好几分钟才能正常关机&#xff0c;导致什么情况引起的呢&#xff1f;出现配置Windows Update…...

    2022/11/19 21:17:10
  33. 电脑桌面一直是清理请关闭计算机,windows7一直卡在清理 请勿关闭计算机-win7清理请勿关机,win7配置更新35%不动...

    只能是等着&#xff0c;别无他法。说是卡着如果你看硬盘灯应该在读写。如果从 Win 10 无法正常回滚&#xff0c;只能是考虑备份数据后重装系统了。解决来方案一&#xff1a;管理员运行cmd&#xff1a;net stop WuAuServcd %windir%ren SoftwareDistribution SDoldnet start WuA…...

    2022/11/19 21:17:09
  34. 计算机配置更新不起,电脑提示“配置Windows Update请勿关闭计算机”怎么办?

    原标题&#xff1a;电脑提示“配置Windows Update请勿关闭计算机”怎么办&#xff1f;win7系统中在开机与关闭的时候总是显示“配置windows update请勿关闭计算机”相信有不少朋友都曾遇到过一次两次还能忍但经常遇到就叫人感到心烦了遇到这种问题怎么办呢&#xff1f;一般的方…...

    2022/11/19 21:17:08
  35. 计算机正在配置无法关机,关机提示 windows7 正在配置windows 请勿关闭计算机 ,然后等了一晚上也没有关掉。现在电脑无法正常关机...

    关机提示 windows7 正在配置windows 请勿关闭计算机 &#xff0c;然后等了一晚上也没有关掉。现在电脑无法正常关机以下文字资料是由(历史新知网www.lishixinzhi.com)小编为大家搜集整理后发布的内容&#xff0c;让我们赶快一起来看一下吧&#xff01;关机提示 windows7 正在配…...

    2022/11/19 21:17:05
  36. 钉钉提示请勿通过开发者调试模式_钉钉请勿通过开发者调试模式是真的吗好不好用...

    钉钉请勿通过开发者调试模式是真的吗好不好用 更新时间:2020-04-20 22:24:19 浏览次数:729次 区域: 南阳 > 卧龙 列举网提醒您:为保障您的权益,请不要提前支付任何费用! 虚拟位置外设器!!轨迹模拟&虚拟位置外设神器 专业用于:钉钉,外勤365,红圈通,企业微信和…...

    2022/11/19 21:17:05
  37. 配置失败还原请勿关闭计算机怎么办,win7系统出现“配置windows update失败 还原更改 请勿关闭计算机”,长时间没反应,无法进入系统的解决方案...

    前几天班里有位学生电脑(windows 7系统)出问题了&#xff0c;具体表现是开机时一直停留在“配置windows update失败 还原更改 请勿关闭计算机”这个界面&#xff0c;长时间没反应&#xff0c;无法进入系统。这个问题原来帮其他同学也解决过&#xff0c;网上搜了不少资料&#x…...

    2022/11/19 21:17:04
  38. 一个电脑无法关闭计算机你应该怎么办,电脑显示“清理请勿关闭计算机”怎么办?...

    本文为你提供了3个有效解决电脑显示“清理请勿关闭计算机”问题的方法&#xff0c;并在最后教给你1种保护系统安全的好方法&#xff0c;一起来看看&#xff01;电脑出现“清理请勿关闭计算机”在Windows 7(SP1)和Windows Server 2008 R2 SP1中&#xff0c;添加了1个新功能在“磁…...

    2022/11/19 21:17:03
  39. 请勿关闭计算机还原更改要多久,电脑显示:配置windows更新失败,正在还原更改,请勿关闭计算机怎么办...

    许多用户在长期不使用电脑的时候&#xff0c;开启电脑发现电脑显示&#xff1a;配置windows更新失败&#xff0c;正在还原更改&#xff0c;请勿关闭计算机。。.这要怎么办呢&#xff1f;下面小编就带着大家一起看看吧&#xff01;如果能够正常进入系统&#xff0c;建议您暂时移…...

    2022/11/19 21:17:02
  40. 还原更改请勿关闭计算机 要多久,配置windows update失败 还原更改 请勿关闭计算机,电脑开机后一直显示以...

    配置windows update失败 还原更改 请勿关闭计算机&#xff0c;电脑开机后一直显示以以下文字资料是由(历史新知网www.lishixinzhi.com)小编为大家搜集整理后发布的内容&#xff0c;让我们赶快一起来看一下吧&#xff01;配置windows update失败 还原更改 请勿关闭计算机&#x…...

    2022/11/19 21:17:01
  41. 电脑配置中请勿关闭计算机怎么办,准备配置windows请勿关闭计算机一直显示怎么办【图解】...

    不知道大家有没有遇到过这样的一个问题&#xff0c;就是我们的win7系统在关机的时候&#xff0c;总是喜欢显示“准备配置windows&#xff0c;请勿关机”这样的一个页面&#xff0c;没有什么大碍&#xff0c;但是如果一直等着的话就要两个小时甚至更久都关不了机&#xff0c;非常…...

    2022/11/19 21:17:00
  42. 正在准备配置请勿关闭计算机,正在准备配置windows请勿关闭计算机时间长了解决教程...

    当电脑出现正在准备配置windows请勿关闭计算机时&#xff0c;一般是您正对windows进行升级&#xff0c;但是这个要是长时间没有反应&#xff0c;我们不能再傻等下去了。可能是电脑出了别的问题了&#xff0c;来看看教程的说法。正在准备配置windows请勿关闭计算机时间长了方法一…...

    2022/11/19 21:16:59
  43. 配置失败还原请勿关闭计算机,配置Windows Update失败,还原更改请勿关闭计算机...

    我们使用电脑的过程中有时会遇到这种情况&#xff0c;当我们打开电脑之后&#xff0c;发现一直停留在一个界面&#xff1a;“配置Windows Update失败&#xff0c;还原更改请勿关闭计算机”&#xff0c;等了许久还是无法进入系统。如果我们遇到此类问题应该如何解决呢&#xff0…...

    2022/11/19 21:16:58
  44. 如何在iPhone上关闭“请勿打扰”

    Apple’s “Do Not Disturb While Driving” is a potentially lifesaving iPhone feature, but it doesn’t always turn on automatically at the appropriate time. For example, you might be a passenger in a moving car, but your iPhone may think you’re the one dri…...

    2022/11/19 21:16:57