'''
import torch
from torch import nn
from torch.nn import functional as F
X = torch.rand(2,20)
'''
'''
#自定义块
class MLP(nn.Module):
#用模型参数声明层。声明两个全连接层
def __init__(self):
#调用MLP的父类Module的构造函数来执行必要的初始化。
#在类实例化时也可以指定其它函数参数,例如模型参数params
super().__init__()
self.hidden = nn.Linear(20,256) #隐藏层
self.out = nn.Linear(256,10) #输出层
#定义模型的前向传播,即如何根据输入X返回所需的模型输出
def forward(self,X):
#使用Relu函数版本,其在nn.functional模块中定义
return self.out(F.relu(self.hidden(X)))
net = MLP()
print(net(X))
'''
'''
#顺序块
class MySequential(nn.Module):
def __init__(self,*args):
super().__init__()
for idx,module in enumerate(args):
#module是Module子类的一个实例,把它保存在‘Module'类的成员
#变量_modules中。_module的类型是OrderedDict
self.__module__[str(idx)] = module
def forward(self,X):
#OrderedDict保证了按照成员添加的顺序遍历它们
for block in self.__module__.values():
X = block(X)
return X
net = MySequential(nn.Linear(20,256),nn.ReLU(),nn.Linear(256,10))
print(net(X))
'''
'''
#在前向传播函数中执行代码
class FixedHiddenMLP(nn.Module):
def __init__(self):
super().__init__()
#不计算梯度的随机权重参数。因此其在训练期间保持不变
self.rand_weight = torch.rand((20,20),requires_grad=False)
self.linear = nn.Linear(20,20)
def forward(self,X):
X = self.linear(X)
#使用创建的常量参数以及relu 和 mm函数
X = F.relu(torch.mm(X,self.rand_weight) + 1)
#复用全连接层。相当于两个全连接层共享参数
X = self.linear(X)
#控制流
while X.abs().sum() > 1:
X /= 2
return X.sum()
net = FixedHiddenMLP()
print(net(X))
#嵌套块
class NestMLP(nn.Module):
def __init__(self):
super().__init__()
self.net = nn.Sequential(nn.Linear(20,64),nn.ReLU(),
nn.Linear(64,32),nn.ReLU())
self.linear = nn.Linear(32,16)
def forward(self,X):
return self.linear(self.net(X))
chimera = nn.Sequential(NestMLP(),nn.Linear(16,20),FixedHiddenMLP())
print(chimera(X))
'''
#参数管理
import torch
from torch import nn
'''
net = nn.Sequential(nn.Linear(4,8),nn.ReLU(),nn.Linear(8,1))
X = torch.rand(size=(2,4))
print(X)
print(net(X))
print(net[2].state_dict())
print(type(net[2].bias))
print(net[2].bias)
print(net[2].bias.data)
net[2].weight.grad == None
print(*[(name,param.shape) for name,param in net[0].named_parameters()])
print(*[(name,param.shape) for name,param in net.named_parameters()])
'''
'''
X = torch.rand(size=(2,4))
def block1():
return nn.Sequential(nn.Linear(4,8),nn.ReLU(),
nn.Linear(8,4),nn.ReLU())
def block2():
net = nn.Sequential()
for i in range(4):
#在这里嵌套
net.add_module(f'block{i}',block1())
return net
rgnet = nn.Sequential(block2(),nn.Linear(4,1))
print(rgnet)
print(rgnet[0][1][0].bias.data)
'''
import torch
from torch import nn
net = nn.Sequential(nn.Linear(4, 8), nn.ReLU(), nn.Linear(8, 1))
#首先调用内置的初始化器。将所有权重参数初始化为标准差为0.01的高斯随机变量,且将偏置参数设置为0。
'''
def init_normal(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight,mean=0,std=0.01)
nn.init.zeros_(m.bias)
print(net.apply(init_normal))
print(net[0].weight.data[0],net[0].bias.data[0])
'''
'''
#将所有参数初始化为给定的常数,比如初始化为1。
def init_constant(m):
if type(m) == nn.Linear:
nn.init.constant_(m.weight,1)
nn.init.zeros_(m.bias)
print(net.apply(init_constant))
print(net[0].weight.data[0],net[0].bias.data[0])
'''
'''
def init_xavier(m):
if type(m) == nn.Linear:
nn.init.xavier_uniform_(m.weight)
def init_42(m):
if type(m) == nn.Linear:
nn.init.constant_(m.weight,42)
print(net[0].apply(init_xavier))
print(net[2].apply(init_42))
print(net[0].weight.data[0])
print(net[2].weight.data[0])
'''
'''
def my_init(m):
if type(m) == nn.Linear:
print("Init",*[(name,param.shape)
for name,param in m.named_parameters()][0])
nn.init.uniform_(m.weight,-10,10)
m.weight.data *= m.weight.data.abs() >= 5
print(net.apply(my_init))
print(net[0].weight[:2])
#可以直接设置参数。
net[0].weight.data[:] += 1
net[0].weight.data[0,0] =42
print(net[0].weight.data[0])
'''
'''
X = torch.rand(size=(2,4))
#在多个层间共享参数:可以定义一个稠密层,然后使用它的参数来设置另一个层的参数。
# 我们需要给共享层一个名称,以便可以引用它的参数
shared = nn.Linear(8,8)
net = nn.Sequential(nn.Linear(4,8),nn.ReLU(),
shared,nn.ReLU(),
shared,nn.ReLU(),
nn.Linear(8,1))
print(net(X))
#检查参数是否相同
print(net[2].weight.data[0] == net[4].weight.data[0])
net[2].weight.data[0,0] = 100
#确保它们实际上是同一个对象,而不只是有相同的值
print(net[2].weight.data[0] == net[4].weight.data[0])
'''
import torch
import torch.nn.functional as F
from torch import nn
'''
#CenteredLayer类要从其输入中减去均值,只需继承基础层类并实现前向传播功能。
class CenteredLayer(nn.Module):
def __init__(self):
super().__init__()
def forward(self,X):
return X - X.mean()
#向该层提供一些数据,验证它是否能按预期工作。
layer = CenteredLayer()
print(layer(torch.FloatTensor([1,2,3,4,5])))
#将层作为组件合并到更复杂的模型中。
net = nn.Sequential(nn.Linear(8,128),CenteredLayer())
#作为额外的健全性检查,可以在向该网络发送随机数据后,检查均值是否为0。由于是浮点数,因为存储精度的原因,仍然可能会看到一个非常小的非零数。
Y = net(torch.rand(4,8))
print(Y.mean())
'''
'''
#定义具有参数的层,这些参数可以通过训练进行调整。使用内置函数来创建参数,提供一些基本的管理功能。比如管理访问、初始化、共享、保存和加载模型参数,不需要为每个自定义层编写自定义的序列化程序。
#实现自定义版本的全连接层.使用修正线性单元作为激活函数。该层需要输入参数:in_units和units,分别表示输入数和输出数。
class MyLinear(nn.Module):
def __init__(self,in_units,units):
super().__init__()
self.weight = nn.Parameter(torch.randn(in_units,units))
self.bias = nn.Parameter(torch.randn(units,))
def forward(self,X):
linear = torch.matmul(X,self.weight.data) + self.bias.data
return F.relu(linear)
#实例化MyLinear类并访问其模型参数。
linear = MyLinear(5,3)
print(linear.weight)
print(linear(torch.rand(2,5)))
net = nn.Sequential(MyLinear(64,8),MyLinear(8,1))
print(net(torch.rand(2,64)))
'''
'''
import torch
from torch import nn
from torch.nn import functional as F
'''
'''
x = torch.arange(4)
#torch.save(x,'x-file')
#x2 = torch.load('x-file')
#print(x2)
y = torch.zeros(4)
torch.save([x,y],'x-files')
x2,y2 = torch.load('x-files')
print((x2,y2))
mydict = {'x':x,'y':y}
torch.save(mydict,'mydict')
mydict2 = torch.load('mydict')
print(mydict2)
'''
'''
#深度学习框架提供了内置函数来保存和加载整个网络。这将保存模型的参数而不是保存整个模型。
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.hidden = nn.Linear(20,256)
self.output = nn.Linear(256,10)
def forward(self,x):
return self.output(F.relu(self.hidden(x)))
net = MLP()
X = torch.randn(size=(2,20))
Y = net(X)
#将模型的参数存储在一个叫做“mlp.params”的文件中。
torch.save(net.state_dict(),'mlp.params')
#为了恢复模型,实例化了原始多层感知机模型的一个备份。不需要随机初始化模型参数,而是直接读取文件中存储的参数。
clone = MLP()
clone.load_state_dict(torch.load('mlp.params'))
print(clone.eval())
Y_clone = clone(X)
Y_clone == Y
'''
import torch
from torch import nn
'''
#!nvidia-smi
print(torch.device('cpu'),torch.device('cuda'),torch.device('cuda:1'))
print(torch.cuda.device_count())
'''
def try_gpu(i=0):
"""如果存在,则返回gpu(i),否则返回cpu()"""
if torch.cuda.device_count() >= i+1:
return torch.device(f'cuda:{i}')
return torch.device('cpu')
def try_all_gpus():
"""返回所有可用的GPU,如果没有GPU,则返回【cpu(),】"""
devices = [torch.device(f'cuda:{i}')
for i in range(torch.cuda.device_count())]
return devices if devices else [torch.device('cpu')]
#print(try_gpu(),try_gpu(10),try_all_gpus())
#x = torch.tensor([1,2,3])
#print(x.device)
X = torch.ones(2,3,device = try_gpu())
print(X)
net = nn.Sequential(nn.Linear(3,1))
net = net.to(device=try_gpu())
print(net(X))
print(net[0].weight.data.device)