请写一个三层神经网络结构,开头3个,第二个隐藏6个,三个是4,输出1的神经网络结构,并打印出这个模型各个层的参数,同时将参数保留在一个列表里面,这个列表的全部参数翻倍再赋值给一个新的模型
import torch
import torch.nn as nn
# 定义神经网络结构
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__()
self.fc1 = nn.Linear(3, 6)
self.fc2 = nn.Linear(6, 4)
self.fc3 = nn.Linear(4, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# 自定义初始化函数
def init_weights(m):
if type(m) == nn.Linear:
torch.nn.init.uniform_(m.weight, a=-1, b=1)
torch.nn.init.uniform_(m.bias, a=-1, b=1)
# 创建神经网络实例
model = NeuralNetwork()
# 打印模型结构
#print(model)
model.apply(init_weights)
# 打印模型各个层的参数
for name, param in model.named_parameters():
print(f"Layer: {name} | Size: {param.size()} | Values: {param}")
params_list=[param.clone() for name,param in model.named_parameters()]
# 将列表中的值翻倍
for param in params_list:
param.data*=2
# 将翻倍后的参数值赋值回模型
index = 0
for param in model.parameters():
param.data = params_list[index]
index += 1
print(index,param.data)
# 打印模型各个层的参数
for name, param in model.named_parameters():
print(f"Layer: {name} | Size: {param.size()} | Values: {param}")