Exemple #1
0
    def test_MNIST(self):
        max_epoch = 5
        batch_size = 100
        hidden_size = 1000

        train_set = dezero.datasets.MNIST(train=True)
        test_set = dezero.datasets.MNIST(train=False)
        train_loader = DataLoader(train_set, batch_size)
        test_loader = DataLoader(test_set, batch_size, shuffle=False)

        #model = MLP((hidden_size, 10))
        model = MLP((hidden_size, hidden_size, 10), activation=F.relu)
        optimizer = optimizers.SGD().setup(model)

        if dezero.cuda.gpu_enable:
            train_loader.to_gpu()
            model.to_gpu()

        for epoch in range(max_epoch):
            sum_loss, sum_acc = 0, 0
            for x, t in train_loader:
                y = model(x)
                loss = F.softmax_cross_entropy(y, t)
                acc = F.accuracy(y, t)
                model.cleargrads()
                loss.backward()
                optimizer.update()

                sum_loss += float(loss.data) * len(t)
                sum_acc += float(acc.data) * len(t)

            print('epoch: {}'.format(epoch + 1))
            print('train loss: {:.4f}, accuracy: {:.4f}'.format(
                sum_loss / len(train_set), sum_acc / len(train_set)))

            sum_loss, sum_acc = 0, 0
            with dezero.no_grad():
                for x, t in test_loader:
                    y = model(x)
                    loss = F.softmax_cross_entropy(y, t)
                    acc = F.accuracy(y, t)
                    sum_loss += float(loss.data) * len(t)
                    sum_acc += float(acc.data) * len(t)

                print('test loss: {:.4f}, accuracy: {:.4f}'.format(
                    sum_loss / len(test_set), sum_acc / len(test_set)))
Exemple #2
0
            l.W.data = 0.02 * np.random.randn(*l.W.data.shape)


init_weight(dis, gen, hidden_size)

opt_g = Adam(alpha=0.0002, beta1=0.5).setup(gen)
opt_d = Adam(alpha=0.0002, beta1=0.5).setup(dis)

transform = lambda x: (x / 255.0).astype(np.float32)
train_set = dezero.datasets.MNIST(train=True, transform=transform)
train_loader = DataLoader(train_set, batch_size)

if use_gpu:
    gen.to_gpu()
    dis.to_gpu()
    train_loader.to_gpu()
    xp = dezero.cuda.cupy
else:
    xp = np

label_real = xp.ones(batch_size).astype(np.int)
label_fake = xp.zeros(batch_size).astype(np.int)
test_z = xp.random.randn(25, hidden_size).astype(np.float32)


def generate_image():
    with dezero.test_mode():
        fake_images = gen(test_z)

    img = dezero.cuda.as_numpy(fake_images.data)
    plt.figure()