原始运行代码请参考以上两个链接,为避免侵权
本解决方案包括大部分报错,直接获取以上链接中代码,进行调试即可
俩链接的代码都一样
原因是博客中给的代码未加入resnet层
解决方法:把ResNet()函数内的代码改成如下(将模型返回+加入resnet_block),增加返回值,可以解决此问题
def ResNet():
model = torch.nn.Sequential(
torch.nn.Conv2d(1, 4, kernel_size=2, padding=1, stride=1),
torch.nn.BatchNorm2d(4),
torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size=2)
)
model.add_module("global_avg_pool", GlobalAvgPool2d())
model.add_module("fc", torch.nn.Sequential(FlattenLayer(), torch.nn.Linear(32, 2)))
return model
# 此处上面一行,加入了返回值 !!!!!
导入包 import time
dataloader是pytorch加载数据里常用方法,原作者在这里简化了包名,以下是dataloader原始使用方式:
train_data = TensorDataset(train_x_tensor, train_y_tensor)
test_data = TensorDataset(train_x_tensor, train_y_tensor)
tr_loader = torch.utils.data.DataLoader(train_data, batch_size, True)
test_loader = torch.utils.data.DataLoader(train_data, batch_size, True)
解决方案:
第一,使用原始方式,所以的dataloader加载代码更换如下格式:
# 源代码:
test_batch = Data.DataLoader(torch_testset, batch_size=batch_size, shuffle=False, num_workers=works_num)
# 更改为:
test_batch = torch.utils.data.DataLoader(torch_testset, batch_size=batch_size, shuffle=False, num_workers=works_num)
或者,导入简化的包,代码如下:
import sys
from torch.utils.data import Dataset
import torch.utils.data as Data
import torch.nn.functional as F
解决方式:原因是博客中给的代码未加入resnet层
两个报错的解决方法:把ResNet()函数内的代码改成如下(将模型返回+加入resnet_block)
def ResNet():
model = torch.nn.Sequential(
torch.nn.Conv2d(1, 4, kernel_size=2, padding=1, stride=1),
torch.nn.BatchNorm2d(4),
torch.nn.ReLU(),
torch.nn.MaxPool2d(kernel_size=2),
resnet_block(4, 32, 2) # 这里加入resnet !!!!!!
)
model.add_module("global_avg_pool", GlobalAvgPool2d())
model.add_module("fc", torch.nn.Sequential(FlattenLayer(), torch.nn.Linear(32, 2)))
return model
解决方式:加上这段代码
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
在此处
# 3、训练验证模型
# 3.1 训练模型
def train(model, train_batch, test_batch, batch_size, optimizer, device, num_epochs):
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = model.to(device)
print("run in ", device)
运行结果:
2023.4.24
本文转载
Resnet网络回归的简单实现_resnet回归_飘满红楼的博客-CSDN博客
只是解决了作者代码的问题和在互联网其他地方搜集的解决方法,仅供参考,如有侵权可以联系删除