如何解决为什么我总是得到与 pytorch 中 CNN 中的结果相同的值?
这是我的代码
dataset = pd.read_csv('augmented_data.csv')
dataset = dataset.sample(frac=1)
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet,self).__init__()
self.conv1 = nn.Conv2d(3,6,5)
self.pool = nn.MaxPool2d(2,2)
self.conv2 = nn.Conv2d(6,16,5)
self.fc1 = nn.Linear(1024144,120)
self.fc2 = nn.Linear(120,84)
self.fc3 = nn.Linear(84,1)
def forward(self,x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1,1024144)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
print(x)
x = self.fc3(x)
return x
files_read = 0
preprocess = transforms.Compose([
transforms.Resize(1024),transforms.ToTensor(),transforms.Normalize((0.5,0.5,0.5),(0.5,0.5))])
# device = torch.device('cuda' if torch.cuda.is_available else 'cpu')
device = torch.device('cpu')
# model = ConvNet().to(device)
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = optim.Adam(model.parameters(),lr=0.001)
results = []
for index,row in dataset.iterrows():
try:
image = load_img('padded_images/' + row['image_name'] +'.jpg')
except:
image = load_img('augmented_images/' + row['image_name'] +'.jpeg')
files_read += 1
input_tensor = preprocess(image)
input_batch = input_tensor.unsqueeze(0).to(device)
if files_read <= 80 * len(dataset) // 100:
output = model(input_batch)
optimizer.zero_grad()
y = torch.tensor([[float(row['target'])]]).to(device)
loss = criterion(output,y)
loss.backward()
optimizer.step()
else:
model.eval()
output = model(input_batch)
results.append([1.0 if output[0][0].double() > 0.5 else 0,float(row['target'])])
所以我使用 pytorch CNN 将 60k 图像分为 2 个类别。当我在模型训练后打印输出时,无论输入的图像是什么,输出总是“tensor([[0.6384]],grad_fn=)”。始终相同的值。所以它只预测 1(因为它大于 0.5)。问题是,当我在训练时打印输出时,结果会有所不同(16、1、0、4、0.6 等)但是当我打印输出(使用相同的模型但未经过训练)时,结果变化不大(0.5、0.51、0.49、0.52、0.55)。所以我认为可以肯定地说它正在收敛到一个单一的值。我只是不知道为什么。我可以做些什么不同的事情?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。