在PyTorch中手动初始化模型参数

我正在创建一个单独的类来初始化模型,并将层添加到一个列表中,但这些层并未被添加到模型的参数中,请告诉我如何将它们添加到模型的parameters()中。

class Mnist_Net(nn.Module):def __init__(self,input_dim,output_dim,hidden_layers=2,neurons=128):    super().__init__()    layers = []    for i in range(hidden_layers):        if len(layers) == 0:            layers.append(nn.Linear(input_dim,neurons))        if i == hidden_layers-1:            layers.append(nn.Linear(layers[-2].weight.shape[0],output_dim))        layers.append(nn.Linear(layers[i-1].weight.shape[0],neurons))    self.layers= layers

当我打印model.parameters()时

model = Mnist_Net(28*28,10,neurons=56)   for t in model.parameters():   print(t)

它显示为空,但是当我在类中像这样添加层时

self.layer1 = nn.Linear(input_dim,neurons)

它显示了一个层在parameters中。请告诉我如何将self.layers中的所有层添加到model.parameters()中


回答:

为了在父模块中注册,你的子模块本身应该是一个nn.Module。在你的情况下,你应该用nn.ModuleList包装layers

  self.layers = nn.ModuleList(layers)

这样,你的层就会被注册:

>>> model = Mnist_Net(28*28,10, neurons=56)>>> for t in model.parameters():...    print(t.shape)torch.Size([56, 784])torch.Size([56])torch.Size([56, 56])torch.Size([56])torch.Size([10, 56])torch.Size([10])torch.Size([56, 56])torch.Size([56])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注