内置的
先不初始化,等初次运行时自动推断形状,进行初始化,可以不用填输入特征数
PyTorch 主要为常用的全连接层、卷积层和归一化层提供了Lazy
版本
Linear()⇒LazyLinear()
Conv1d()⇒LazyConv1d()
自定义层的
class MyLayer(nn.Module):
def __init__(self,out_features):
super().__init__()
#nn.Parameter()告诉pytorch该参数需要训练
self.weight = None
self.out_features = out_features
def forward(self,x):
if self.weight is None:
in_features = x.shape[1]
self.weight = nn.Parameter(torch.randn(in_features.,out_features))
return torch.matmul(x, self.weight)