Pytorch CNN损失没有改变,

时间:2020-01-31 12:24:44

标签: python neural-network pytorch

我针对蜜蜂和蚂蚁图像之间的二进制分类问题制作了CNN。 图像尺寸为500x500,带有3个通道。

这是我的代码。

数据加载器:

hello world

CNN班

def load_data(path):
    data = []
    ant = 0
    bee = 0
    for folder in os.listdir(path):
        print(folder)
        curfolder = os.path.join(path, folder)
        for file in os.listdir(curfolder):
            image = plt.imread(curfolder+'/'+file)
            image = cv2.resize(image, (500,500))
            if folder == 'ants':
                ant += 1
                data.append([np.array(image) , np.eye(2)[0]])
            elif folder == 'bees':
                bee += 1
                data.append([np.array(image) , np.eye(2)[1]])

    np.random.shuffle(data)      
    np.save('train.npy',data)
    print('ants : ',ant)
    print('bees : ',bee)

training_data = np.load("train.npy",allow_pickle=True)
print(len(training_data))

损失和优化器

class Net(nn.Module):
    def __init__(self):
        super().__init__() # just run the init of parent class (nn.Module)
        self.conv1 = nn.Conv2d(3, 32, 5) # input is 1 image, 32 output channels, 5x5 kernel / window
        self.conv2 = nn.Conv2d(32, 64, 5) # input is 32, bc the first layer output 32. Then we say the output will be 64 channels, 5x5 kernel / window
        self.conv3 = nn.Conv2d(64, 128, 5)

        x = torch.randn(3,500,500).view(-1,3,500,500)
        self._to_linear = None
        self.convs(x)
        print(self._to_linear)
        self.fc1 = nn.Linear(self._to_linear, 512) #flattening.
        self.fc2 = nn.Linear(512, 2) # 512 in, 2 out bc we're doing 2 classes (dog vs cat).

    def convs(self, x):
        # max pooling over 2x2
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2))
        x = F.max_pool2d(F.relu(self.conv3(x)), (2, 2))

        if self._to_linear is None:
            self._to_linear = x[0].shape[0]*x[0].shape[1]*x[0].shape[2]
        return x

    def forward(self, x):
        x = self.convs(x)
        x = x.view(-1, self._to_linear)  # .view is reshape ... this flattens X before 
        x = F.relu(self.fc1(x))
        x = self.fc2(x) # bc this is our output layer. No activation here.
        return F.softmax(x, dim=1)

net = Net()
print(net)

数据平面

import torch.optim as optim

optimizer = optim.Adam(net.parameters(), lr=0.001)
loss_function = nn.MSELoss()

训练模型

train_X = torch.Tensor([i[0] for i in training_data]).view(-1,3,500,500)
train_X = train_X/255.0
train_y = torch.Tensor([i[1] for i in training_data])

损失不会在每个时期更新。我曾尝试更改学习率,但问题仍然存在。

Epoch:0。损失:0.23345321416854858

时代:1.损失:0.23345321416854858

Epoch:2。损失:0.23345321416854858

Epoch:3。损失:0.23345321416854858

Epoch:4。损失:0.23345321416854858

Epoch:5。损失:0.23345321416854858

Epoch:6。损失:0.23345321416854858

Epoch:7。损失:0.23345321416854858

Epoch:8。损失:0.23345321416854858

Epoch:9。损失:0.23345321416854858

谢谢。

1 个答案:

答案 0 :(得分:1)

在训练循环中,您应该做optimizer.zero_grad()而不是net.zero_grad()。另外,您正在使用MSELoss()解决分类问题,需要使用BinaryCrossEntropy()CrossEntropy()NLLLoss()之类的东西。

相关问题