Я пытался создать сеть для генерации изображений чисел, имитирующих набор данных MNIST. Однако на выходе сеть выдает только шум, а не связное изображение.
Я пробовал экспериментировать с функциями потерь и оптимизаторами, но результаты те же. Я думаю, что это неправильное понимание того, как работают эти типы сетей, но мне все равно хотелось бы знать, в чем моя ошибка.
Вот код генератора изображений:
import numpy as np
import torch.utils
import torch.utils.data
import torch.utils.data.dataloader
from tqdm import tqdm
import torch
import torch.nn as nn #OOP
import torch.nn.functional as F #Functions (not oop based)
import torch.optim as optim
import matplotlib.pyplot as plt
from matplotlib import style
import torchvision
from torchvision import transforms, datasets
device = torch.device("cuda:0") #GPU
class Net(nn.Module):
def __init__(self):
super().__init__() #Super = nn.Module, inherit the methods and modules from __init__
self.fc1 = nn.Linear(10, 128)
self.fc2 = nn.Linear(128, 128)
self.fc3 = nn.Linear(128, 128)
self.fc4 = nn.Linear(128, 28*28)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = self.fc4(x)
return (F.softmax(x, dim=1))
net = Net().to(device)
#Data
# 1 hot vector, index represents the number i want it to generate
# Generate a batch of 10 images
# Pass these images through the Number_Recogniser
# Compare the outputs using mean square loss
# With the loss update the gradients
def Data():
return(np.random.randint(0, 10, size=64))
#Data sets
def DataSet(Data):
One_Hot = []
for data in Data:
Ones = [0] * 10
Ones[data] = 1
Ones = torch.Tensor(Ones)
Ones.view(-1, 10)
Ones.to(device)
One_Hot.append(Ones)
return(One_Hot)
EPOCHS = 3000 # 300 for 30000 images
# Generate the labels
# Generate the images from the labels
# Pass the images through the Recogniser
# Take the ouput as a vector
# Use the mean square loss
# etc...
#Load the Number Recogniser
Number_Recogniser = torch.jit.load("model.pth")
Number_Recogniser.eval()
optimizer = torch.optim.SGD(net.parameters(), lr=1e-3)
loss_fn = nn.CrossEntropyLoss()
for epoch in tqdm(range(EPOCHS)):
rand = Data()
dataset = DataSet(rand) #One hot vectors
for data in dataset: #Loops over the batch
y = data
y = y.view(-1, 10)
y = y.to(device)
X = net(y)
X = X.view(-1, 28*28)
X = X.to(device)
pred = Number_Recogniser(X)
pred = pred.view(-1, 10)
pred = pred.to(device)
loss = loss_fn(pred, y)
loss.backward()
optimizer.step()
optimizer.zero_grad()
#print(loss)
image = X.view(-1, 28, 28)
image = torch.Tensor.cpu(image)
image = image.detach().numpy()
plt.imshow(image[0]).cmap("gray")
plt.show()
Подробнее здесь: https://stackoverflow.com/questions/790 ... -of-images