Output image from a loading model

Mike2004: <p>I´m trying to loading a image, and then i get this error:  img=torch.view(img,(1,-1))</p>
<p>AttributeError: module ‘torch’ has no attribute ‘view’</p>
<p>This is the program to load the model:</p>
<p>import os<br>
import cv2<br>
import torch<br>
import torch.nn.functional as F<br>
import numpy as np<br>
from scipy.spatial import distance<br>
import torchvision<br>
import torchvision.datasets as dsets<br>
from torch import nn<br>
from torch.autograd import Variable<br>
from torch.utils.data import DataLoader<br>
from torchvision import transforms<br>
from torchvision.datasets import MNIST<br>
from torchvision.utils import save_image</p>
<p>if not os.path.exists(’./teste_novo’):<br>
os.mkdir(’./teste_novo’)</p>
<p>img=cv2.imread(".\bolinhas.png",0)<br>
img=img.astype(float)<br>
img=img/255<br>
img=torch.Tensor(img)<br>
img=img.unsqueeze(2)<br>
img=img.permute(2,0,1)<br>
img=img.unsqueeze(0)</p>
<p>class VAE(nn.Module):<br>
def <strong>init</strong>(self):<br>
super(VAE, self).<strong>init</strong>()</p>
<pre><code>    self.fc1 = nn.Linear(784, 400)
    self.fc21 = nn.Linear(400, 20)
    self.fc22 = nn.Linear(400, 20)
    self.fc3 = nn.Linear(20, 400)
    self.fc4 = nn.Linear(400, 784)

def encode(self, x):
    h1 = F.relu(self.fc1(x))
    return self.fc21(h1), self.fc22(h1)

def reparametrize(self, mu, logvar):
    std = logvar.mul(0.5).exp_()
    if torch.cuda.is_available():
        eps = torch.cuda.FloatTensor(std.size()).normal_()
    else:
        eps = torch.FloatTensor(std.size()).normal_()
    eps = Variable(eps)
    return eps.mul(std).add_(mu)

def decode(self, z):
    h3 = F.relu(self.fc3(z))
    return F.sigmoid(self.fc4(h3))

def forward(self, x):
    mu, logvar = self.encode(x)
    z = self.reparametrize(mu, logvar)
    return self.decode(z), mu, logvar
</code></pre>
<p>model = VAE().cuda()<br>
model.load_state_dict(torch.load(’./vae.pth’))<br>
img=torch.view(img,(1,-1))<br>
img = Variable(img)<br>
out=model(img)<br>
i=img.view(img.size(0), -1)<br>
o=out.view(out.size(0), -1)<br>
i=i.detach().cpu().numpy()<br>
o=o.detach().cpu().numpy()<br>
dt=distance.euclidean(o,i)<br>
print(dt)</p>
<p>And this is the model:</p>
<p>import torch<br>
import torchvision<br>
from torch import nn<br>
from torch import optim<br>
import torch.nn.functional as F<br>
from torch.autograd import Variable<br>
from torch.utils.data import DataLoader<br>
from torchvision import transforms<br>
from torchvision.utils import save_image<br>
from torchvision.datasets import MNIST<br>
import os</p>
<p>if not os.path.exists(’./var_autoencoder_out’):<br>
os.mkdir(’./var_autoencoder_out’)</p>
<p>if not os.path.exists(’./var_autoencoder_in’):<br>
os.mkdir(’./var_autoencoder_in’)</p>
<p>def to_img(x):<br>
x = x.view(x.size(0), 1, 28, 28)<br>
return x</p>
<p>num_epochs = 300<br>
batch_size = 251<br>
learning_rate = 1e-3</p>
<p>img_transform = transforms.Compose([<br>
transforms.ToTensor()<br>
])</p>
<p>dataset = MNIST(’./data’, transform=img_transform, download=True)<br>
dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)</p>
<p>class VAE(nn.Module):<br>
def <strong>init</strong>(self):<br>
super(VAE, self).<strong>init</strong>()</p>
<pre><code>    self.fc1 = nn.Linear(784, 400)
    self.fc21 = nn.Linear(400, 20)
    self.fc22 = nn.Linear(400, 20)
    self.fc3 = nn.Linear(20, 400)
    self.fc4 = nn.Linear(400, 784)

def encode(self, x):
    h1 = F.relu(self.fc1(x))
    return self.fc21(h1), self.fc22(h1)

def reparametrize(self, mu, logvar):
    std = logvar.mul(0.5).exp_()
    if torch.cuda.is_available():
        eps = torch.cuda.FloatTensor(std.size()).normal_()
    else:
        eps = torch.FloatTensor(std.size()).normal_()
    eps = Variable(eps)
    return eps.mul(std).add_(mu)

def decode(self, z):
    h3 = F.relu(self.fc3(z))
    return F.sigmoid(self.fc4(h3))

def forward(self, x):
    mu, logvar = self.encode(x)
    z = self.reparametrize(mu, logvar)
    return self.decode(z), mu, logvar
</code></pre>
<p>model = VAE()<br>
if torch.cuda.is_available():<br>
model.cuda()</p>
<p>reconstruction_function = nn.MSELoss(size_average=False)</p>
<p>def loss_function(recon_x, x, mu, logvar):<br>
BCE = reconstruction_function(recon_x, x)<br>
KLD_element = mu.pow(2).add_(logvar.exp()).mul_(-1).add_(1).add_(logvar)<br>
KLD = torch.sum(KLD_element).mul_(-0.5)<br>
return BCE + KLD</p>
<p>optimizer = optim.Adam(model.parameters(), lr=1e-3)</p>
<p>for epoch in range(num_epochs):<br>
model.train()<br>
train_loss = 0<br>
for batch_idx, data in enumerate(dataloader):<br>
img, _ = data<br>
img = img.view(img.size(0), -1)<br>
img = Variable(img)<br>
nova=to_img(img)<br>
save_image(nova, ‘./var_autoencoder_in/image_{}.png’.format(epoch))<br>
if torch.cuda.is_available():<br>
img = img.cuda()<br>
optimizer.zero_grad()<br>
recon_batch, mu, logvar = model(img)<br>
loss = loss_function(recon_batch, img, mu, logvar)<br>
loss.backward()<br>
train_loss += loss.data<br>
optimizer.step()<br>
if batch_idx % 100 == 0:<br>
print(‘Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}’.format(<br>
epoch,<br>
batch_idx * len(img),<br>
len(dataloader.dataset), 100. * batch_idx / len(dataloader),<br>
loss.data / len(img)))</p>
<pre><code>print('====&gt; Epoch: {} Average loss: {:.4f}'.format(
    epoch, train_loss / len(dataloader.dataset)))
if epoch % 1 == 0:
    save = to_img(recon_batch.cpu().data)
    save_image(save, './var_autoencoder_out/image_{}.png'.format(epoch))
</code></pre>
<p>torch.save(model.state_dict(), ‘./vae.pth’)</p>

ptrblck: <p><code>view</code> is a tensor method, so you should call <code>img.view</code> instead of <code>torch.view(img,...)</code>.</p>

ptrblck: <p>Your model returns three tensors in its <code>forward</code> method:</p>
<pre><code class="lang-python">return self.decode(z), mu, logvar
</code></pre>
<p>Assuming you would like to visualize the first returned tensor, this should work:</p>
<pre><code class="lang-python">o = out[0].view(out[0].size(0), -1)
</code></pre>