instruction
stringlengths 13
150
| input
stringlengths 36
29.1k
| output
stringlengths 31
29.5k
| source
stringlengths 45
45
|
---|---|---|---|
Pytorch: Image label | I am working on an image classifier with 31 classes(Office dataset). There is one folder for each of the classes. I have a python script written using PyTorch that loads the dataset using datasets.ImageFolder and assigns a label to each image and then trains. Here is my code snippet for loading data:
from torchvision import datasets, transforms
import torch
def load_training(root_path, dir, batch_size, kwargs):
transform = transforms.Compose(
[transforms.Resize([256, 256]),
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor()])
data = datasets.ImageFolder(root=root_path + dir, transform=transform)
train_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=True, drop_last=True, **kwargs)
return train_loader
The code takes each folder, assigns the same label to all images in that folder. Is there any way to find which label is assigned to which image/image folder?
| The class ImageFolder has an attribute class_to_idx which is a dictionary mapping the name of the class to the index (label). So, you can access the classes with data.classes and for each class get the label with data.class_to_idx.
For reference: https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py
| https://stackoverflow.com/questions/51906144/ |
Is there a mistake in pytorch tutorial? | The official pytorch tutorial (https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html#gradients) indicates that out.backward() and out.backward(torch.tensor(1)) are equivalent. But this does not seem to be the case.
import torch
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
# option 1
out.backward()
# option 2. Replace! do not leave one after the other
# out.backward(torch.tensor(1))
print(x.grad)
Using option 2 (commented out) results in an error.
Note: do not leave two backward calls. Replace option 1 with 2.
Is the tutorial out of date? What is the purpose of the argument?
Update
If I use out.backward(torch.tensor(1)) as the tutorial says, I get:
E RuntimeError: invalid gradient at index 0 - expected type torch.FloatTensor but got torch.LongTensor
../../../anaconda3/envs/phd/lib/python3.6/site-packages/torch/autograd/__init__.py:90: RuntimeError
I tried also using out.backward(torch.Tensor(1)) and I get instead:
E RuntimeError: invalid gradient at index 0 - expected shape [] but got [1]
../../../anaconda3/envs/phd/lib/python3.6/site-packages/torch/autograd/__init__.py:90: RuntimeError
| You need to use dtype=torch.float:
import torch
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
# option 1
out.backward()
print(x.grad)
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
z = y * y * 3
out = z.mean()
#option 2. Replace! do not leave one after the other
out.backward(torch.tensor(1, dtype=torch.float))
print(x.grad)
Output:
tensor([[ 4.5000, 4.5000],
[ 4.5000, 4.5000]])
tensor([[ 4.5000, 4.5000],
[ 4.5000, 4.5000]])
| https://stackoverflow.com/questions/51909270/ |
PyTorch: Image dimension issue | I am working on an image classifier dataset. There are 31 classes in my dataset and there is a folder for each class. For training, I am loading data in the following manner:
from torchvision import datasets, transforms
import torch
def load_training(root_path, dir, batch_size, kwargs):
transform = transforms.Compose(
[transforms.Resize([256, 256]),
transforms.RandomCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor()])
data = datasets.ImageFolder(root=root_path + dir, transform=transform)
train_loader = torch.utils.data.DataLoader(data, batch_size=batch_size, shuffle=False, drop_last=True, **kwargs)
return train_loader
Now for a batch size 32, each batch dim are : [32,3,224,224]. I know Pytorch uses PIL for loading images. But when I'm trying to load images from a list named images of size 32 using PIL using the following code snippet:
for i in images:
im = Image.open(root_dir + dir + i)
im = im.convert('RGB')
im.load()
im = im.resize((224, 224))
im = np.asarray( im, dtype="int32" )
print(im.shape)
temp_im_2 = torch.from_numpy(np.array(temp_im)).float()
It says im.shape is (32,224,224,3). What am I doing wrong? What should I do to get the batches to be of the same shape in both cases say [32,3,224,224]?
| How about just swapping axes? Like im.transpose(0, 3, 1, 2) if im has four dimensions. However, im.shape should return (224, 224, 3) as you've loaded only one image, so that im.transpose(2, 0, 1) should give you the image with the channels in the first dimension which you can then stack together to form a batch.
| https://stackoverflow.com/questions/51911447/ |
What is the difference between torch.tensor and torch.Tensor? | Since version 0.4.0, it is possible to use torch.tensor and torch.Tensor
What is the difference? What was the reasoning for providing these two very similar and confusing alternatives?
| In PyTorch torch.Tensor is the main tensor class. So all tensors are just instances of torch.Tensor.
When you call torch.Tensor() you will get an empty tensor without any data.
In contrast torch.tensor is a function which returns a tensor. In the documentation it says:
torch.tensor(data, dtype=None, device=None, requires_grad=False) → Tensor
Constructs a tensor with data.
This also explains why it is no problem creating an empty tensor instance of `torch.Tensor` without `data` by calling:
tensor_without_data = torch.Tensor()
But on the other side:
tensor_without_data = torch.tensor()
Will lead to an error:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-ebc3ceaa76d2> in <module>()
----> 1 torch.tensor()
TypeError: tensor() missing 1 required positional arguments: "data"
But in general there is no reason to choose `torch.Tensor` over `torch.tensor`. Also `torch.Tensor` lacks a docstring.
Similar behaviour for creating a tensor without data like with: torch.Tensor() can be achieved using:
torch.tensor(())
Output:
tensor([])
| https://stackoverflow.com/questions/51911749/ |
Multiple matrix multiplication loses weight updates | When in forward method I only do one set of torch.add(torch.bmm(x, exp_w), self.b) then my model is back propagating correctly. When I add another layer - torch.add(torch.bmm(out, exp_w2), self.b2) - then the gradients are not updated and the model isn't learning. If I change the activation function from nn.Sigmoid to nn.ReLU then it works with two layers.
Been thinking about this a day now, and not figuring out why it's not working with nn.Sigmoid.
I've tried different learning rates, Loss functions and optimization functions, but no combination seems to work. When I add the weights together before and after training they are the same.
Code:
class MyModel(nn.Module):
def __init__(self, input_dim, output_dim):
torch.manual_seed(1)
super(MyModel, self).__init__()
self.input_dim = input_dim
self.output_dim = output_dim
hidden_1_dimentsions = 20
self.w = torch.nn.Parameter(torch.empty(input_dim, hidden_1_dimentsions).uniform_(0, 1))
self.b = torch.nn.Parameter(torch.empty(hidden_1_dimentsions).uniform_(0, 1))
self.w2 = torch.nn.Parameter(torch.empty(hidden_1_dimentsions, output_dim).uniform_(0, 1))
self.b2 = torch.nn.Parameter(torch.empty(output_dim).uniform_(0, 1))
def activation(self):
return torch.nn.Sigmoid()
def forward(self, x):
x = x.view((x.shape[0], 1, self.input_dim))
exp_w = self.w.expand(x.shape[0], self.w.size(0), self.w.size(1))
out = torch.add(torch.bmm(x, exp_w), self.b)
exp_w2 = self.w2.expand(out.shape[0], self.w2.size(0), self.w2.size(1))
out = torch.add(torch.bmm(out, exp_w2), self.b2)
out = self.activation()(out)
return out.view(x.shape[0])
| Besides loss functions, activation functions and learning rates, your parameter initialisation is also important. I suggest you to take a look at Xavier initialisation: https://pytorch.org/docs/stable/nn.html#torch.nn.init.xavier_uniform_
Furthermore, for a wide range of problems and network architectures Batch Normalization, which ensures that your activations have zero mean and standard deviation, helps: https://pytorch.org/docs/stable/nn.html#torch.nn.BatchNorm1d
If you are interested to know more about the reason for this, it's mostly due to the vanishing gradient problem, which means that your gradients get so small that your weights don't get updated. It's so common that it has its own page on Wikipedia: https://en.wikipedia.org/wiki/Vanishing_gradient_problem
| https://stackoverflow.com/questions/51919621/ |
Correct way to create Pytorch dataset that returns sequence of data for RNN? | I am attempting to train an RNN on time series data, and while there are plenty of tutorials out there on how to build a RNN model I am having some trouble with building the dataloader object for this task. The data is all going to be the same length, so no need for padding as well. The approach I have taken so far is to return a range of data in the getitem function on the dataset class and define the length as
len(data) - seq_len + 1
, however I feel that this is a bit "hacky" and that there should be a more proper way to do this. This method seems confusing and I feel that this would cause problems if collaborating with a group. More specifically, I think that somehow overriding the sampler function in the Pytorch Dataset constructor is the correct way, but I am having trouble understanding how to implement that. Below is the current dataset class I have built, can anyone point me in the right direction with how to fix it? Thank you in advance.
class CustomDataset(Dataset):
def __init__(self, df, cats, y, seq_l):
self.n, self.seq_l = len(df), seq_l
self.cats = np.array(np.stack([c.values for n,c in df[cats].items()], 1).astype(np.int64))
self.conts = np.array(np.stack([c.values for n,c in df[[i for i in df.columns if i not in cats]].items()], 1).astype(np.float32))
self.y = np.array(y)
def __len__(self): return len(self.y) - self.seq_l + 1
def __getitem__(self, idx):
return [
(torch.from_numpy(self.cats[idx:idx+self.seq_l]),
torch.from_numpy(self.conts[idx:idx+self.seq_l])),
self.y[idx+self.seq_l-1]
]
| If I understood correctly you have time series data and you want to crate batches of data with the same length by sampling from it?
I think you can use Dataset for returning just one sample of data as it was initially intended by the PyTorch developers. You can stack them in the batch with your own _collate_fn function and pass it to the DataLoader class (_collate_fn is a callable which takes a list of samples and returns a batch, usually, for example, padding is done there). So you would not have a dependency of length (=batch size in your dataset class). I assume you want to preserve sequential order of your samples when you form a batch (given that you work with time series), you can write your own Sampler class (or use SequentialSampler already available in PyTorch).
As a result, you will decouple your sample representation, forming them in a batch (_collate_fn in DataLoader) and sampling (Sampler class). Hope this helps.
| https://stackoverflow.com/questions/51939022/ |
cifar100 dataset consists of repeated image? | I randomly browsed some images in cifar100, and found many images like this:
.
Anything went wrong? Or cifar100 indeed consist of such images?
| I think you did not load in the images correctly. Take a look at loading an image from cifar-10 dataset to see that others also have those problems. The correct way to reshape one of those cifar images is as follows:
single_img_reshaped = np.transpose(np.reshape(single_img,(3, 32,32)), (1,2,0))
| https://stackoverflow.com/questions/51940967/ |
What is this attribute syntax in Python? | I am current following a tutorial in Pytorch and there is this expression:
grad_h[h < 0] = 0
How does this syntax work and what does it do?
| It means replace with zeros all the values in grad_h where its corresponding h is negative.
So it is implementing some kind of mask, to keep the gradient values only when h is negative
suppose that grad_h and h have the same shape.
grad_h.shape == h.shape
when you do h < 0 you obtain an array of booleans of the same shape that is set to True if h[i] < 0 for each i.
So then you apply this mask to do slicing on grad_h and finally you set all the sliced elements to zero
| https://stackoverflow.com/questions/51943308/ |
How can I get data for a quiver plot in torch? | I have some function z(x, y) and I would like to generate a quiver plot (a 2D plot of the gradients). Something like this:
In order to do it, I have to run gradient over a linear mesh and adjust data to the format that matplotlib.quiver does.
A naive way is to iterate forward and backward in a loop:
for i in range(10):
for j in range(10):
x = torch.tensor(1. * i, requires_grad=True)
y = torch.tensor(1. * j, requires_grad=True)
z = x ** 2 + y ** 2
z.backward()
print(x.grad, y.grad)
This is obviously very inefficient. There are some examples on how to generate a linear mesh from x, y but I would need later change the mesh back to the format of the forward formula, get vectors of gradient and put them back, etc..
A simple example in numpy would be:
import matplotlib.pyplot as plt
n = 25
x_range = np.linspace(-25, 25, n)
y_range = np.linspace(-25, 25, n)
X, Y = np.meshgrid(x_range, y_range)
Z = X**2 + Y**2
U, V = 2*X, 2*Y
plt.quiver(X, Y, U, V, Z, alpha=.9)
What would be the standard way of doing this with pytorch? Are there some simple examples available?
| You can compute gradients of non-scalars by passing torch.Tensors of ones.
import matplotlib.pyplot as plt
import torch
# create meshgrid
n = 25
a = torch.linspace(-25, 25, n)
b = torch.linspace(-25, 25, n)
x = a.repeat(n)
y = b.repeat(n, 1).t().contiguous().view(-1)
x.requires_grad = True
y.requires_grad=True
z = x**2 + y**2
# this line will compute the gradients
torch.autograd.backward([z], [torch.ones(x.size()), torch.ones(y.size())])
# detach to plot
plt.quiver(x.detach(), y.detach(), x.grad, y.grad, z.detach(), alpha=.9)
plt.show()
If you need to do this repeatedly you need to zero the gradients (set x.grad = y.grad = None).
| https://stackoverflow.com/questions/51946750/ |
Making a prediction from a trained convolution network | Here is my convolution net that creates training data , then trains on this data using a single convolution with relu activation :
train_dataset = []
mu, sigma = 0, 0.1 # mean and standard deviation
num_instances = 10
for i in range(num_instances) :
image = []
image_x = np.random.normal(mu, sigma, 1000).reshape((1 , 100, 10))
train_dataset.append(image_x)
mu, sigma = 100, 0.80 # mean and standard deviation
for i in range(num_instances) :
image = []
image_x = np.random.normal(mu, sigma, 1000).reshape((1 , 100, 10))
train_dataset.append(image_x)
labels_1 = [1 for i in range(num_instances)]
labels_0 = [0 for i in range(num_instances)]
labels = labels_1 + labels_0
print(labels)
x2 = torch.tensor(train_dataset).float()
y2 = torch.tensor(labels).long()
my_train2 = data_utils.TensorDataset(x2, y2)
train_loader2 = data_utils.DataLoader(my_train2, batch_size=batch_size_value, shuffle=False)
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
# Device configuration
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
# device = 'cpu'
# Hyper parameters
num_epochs = 50
num_classes = 2
batch_size = 5
learning_rate = 0.001
# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
def __init__(self, num_classes=1):
super(ConvNet, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Linear(32*25*2, num_classes)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = out.reshape(out.size(0), -1)
out = self.fc(out)
return out
model = ConvNet(num_classes).to(device)
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
total_step = len(train_loader2)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader2):
images = images.to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i % 10) == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
To make a single prediction I use :
model(x2[10].unsqueeze_(0).cuda())
Which outputs :
tensor([[ 4.4880, -4.3128]], device='cuda:0')
Should this not return an image tensor of shape (100,10) of the prediction ?
Update : In order to perform a prediction I use :
torch.argmax(model(x2[2].unsqueeze_(0).cuda()), dim=1)
src : https://discuss.pytorch.org/t/argmax-with-pytorch/1528/11
torch.argmax in this context returns the position of the value that maximises the prediction.
| As noted by Koustav your net is not "fully convolutional": although you have two nn.Conv2d layers, you still have a "fully-connected" (aka nn.Linear) layer on top, which outputs only 2 dimensional (num_classes) output tensor.
More specifically, your net expects a 1x100x10 input (single channel, 100 by 10 pixels image).
After self.layer1 you have a 16x50x5 tensor (16 channels from the convolution, spatial dimensions reduced by max pooling layer).
After self.layer2 you have a 32x25x2 tensor (32 channels from the convolution, spatial dimensions reduced by another max pooling layer).
Finally, your fully connected self.fc nn.Linear layer takes the entire 32*25*2 dimensional input tensor and produces a num_classes output from the entire input.
| https://stackoverflow.com/questions/51965539/ |
Implementing Curriculum Dropout in Pytorch | Is there anyone who can help me implement Curriculum Dropout by Pytorch. Thanks in advance, and any kind of help will be appreciable.
I want to do some experiments of Curriculum Dropout in Pytorch. Curriculum Dropout tries to use a time scheduling for adjusting the dropout rate in the neural networks. The related paper can be downloaded from here.
The source code in python can be found here
| I took a quick look at the paper and it seems like the main idea is to use a scheduled dropout rate instead of a fixed dropout rate.
Torch already has a Dropout module: torch.nn.modules.dropout.Dropout.
For your custom neural net using a Dropout module dropout, you can schedule the dropout rate simply by modifying dropout.p between optimization steps.
| https://stackoverflow.com/questions/51977025/ |
TypeError: Cannot handle the data type in PIL Image | I have a Pytorch tensor of size (4,3,224,224). When I am trying to convert the first tensor into an Image object, it says:
TypeError: Cannot handle this data type
I ran the following command:
img = Image.fromarray(data[0][i].numpy().astype(np.uint8))
where data is the Pytorch tensor
I tried other solutions but couldn't find any solution.
Please suggest !!
| You are trying to convert 3x224x224 np.array into an image, but PIL.Image expects its images to be of shape 224x224x3, threfore you get an error.
If you transpose your tensor so that the channel dimension will be the last (rather than the first), you should have no problem
img = Image.fromarray(data[0][i].transpose(0,2).numpy().astype(np.uint8))
| https://stackoverflow.com/questions/51979554/ |
PyTorch element-wise filter layer | Hi, I want to add element-wise multiplication layer to duplicate the input to multi-channels like this figure. (So, the input size M x N and multiplication filter size M x N is same), as illustrated in this figure
I want to add custom initialization value to filter, and also want them to get gradient while training. However, I can't find element-wise filter layer in PyTorch. Can I make it? Or is it just impossible in PyTorch?
| In pytorch you can always implement your own layers, by making them subclasses of nn.Module. You can also have trainable parameters in your layer, by using nn.Parameter.
Possible implementation of such layer might look like
import torch
from torch import nn
class TrainableEltwiseLayer(nn.Module)
def __init__(self, n, h, w):
super(TrainableEltwiseLayer, self).__init__()
self.weights = nn.Parameter(torch.Tensor(1, n, h, w)) # define the trainable parameter
def forward(self, x):
# assuming x is of size b-1-h-w
return x * self.weights # element-wise multiplication
You still need to worry about initializing the weights. look into nn.init on ways to init weights. Usually one init the weights of all the net prior to training and prior to loading any stored model (so partially trained models can override random init). Something like
model = mymodel(*args, **kwargs) # instantiate a model
for m in model.modules():
if isinstance(m, nn.Conv2d):
nn.init.normal_(m.weights.data) # init for conv layers
if isinstance(m, TrainableEltwiseLayer):
nn.init.constant_(m.weights.data, 1) # init your weights here...
| https://stackoverflow.com/questions/51980654/ |
Calculating Euclidian Norm in Pytorch.. Trouble understanding an implementation | I've seen another StackOverflow thread talking about the various implementations for calculating the Euclidian norm and I'm having trouble seeing why/how a particular implementation works.
The code is found in an implementation of the MMD metric: https://github.com/josipd/torch-two-sample/blob/master/torch_two_sample/statistics_diff.py
Here is some beginning boilerplate:
import torch
sample_1, sample_2 = torch.ones((10,2)), torch.zeros((10,2))
Then the next part is where we pick up from the code above.. I'm unsure why the samples are being concatenated together..
sample_12 = torch.cat((sample_1, sample_2), 0)
distances = pdist(sample_12, sample_12, norm=2)
and are then passed to the pdist function:
def pdist(sample_1, sample_2, norm=2, eps=1e-5):
r"""Compute the matrix of all squared pairwise distances.
Arguments
---------
sample_1 : torch.Tensor or Variable
The first sample, should be of shape ``(n_1, d)``.
sample_2 : torch.Tensor or Variable
The second sample, should be of shape ``(n_2, d)``.
norm : float
The l_p norm to be used.
Returns
-------
torch.Tensor or Variable
Matrix of shape (n_1, n_2). The [i, j]-th entry is equal to
``|| sample_1[i, :] - sample_2[j, :] ||_p``."""
here we get to the meat of the calculation
n_1, n_2 = sample_1.size(0), sample_2.size(0)
norm = float(norm)
if norm == 2.:
norms_1 = torch.sum(sample_1**2, dim=1, keepdim=True)
norms_2 = torch.sum(sample_2**2, dim=1, keepdim=True)
norms = (norms_1.expand(n_1, n_2) +
norms_2.transpose(0, 1).expand(n_1, n_2))
distances_squared = norms - 2 * sample_1.mm(sample_2.t())
return torch.sqrt(eps + torch.abs(distances_squared))
I am at a loss for why the euclidian norm would be calculated this way. Any insight would be greatly appreciated
| Let's walk through this block of code step by step. The definition of Euclidean distance, i.e., L2 norm is
Let's consider the simplest case. We have two samples,
Sample a has two vectors [a00, a01] and [a10, a11]. Same for sample b. Let first calculate the norm
n1, n2 = a.size(0), b.size(0) # here both n1 and n2 have the value 2
norm1 = torch.sum(a**2, dim=1)
norm2 = torch.sum(b**2, dim=1)
Now we get
Next, we have norms_1.expand(n_1, n_2) and norms_2.transpose(0, 1).expand(n_1, n_2)
Note that b is transposed. The sum of the two gives norm
sample_1.mm(sample_2.t()), that's the multiplication of the two matrix.
Therefore, after the operation
distances_squared = norms - 2 * sample_1.mm(sample_2.t())
you get
In the end, the last step is taking the square root of every element in the matrix.
| https://stackoverflow.com/questions/51986758/ |
Pytorch DataLoader memory is not released | I'd like to implement SRGAN on pythorch on google collaboratory, but memory of DataLoader seems to be released, so if you turn epoch, memory error will occur.
It would be greatly appreciated if you tell me how to do it in order to free up memory per batch.
This is the github link of the code
https://github.com/pacifinapacific/Hello-World/blob/master/Untitled0.ipynb
It turned 48 and a memory error occurred on 1 echoch,
If you set the batch size to 1/6 of 8, you will get an error at about 6 epoch.
I am reading high resolution and low resolution images with the following code. Extend ImageFolder
but For example, even if an error occurs when learning is executed, the memory of the GPU is not released
class DownSizePairImageFolder(ImageFolder):
def __init__(self, root, transform=None, large_size=256, small_size=64, **kwds):
super().__init__(root, transform=transform, **kwds)
self.large_resizer = transforms.Scale(large_size)
self.small_resizer = transforms.Scale(small_size)
def __getitem__(self, index):
path, _ = self.imgs[index]
img = self.loader(path)
large_img = self.large_resizer(img)
small_img = self.small_resizer(img)
if self.transform is not None:
large_img = self.transform(large_img)
small_img = self.transform(small_img)
return small_img, large_img
train_data = DownSizePairImageFolder('./lfw-deepfunneled/train', transform=transforms.ToTensor())
test_data = DownSizePairImageFolder('./lfw-deepfunneled/test', transform=transforms.ToTensor())
batch_size = 8
train_loader = DataLoader(train_data, batch_size, shuffle=True)
test_loader = DataLoader(test_data, batch_size, shuffle=False)
| Pytorch builds a computational graph each time you propagate through your model. This graph is normally retained until the output variable G_loss is out of scope, e.g. when a new iteration through the loop starts.
However, you append this loss to a list. Hence, the variable is still known to python and the graph not freed. You can use .detach() to detach the variable from the current graph (which is better than .clone() which I proposed before as it will also copy the data of the tensor).
As a little side node: In your train() function, you return D_loss,G_loss in the for loop, not after it; so you always only use the first batch.
| https://stackoverflow.com/questions/52015010/ |
Can nvidia-docker be run without a GPU? | The official PyTorch Docker image is based on nvidia/cuda, which is able to run on Docker CE, without any GPU. It can also run on nvidia-docker, I presume with CUDA support enabled. Is it possible to run nvidia-docker itself on an x86 CPU, without any GPU? Is there a way to build a single Docker image that takes advantage of CUDA support when it is available (e.g. when running inside nvidia-docker) and uses the CPU otherwise? What happens when you use torch.cuda from inside Docker CE? What exactly is the difference between Docker CE and why can't nvidia-docker be merged into Docker CE?
| nvidia-docker is a shortcut for docker --runtime nvidia. I do hope they merge it one day, but for now it's a 3rd party runtime. They explain what it is and what it does on their GitHub page.
A modified version of runc adding a custom pre-start hook to all containers.
If environment variable NVIDIA_VISIBLE_DEVICES is set in the OCI spec, the hook will configure GPU access for the container by leveraging nvidia-container-cli from project libnvidia-container.
Nothing stops you from running images meant for nvidia-docker with normal docker. They work just fine but if you run something in them that requires the GPU, that will fail.
I don't think you can run nvidia-docker on a machine without a GPU. It won't be able to find the CUDA files it's looking for and will error out.
To create an image that can run on both docker and nvidia-docker, your program inside it needs to be able to know where it's running. I am not sure if there's an official way, but you can try one of the following:
Check if nvidia-smi is available
Check if the directory specified in $CUDA_LIB_PATH exists
Check if your program can load the CUDA libraries successfully, and if it can't just fallback
| https://stackoverflow.com/questions/52030952/ |
How to calculate kernel dimensions from original image dimensions? | https://github.com/kuangliu/pytorch-cifar/blob/master/models/resnet.py
From reading https://www.cs.toronto.edu/~kriz/cifar.html the cifar dataset consists of images each with 32x32 dimension.
My understanding of code :
self.conv1 = nn.Conv2d(3, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5, 120)
Is :
self.conv1 = nn.Conv2d(3, 6, 5) # 3 channels in, 6 channels out , kernel size of 5
self.conv2 = nn.Conv2d(6, 16, 5) # 6 channels in, 16 channels out , kernel size of 5
self.fc1 = nn.Linear(16*5*5, 120) # 16*5*5 in features , 120 ouot feature
From resnet.py the following :
self.fc1 = nn.Linear(16*5*5, 120)
From http://cs231n.github.io/convolutional-networks/ the following is stated :
Summary. To summarize, the Conv Layer:
Accepts a volume of size W1×H1×D1 Requires four hyperparameters:
Number of filters K, their spatial extent F, the stride S, the amount
of zero padding P. Produces a volume of size W2×H2×D2 where:
W2=(W1−F+2P)/S+1 H2=(H1−F+2P)/S+1 (i.e. width and height are computed
equally by symmetry) D2=K With parameter sharing, it introduces F⋅F⋅D1
weights per filter, for a total of (F⋅F⋅D1)⋅K weights and K biases. In
the output volume, the d-th depth slice (of size W2×H2) is the result
of performing a valid convolution of the d-th filter over the input
volume with a stride of S, and then offset by d-th bias.
From this I'm attempting to understand how the training image dimension 32x32 (1024 pixels) is transformed to feature map (16*5*5 -> 400) as aprt of nn.Linear(16*5*5, 120)
From https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d can see default stride is 1 and padding is 0.
What are steps to arrive at 16*5*5 from image dimension of 32*32 and can 16*5*5 be derived from above steps ?
From above steps how to calculate spatial extent ?
Update :
Source code :
'''LeNet in PyTorch.'''
import torch.nn as nn
import torch.nn.functional as F
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
out = F.relu(self.conv1(x))
out = F.max_pool2d(out, 2)
out = F.relu(self.conv2(out))
out = F.max_pool2d(out, 2)
out = out.view(out.size(0), -1)
out = F.relu(self.fc1(out))
out = F.relu(self.fc2(out))
out = self.fc3(out)
return out
Taken from https://github.com/kuangliu/pytorch-cifar/blob/master/models/lenet.py
My understanding is that the convolution operation is applied to the image data per kernel. So if 5 kernels are set then 5 convolutions are applied to the data which generates a 5 dimensional image representation.
| You do not provide enough information in your question (see my comment).
However, if I have to guess then you have two pooling layers (with stride 2) in between your convolution layers:
input size 32x32 (3 channels)
conv1 output size 28x28 (6 channels): conv with no padding and kernel size 5, reduces input size by 4.
Pooling layer with stride 2, output size 14x14 (6 channels).
conv2 output size 10x10 (16 channels)
Another pooling layer with stride 2, output size 5x5 (16 channels)
A fully connected layer (nn.Linear) connecting all 5x5x16 inputs to all 120 outputs.
A more thorough guide for estimating the receptive field can be found here.
| https://stackoverflow.com/questions/52044361/ |
'None' gradients in pytorch | I am trying to implement a simple MDN that predicts the parameters of a distribution over a target variable instead of a point value, and then assigns probabilities to discrete bins of the point value. Narrowing down the issue, the code from which the 'None' springs is:
import torch
# params
tte_bins = np.linspace(
start=0,
stop=399,
num=400,
dtype='float32'
).reshape(1, 1, -1)
bins = torch.tensor(tte_bins, dtype=torch.float32)
x_train = np.random.randn(1, 1024, 3)
y_labels = np.random.randint(low=0, high=399, size=(1, 1024))
y_train = np.eye(400)[y_labels]
# data
in_train = torch.tensor(x_train[0:1, :, :], dtype=torch.float)
in_train = (in_train - torch.mean(in_train)) / torch.std(in_train)
out_train = torch.tensor(y_train[0:1, :, :], dtype=torch.float)
# model
linear = torch.nn.Linear(in_features=3, out_features=2)
lin = linear(in_train)
preds = torch.exp(lin)
# intermediate values
alpha = torch.clamp(preds[0:1, :, 0:1], 0, 500)
beta = torch.clamp(preds[0:1, :, 1:2], 0, 100)
# probs
p1 = torch.exp(-torch.pow(bins / alpha, beta))
p2 = torch.exp(-torch.pow((bins + 1.0) / alpha, beta))
probs = p1 - p2
# loss
loss = torch.mean(torch.pow(out_train - probs, 2))
# gradients
loss.backward()
for p in linear.parameters():
print(p.grad, 'gradient')
in_train has shape: [1, 1024, 3], out_train has shape: [1, 1024, 400], bins has shape: [1, 1, 400]. All the broadcasting etc.. appears find, the resulting matrices (like alpha/beta/loss) are the right shape and have the right values - there's simply no gradients
edit: added loss.backward() and x_train/y_train, now I have nans
| You simply forgot to compute the gradients. While you calculate the loss, you never tell pytorch with respect to which function it should calculate the gradients.
Simply adding
loss.backward()
to your code should fix the problem.
Additionally, in your code some intermediate results like alpha are sometimes zero but are in a denominator when computing the gradient. This will lead to the nan results you observed.
| https://stackoverflow.com/questions/52067784/ |
How can I only update some specific tensors in network with pytorch? | For instance, I want to only update all cnn weights in Resnet in the first 10 epochs and freeze the others.
And from 11th epoch, I wanna change to update the whole model.
How can I achieve the goal?
| You can set the learning rate (and some other meta-parameters) per parameters group. You only need to group your parameters according to your needs.
For example, setting different learning rate for conv layers:
import torch
import itertools
from torch import nn
conv_params = itertools.chain.from_iterable([m.parameters() for m in model.children()
if isinstance(m, nn.Conv2d)])
other_params = itertools.chain.from_iterable([m.parameters() for m in model.children()
if not isinstance(m, nn.Conv2d)])
optimizer = torch.optim.SGD([{'params': other_params},
{'params': conv_params, 'lr': 0}], # set init lr to 0
lr=lr_for_model)
You can later access the optimizer param_groups and modify the learning rate.
See per-parameter options for more information.
| https://stackoverflow.com/questions/52069377/ |
Cannot convert list to array: ValueError: only one element tensors can be converted to Python scalars | I'm currently working with the PyTorch framework and trying to understand foreign code. I got an indices issue and wanted to print the shape of a list.
The only way of doing so (as far as Google tells me) is to convert the list into a numpy array and then getting the shape with numpy.ndarray.shape().
But trying to convert my list into an array, I got a ValueError: only one element tensors can be converted to Python scalars.
My List is a converted PyTorch Tensor (list(pytorchTensor)) and looks somewhat like this:
[
tensor([[-0.2781, -0.2567, -0.2353, ..., -0.9640, -0.9855, -1.0069],
[-0.2781, -0.2567, -0.2353, ..., -1.0069, -1.0283, -1.0927],
[-0.2567, -0.2567, -0.2138, ..., -1.0712, -1.1141, -1.1784],
...,
[-0.6640, -0.6425, -0.6211, ..., -1.0712, -1.1141, -1.0927],
[-0.6640, -0.6425, -0.5997, ..., -0.9426, -0.9640, -0.9640],
[-0.6640, -0.6425, -0.5997, ..., -0.9640, -0.9426, -0.9426]]),
tensor([[-0.0769, -0.0980, -0.0769, ..., -0.9388, -0.9598, -0.9808],
[-0.0559, -0.0769, -0.0980, ..., -0.9598, -1.0018, -1.0228],
[-0.0559, -0.0769, -0.0769, ..., -1.0228, -1.0439, -1.0859],
...,
[-0.4973, -0.4973, -0.4973, ..., -1.0018, -1.0439, -1.0228],
[-0.4973, -0.4973, -0.4973, ..., -0.8757, -0.9177, -0.9177],
[-0.4973, -0.4973, -0.4973, ..., -0.9177, -0.8967, -0.8967]]),
tensor([[-0.1313, -0.1313, -0.1100, ..., -0.8115, -0.8328, -0.8753],
[-0.1313, -0.1525, -0.1313, ..., -0.8541, -0.8966, -0.9391],
[-0.1100, -0.1313, -0.1100, ..., -0.9391, -0.9816, -1.0666],
...,
[-0.4502, -0.4714, -0.4502, ..., -0.8966, -0.8966, -0.8966],
[-0.4502, -0.4714, -0.4502, ..., -0.8115, -0.8115, -0.7903],
[-0.4502, -0.4714, -0.4502, ..., -0.8115, -0.7690, -0.7690]]),
]
Is there a way of getting the shape of that list without converting it into a numpy array?
| It seems like you have a list of tensors. For each tensor you can see its size() (no need to convert to list/numpy). If you insist, you can convert a tensor to numpy array using numpy():
Return a list of tensor shapes:
>> [t.size() for t in my_list_of_tensors]
Returns a list of numpy arrays:
>> [t.numpy() for t in my_list_of_tensors]
In terms of performance, it is always best to avoid casting of tensors into numpy arrays, as it may incur sync of device/host memory. If you only need to check the shape of a tensor, use size() function.
| https://stackoverflow.com/questions/52074153/ |
pytorch - use device inside 'with statement' | Is there a way of running pytorch inside the context of a specific (GPU) device (without having to specify the device for each new tensor, such as the .to option)?
Something like an equivalent of the tensorflow with tf.device('/device:GPU:0'):..
It seems that the default device is the cpu (unless I'm doing it wrong):
with torch.cuda.device('0'):
a = torch.zeros(1)
print(a.device)
>>> cpu
| Unfortunately in the current implementation the with-device statement doesn't work this way, it can just be used to switch between cuda devices.
You still will have to use the device parameter to specify which device is used (or .cuda() to move the tensor to the specified GPU), with a terminology like this when:
# allocates a tensor on GPU 1
a = torch.tensor([1., 2.], device=cuda)
So to access cuda:1:
cuda = torch.device('cuda')
with torch.cuda.device(1):
# allocates a tensor on GPU 1
a = torch.tensor([1., 2.], device=cuda)
And to access cuda:2:
cuda = torch.device('cuda')
with torch.cuda.device(2):
# allocates a tensor on GPU 2
a = torch.tensor([1., 2.], device=cuda)
However tensors without the device parameter will still be CPU tensors:
cuda = torch.device('cuda')
with torch.cuda.device(1):
# allocates a tensor on CPU
a = torch.tensor([1., 2.])
To sum it up:
No - unfortunately it is in the current implementation of the with-device
statement not possible to use in a way you described in your
question.
Here are some more examples from the documentation:
cuda = torch.device('cuda') # Default CUDA device
cuda0 = torch.device('cuda:0')
cuda2 = torch.device('cuda:2') # GPU 2 (these are 0-indexed)
x = torch.tensor([1., 2.], device=cuda0)
# x.device is device(type='cuda', index=0)
y = torch.tensor([1., 2.]).cuda()
# y.device is device(type='cuda', index=0)
with torch.cuda.device(1):
# allocates a tensor on GPU 1
a = torch.tensor([1., 2.], device=cuda)
# transfers a tensor from CPU to GPU 1
b = torch.tensor([1., 2.]).cuda()
# a.device and b.device are device(type='cuda', index=1)
# You can also use ``Tensor.to`` to transfer a tensor:
b2 = torch.tensor([1., 2.]).to(device=cuda)
# b.device and b2.device are device(type='cuda', index=1)
c = a + b
# c.device is device(type='cuda', index=1)
z = x + y
# z.device is device(type='cuda', index=0)
# even within a context, you can specify the device
# (or give a GPU index to the .cuda call)
d = torch.randn(2, device=cuda2)
e = torch.randn(2).to(cuda2)
f = torch.randn(2).cuda(cuda2)
# d.device, e.device, and f.device are all device(type='cuda', index=2)
| https://stackoverflow.com/questions/52076815/ |
Indexing a multi-dimensional tensor with a tensor in PyTorch | I have the following code:
a = torch.randint(0,10,[3,3,3,3])
b = torch.LongTensor([1,1,1,1])
I have a multi-dimensional index b and want to use it to select a single cell in a. If b wasn't a tensor, I could do:
a[1,1,1,1]
Which returns the correct cell, but:
a[b]
Doesn't work, because it just selects a[1] four times.
How can I do this? Thanks
| A more elegant (and simpler) solution might be to simply cast b as a tuple:
a[tuple(b)]
Out[10]: tensor(5.)
I was curious to see how this works with "regular" numpy, and found a related article explaining this quite well here.
| https://stackoverflow.com/questions/52092230/ |
Torchtext BucketIterator wrapper from tutorial produces SyntaxError | I am following and implementing code from this short tutorial on Torchtext, which is surprisingly clear given the poor documentation of Torchtext.
When the Iterator has been created (the batch generator) he proposes to create a wrapper to produce more reusable code. (See step 5 in the tutorial).
The code contains a surprisingly long and weird line, which I don't understand and which raises a SyntaxError: invalid syntax. Does anyone have a clue of what is going on?
(The problematic line is the one that starts with: if self.y_vars is &amp;amp;amp;lt;g [...])
class BatchWrapper:
def __init__(self, dl, x_var, y_vars):
self.dl, self.x_var, self.y_vars = dl, x_var, y_vars # we pass in the list of attributes for x &amp;amp;amp;amp;lt;g class="gr_ gr_3178 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del" id="3178" data-gr-id="3178"&amp;amp;amp;amp;gt;and y&amp;amp;amp;amp;lt;/g&amp;amp;amp;amp;gt;
def __iter__(self):
for batch in self.dl:
x = getattr(batch, self.x_var) # we assume only one input in this wrapper
if self.y_vars is &amp;amp;amp;amp;lt;g class="gr_ gr_3177 gr-alert gr_gramm gr_inline_cards gr_disable_anim_appear Grammar replaceWithoutSep" id="3177" data-gr-id="3177"&amp;amp;amp;amp;gt;not&amp;amp;amp;amp;lt;/g&amp;amp;amp;amp;gt; None: # we will concatenate y into a single tensor
y = torch.cat([getattr(batch, feat).unsqueeze(1) for feat in self.y_vars], dim=1).float()
else:
y = torch.zeros((1))
yield (x, y)
def __len__(self):
return len(self.dl)
| Yeah, I guess there is some typo from the author.
I think the correct piece of code is this:
if self.y_vars is not None:
y = torch.cat([getattr(batch, feat).unsqueeze(1) for feat in self.y_vars], dim=1).float()
else:
y = torch.zeros((1))
You can see this typo in the comment of line 3 also (in the code in blogpost).
| https://stackoverflow.com/questions/52096123/ |
What dtype should I use for PyTorch parameters in a neural network that inputs and outputs arrays of integers? | I'm currently building a neural network in PyTorch that accepts tensors of integers and outputs tensors of integers. There is only a small number of positive integers that are "allowed" (like 0, 1, 2, 3, and 4) as elements of the input and output tensors.
Neural networks usually work in continuous space.
For example, the nonlinear activation functions between layers are continuous and map integers to real numbers (including non-integers).
Is it best to use unsigned integers like torch.uint8 internally for the weights and biases of the network plus some custom activation function that maps ints to ints?
Or should I use high precision floats like torch.float32 and then round in the end, by binning real numbers to the nearest integer? I think this second strategy is the way to go, but maybe I'm missing out on something that would work nicely.
| Without knowing too much about your application I would go for torch.float32 with rounding. The main reason being that if you use a GPU to compute your neural network, it will require wights and data to be in float32 datatype. If you are not going to train your neural network and you want to run on CPU, then datatypes like torch.uint8 may help you as you can achieve more instructions per time interval (i.e. your application should run faster). If that doesn't leave you with a clue, then please be more specific about your application.
| https://stackoverflow.com/questions/52102692/ |
Why filters do not learn same features | The result of the convolution operation is multiple subsets of data are generated per kernel. For example if 5 kernels are applies to an image of dimension WxDx1 (1 channel) then 5 convolutions are applied to the data which generates a 5 dimensional image representation. WxDx1 becomes W'xD'x5 where W' and D' are smaller in dimension that W * D
Is the fact that each kernel is initialised to different values prevent each kernel from learning the same parameters ? If not what prevents each kernel learning the same parameters ?
If the image is RGB instead of grayscale so dimension WxDx3 instead of WxDx1 does this impact how the kernels learns patterns ?
| As you already mentioned, the sole fact of differing what Kernels learn is due to the random initialization of the weights in the beginning.
A great explanation is delivered here and also applies for the convolutional kernels in CNNs.
I regard this as distinct enough to not highlight it as a duplicate, but essentially it works the same.
| https://stackoverflow.com/questions/52111149/ |
Transforms not applying to the dataset | I'm new to pytorch and would like to understand something.
I am loading MNIST as follows:
transform_train = transforms.Compose(
[transforms.ToTensor(),
transforms.Resize(size, interpolation=2),
# transforms.Grayscale(num_output_channels=1),
transforms.RandomHorizontalFlip(p=0.5),
transforms.Normalize((mean), (std))])
trainset = torchvision.datasets.MNIST(root='./data', train=True,
download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=batch_size,
shuffle=True, num_workers=2)
However, when I explore the dataset, i.e. trainloader.dataset.train_data[0], I am getting a tensor in range [0,255] with shape (28,28).
What am I missing? Is this because the transforms are not applied directly to the dataloader but only in runtime? How can I explore my data otherwise?
| The transforms are applied when the __getitem__ method of the Dataset is called. For example look at the __getitem__ method of the MNIST dataset class: https://github.com/pytorch/vision/blob/master/torchvision/datasets/mnist.py#L62
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
img, target = self.data[index], self.targets[index]
# doing this so that it is consistent with all other datasets
# to return a PIL Image
img = Image.fromarray(img.numpy(), mode='L')
if self.transform is not None:
img = self.transform(img)
if self.target_transform is not None:
target = self.target_transform(target)
return img, target
The __getitem__ method gets called when you index your MNIST instance for the training set, e.g.:
trainset[0]
For more information on __getitem__: https://docs.python.org/3.6/reference/datamodel.html#object.getitem
The reason why Resize and RandomHorizontalFlip should be before ToTensor is that they act on PIL Images and all the datasets in Pytorch for consistency load the data as PIL Images first. In fact you can see that here they force that behavior through:
img = Image.fromarray(img.numpy(), mode='L')
Once you have the PIL Image of the corresponding index, the transforms are applied with
if self.transform is not None:
img = self.transform(img)
ToTensor transforms the PIL Image to a torch.Tensor and Normalize subtracts the mean and divides by the standard deviation you provide.
Eventually some transforms are applied to the label with
if self.target_transform is not None:
target = self.target_transform(target)
Finally the processed image and the processed label are returned. All of this happens in a single trainset[key] call.
import torch
from torchvision.transforms import *
from torchvision.datasets import MNIST
from torch.utils.data import DataLoader
transform_train = Compose([Resize(28, interpolation=2),
RandomHorizontalFlip(p=0.5),
ToTensor(),
Normalize([0.], [1.])])
trainset = MNIST(root='./data', train=True, download=True,
transform=transform_train)
trainloader = DataLoader(trainset, batch_size=32, shuffle=True, num_workers=2)
print(trainset[0][0].size(), trainset[0][0].min(), trainset[0][0].max())
shows
(torch.Size([1, 28, 28]), tensor(0.), tensor(1.))
| https://stackoverflow.com/questions/52120880/ |
How to ensure all PyTorch code fully utilises GPU on Google Colab | I am new to PyTorch and have been doing some tutorial on CIFAR10, specifically with Google Colab since I personally do not have a GPU to experiment on it yet.
I have successfully trained my neural network but I'm not sure whether my code is using the GPU from Colab, because the training time taken with Colab is not significantly faster than my 2014 MacBook Pro (without GPU).
I checked and my notebook is indeed running Tesla K80 but somehow the training speed is slow. So I think perhaps my code is not equipped with GPU syntax but I couldn't figure out which part is that.
# install PyTorch
from os import path
from wheel.pep425tags import get_abbr_impl, get_impl_ver, get_abi_tag
platform = '{}{}-{}'.format(get_abbr_impl(), get_impl_ver(), get_abi_tag())
accelerator = 'cu80' if path.exists('/opt/bin/nvidia-smi') else 'cpu'
!pip install -q http://download.pytorch.org/whl/{accelerator}/torch-0.4.0-{platform}-linux_x86_64.whl torchvision
import torch
import torch.nn as nn
from torch.optim import Adam
from torchvision import transforms
from torch.autograd import Variable
import torchvision.datasets as datasets
from torch.utils.data import DataLoader, TensorDataset
import matplotlib.pyplot as plt
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print(device)
# hyperparameters
n_epochs = 50
n_batch_size = 200
n_display_step = 200
n_learning_rate = 1e-3
n_download_cifar = True
# import cifar
# more about cifar https://www.cs.toronto.edu/~kriz/cifar.html
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
train_dataset = datasets.CIFAR10(
root="../datasets/cifar",
train=True,
transform=transform,
download=n_download_cifar)
test_dataset = datasets.CIFAR10(
root="../datasets/cifar",
train=False,
transform=transform)
# create data loader
train_loader = DataLoader(train_dataset, batch_size=n_batch_size, shuffle=True, num_workers=2)
test_loader = DataLoader(test_dataset, batch_size=n_batch_size, shuffle=False)
# build CNN
class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
# (3, 32, 32)
self.conv1 = nn.Sequential(
nn.Conv2d(3, 32, 5, 1, 2),
nn.ReLU(),
nn.MaxPool2d(2, 2))
# (32, 16, 16)
self.conv2 = nn.Sequential(
nn.Conv2d(32, 16, 5, 1, 2),
nn.ReLU(),
nn.MaxPool2d(2, 2))
# (16, 8, 8)
self.out = nn.Linear(16 * 8 * 8, 10)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = x.view(x.size(0), -1)
out = self.out(x)
return out
net = CNN()
net.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = Adam(net.parameters(), lr=n_learning_rate)
def get_accuracy(model, loader):
model.eval()
n_samples = 0
n_correct = 0
with torch.no_grad():
for step, (x, y) in enumerate(loader):
x, y = Variable(x).to(device), Variable(y).to(device)
out = model(x)
_, pred = torch.max(out, 1)
n_samples += y.size(0)
n_correct += (pred == y).sum().item()
return n_correct / n_samples
def train(model, criterion, optimizer, epochs, train_loader, test_loader):
for epoch in range(epochs):
for step, (x, y) in enumerate(train_loader):
model.train()
x, y = Variable(x).to(device), Variable(y).to(device)
out = model(x)
loss = criterion(out, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if step % n_display_step == 0:
print("Epoch {:2d} Loss {:.4f} Accuracy (Train | Test) {:.4f} {:.4f}".format(epoch, loss.item(), get_accuracy(model, train_loader), get_accuracy(model, test_loader)))
train(net, criterion, optimizer, n_epochs, train_loader, test_loader)
| Your code seems appropriate and I ran it on my MacBook, a GPU-enabled machine, and Google Colab. I compared the training time taken and my experiments show your code is optimized for GPU.
Can you try running this code from this thread and see how much GPU RAM Google has allocated for you? My guess is you've only given 5% GPU usage.
Regards,
Rex.
| https://stackoverflow.com/questions/52128744/ |
pytorch where is Embedding "max_norm" implemented? | The "embedding" class documentation https://pytorch.org/docs/stable/nn.html says
max_norm (float, optional) – If given, will renormalize the embedding vectors to have a norm lesser than this before extracting.
1) In my model, I use this embedding class as a parameter, not just as an input (the model learns the embedding.) In this case, I assume every time when updates happen, the embedding gets renormalized, not only when it's initialized. Is my understanding correct?
2) I wanted to confirm 1) by looking at the source, but I couldn't find the implementation in pytorch embedding class. https://pytorch.org/docs/stable/_modules/torch/nn/modules/sparse.html
Can someone point me to the max_norm implementation?
| If you see forward function in Embedding class here, there is a reference to torch.nn.functional.embedding which uses embedding_renorm_ which is in the cpp documentation here which means it is a cpp implementation. Some github search on pytorch repo pointed to this files (1, 2).
Answer to 1 is yes. Answer to 2 is above.
| https://stackoverflow.com/questions/52143583/ |
Installing packages but still python interpreter doesn't recognize using pycharm | I'm trying to install pytorch, but when I'm trying to import, my pycharm doesn't recognize this package although I'm sure I've installed this package on the same interpreter.
What I am missing?!
Thanks for your help.
| You are installing the packages in your base interpreter i.e your system interpreter. And I guess you started your Pycharm project using a virtual environment. So to install to your Pycharm venv. You need to start the console below i.e The Terminal in your Pycharm project and then perform pip install package_name again. This should install it to your virtual env. And then python will pick it up.
If you want to have all base packages from your system into your Pycharm venv. You can check the inherit base packages option while you are starting a new project with a new virtual env.
| https://stackoverflow.com/questions/52144109/ |
How to transform a vector to a matrix with each line equal to the vector in pytorch? | for exemple I have the vector [1, 2, 3]
I want to get a matrix like
[[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
How to do that efficiently?
| You should look at .repeat():
In [1]: torch.Tensor([1, 2, 3]).repeat(4, 1)
Out[1]:
tensor([[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.],
[1., 2., 3.]])
| https://stackoverflow.com/questions/52144507/ |
How do we analyse a loss vs epochs graph? | I'm training a language model and the loss vs epochs is plotted each time of training. I'm attaching two samples from it.
Obviously, the second one is showing better performance. But, from these graphs, when do we take a decision to stop training (early stopping)?
Can we understand overfitting and underfitting from these graphs or do I need to plot additional learning curves?
What are the additional inferences that can be made from these plots?
| The first conclusion is obviously that the first model performs worse than the second, and that is generally true, as long as you use the same data for validation. In the case where you train a model with different splits, that might not necessarily be the case.
Furthermore, to answer your question regarding overfitting/underfitting:
A typical graph for overfitting looks like this:
So, in your case, you clearly just reach convergence, but don't actually overfit! (This is great news!) On the other hand, you could ask yourself whether you could achieve even better results. I am assuming that you are decaying your learning rate, which lets you pan out at some form of plateau. If that is the case, try reducing the learning rate less at first, and see if you can reduce your loss even further.
Moreover, if you still see a very long plateau, you can also consider stopping early, since you effectively gain no more improvements. Depending on your framework, there are implementations of this (for example, Keras has callbacks for early stopping, which is generally tied to the validation/testing error). If your validation error increases, similar to the image, you should consider using the loweste validation error as a point for early stopping. One way I like to do this is to checkpoint the model every now and then, but only if the validation error improved.
Another inference you can make is the learning rate in general: Is it too large, your graph will likely be very "jumpy/jagged", whereas a very low learning rate will have only a small decline in the error, and not so much exponentially decaying behavior.
You can see a weak form of this by comparing the steepness of the decline in the first few epochs in your two examples, where the first one (with the lower learning rate) takes longer to converge.
Lastly, if your training and test error are very far apart (as in the first case), you might ask yourself whether you are actually accurately describing or modeling the problem; in some instances, you might realize that there is some problem in the (data) distribution that you might have overlooked. Since the second graph is way better, though, I doubt this is the case in your problem.
| https://stackoverflow.com/questions/52145992/ |
Best loss function for multi-class classification when the dataset is imbalance? | I'm currently using the Cross Entropy Loss function but with the imbalance data-set the performance is not great.
Is there better lost function?
| It's a very broad subject, but IMHO, you should try focal loss: It was introduced by Tsung-Yi Lin, Priya Goyal, Ross Girshick, Kaiming He and Piotr Dollar to handle imbalance prediction in object detection. Since introduced it was also used in the context of segmentation.
The idea of the focal loss is to reduce both loss and gradient for correct (or almost correct) prediction while emphasizing the gradient of errors.
As you can see in the graph:
Blue curve is the regular cross entropy loss: it has on the one hand non-negligible loss and gradient even for well classified examples, and on the other hand it has weaker gradient for the erroneously classified examples.
In contrast, focal loss (all other curves) has smaller loss and weaker gradient for the well classified examples and stronger gradients for the erroneously classified examples.
| https://stackoverflow.com/questions/52160979/ |
Coreml model float input for a pytorch model | I have a pytorch model that takes 3 x width x height image as input with the pixel values normalized between 0-1
E.g., input in pytorch
img = io.imread(img_path)
input_img = torch.from_numpy( np.transpose(img, (2,0,1)) ).contiguous().float()/255.0
I converted this model to coreml and exported an mlmodel which takes the input with correct dimensions
Image (Color width x height)
However, my predictions are incorrect as the model is expecting a float value between 0-1 and cvpixelbuffer is a int bwetween 0-255
I tried to normalize the values inside the model like so,
z = x.mul(1.0/255.0) # div op is not supported for export yet
However, when this op is done inside model at coreml level, int * float is casted as int and all values are essentially 0
Cast op is not supported for export e.g., x = x.float()
How can I make sure my input is properly shaped for prediction? Essentially, I want to take the pixel rgb and float divide 255.0 and pass it to the model for inference?
| I solved it using the coreml onnx coverter's preprocessing_args like so,
preprocessing_args= {'image_scale' : (1.0/255.0)}
Hope this helps someone
| https://stackoverflow.com/questions/52171143/ |
Pytorch model accuracy test | I'm using Pytorch to classify a series of images.
The NN is defined as follows:
model = models.vgg16(pretrained=True)
model.cuda()
for param in model.parameters(): param.requires_grad = False
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(25088, 4096)),
('relu', nn.ReLU()),
('fc2', nn.Linear(4096, 102)),
('output', nn.LogSoftmax(dim=1))
]))
model.classifier = classifier
The criterions and optimizers are as follows:
criterion = nn.NLLLoss()
optimizer = optim.Adam(model.classifier.parameters(), lr=0.001)
My validation function is as follows:
def validation(model, testloader, criterion):
test_loss = 0
accuracy = 0
for images, labels in testloader:
images.resize_(images.shape[0], 784)
output = model.forward(images)
test_loss += criterion(output, labels).item()
ps = torch.exp(output)
equality = (labels.data == ps.max(dim=1)[1])
accuracy += equality.type(torch.FloatTensor).mean()
return test_loss, accuracy
This is the piece of code that is throwing the following error:
RuntimeError: input has less dimensions than expected
epochs = 3
print_every = 40
steps = 0
running_loss = 0
testloader = dataloaders['test']
# change to cuda
model.to('cuda')
for e in range(epochs):
running_loss = 0
for ii, (inputs, labels) in enumerate(dataloaders['train']):
steps += 1
inputs, labels = inputs.to('cuda'), labels.to('cuda')
optimizer.zero_grad()
# Forward and backward passes
outputs = model.forward(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if steps % print_every == 0:
model.eval()
with torch.no_grad():
test_loss, accuracy = validation(model, testloader, criterion)
print("Epoch: {}/{}.. ".format(e+1, epochs),
"Training Loss: {:.3f}.. ".format(running_loss/print_every),
"Test Loss: {:.3f}.. ".format(test_loss/len(testloader)),
"Test Accuracy: {:.3f}".format(accuracy/len(testloader)))
running_loss = 0
Any help?
| Just in case it helps someone.
If you don't have a GPU system (say you are developing on a laptop and will eventually test on a server with GPU) you can do the same using:
if torch.cuda.is_available():
inputs =inputs.to('cuda')
else:
inputs = inputs.to('cuda')
Also, if you are wondering why there is a LogSoftmax, instead of Softmax that is because he is using NLLLoss as his loss function. You can read more about softmax here
| https://stackoverflow.com/questions/52176178/ |
Pytorch Validating Model Error: Expected input batch_size (3) to match target batch_size (4) | I'm building a NN in Pytorch that is supposed to classify across 102 classes.
I've got the following validation function:
def validation(model, testloader, criterion):
test_loss = 0
accuracy = 0
for inputs, classes in testloader:
inputs = inputs.to('cuda')
output = model.forward(inputs)
test_loss += criterion(output, labels).item()
ps = torch.exp(output)
equality = (labels.data == ps.max(dim=1)[1])
accuracy += equality.type(torch.FloatTensor).mean()
return test_loss, accuracy
Code for training (calls validation):
epochs = 3
print_every = 40
steps = 0
running_loss = 0
testloader = dataloaders['test']
# change to cuda
model.to('cuda')
for e in range(epochs):
running_loss = 0
for ii, (inputs, labels) in enumerate(dataloaders['train']):
steps += 1
inputs, labels = inputs.to('cuda'), labels.to('cuda')
optimizer.zero_grad()
# Forward and backward passes
outputs = model.forward(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if steps % print_every == 0:
model.eval()
with torch.no_grad():
test_loss, accuracy = validation(model, testloader, criterion)
print("Epoch: {}/{}.. ".format(e+1, epochs),
"Training Loss: {:.3f}.. ".format(running_loss/print_every),
"Test Loss: {:.3f}.. ".format(test_loss/len(testloader)),
"Test Accuracy: {:.3f}".format(accuracy/len(testloader)))
running_loss = 0
model.train()
Im getting this error message:
ValueError: Expected input batch_size (3) to match target batch_size (4).
Full Traceback:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-63-f9f67ed13b94> in <module>()
28 model.eval()
29 with torch.no_grad():
---> 30 test_loss, accuracy = validation(model, testloader, criterion)
31
32 print("Epoch: {}/{}.. ".format(e+1, epochs),
<ipython-input-62-dbc77acbda5e> in validation(model, testloader, criterion)
6 inputs = inputs.to('cuda')
7 output = model.forward(inputs)
----> 8 test_loss += criterion(output, labels).item()
9
10 ps = torch.exp(output)
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
489 result = self._slow_forward(*input, **kwargs)
490 else:
--> 491 result = self.forward(*input, **kwargs)
492 for hook in self._forward_hooks.values():
493 hook_result = hook(self, input, result)
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/loss.py in forward(self, input, target)
191 _assert_no_grad(target)
192 return F.nll_loss(input, target, self.weight, self.size_average,
--> 193 self.ignore_index, self.reduce)
194
195
/opt/conda/lib/python3.6/site-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce)
1328 if input.size(0) != target.size(0):
1329 raise ValueError('Expected input batch_size ({}) to match target batch_size ({}).'
-> 1330 .format(input.size(0), target.size(0)))
1331 if dim == 2:
1332 return torch._C._nn.nll_loss(input, target, weight, size_average, ignore_index, reduce)
ValueError: Expected input batch_size (3) to match target batch_size (4).
I don't understand where the error comes from. Indeed, without the validation code the training part works perfectly.
| In your validation function,
def validation(model, testloader, criterion):
test_loss = 0
accuracy = 0
for inputs, classes in testloader:
inputs = inputs.to('cuda')
output = model.forward(inputs)
test_loss += criterion(output, labels).item()
ps = torch.exp(output)
equality = (labels.data == ps.max(dim=1)[1])
accuracy += equality.type(torch.FloatTensor).mean()
return test_loss, accuracy
You are iterating on testloader and passing values to the variables inputs, classes but you are passing labels to your criterion.
| https://stackoverflow.com/questions/52178922/ |
How to delete maxpooling layer from pytorch network | I have "simple" Unet with resnet encoder on pytorch v3.1, which works pretty fine:
class UNetResNet(nn.Module):
"""PyTorch U-Net model using ResNet(34, 101 or 152) encoder.
UNet: https://arxiv.org/abs/1505.04597
ResNet: https://arxiv.org/abs/1512.03385
Args:
encoder_depth (int): Depth of a ResNet encoder (34, 101 or 152).
num_classes (int): Number of output classes.
num_filters (int, optional): Number of filters in the last layer of decoder. Defaults to 32.
dropout_2d (float, optional): Probability factor of dropout layer before output layer. Defaults to 0.2.
pretrained (bool, optional):
False - no pre-trained weights are being used.
True - ResNet encoder is pre-trained on ImageNet.
Defaults to False.
is_deconv (bool, optional):
False: bilinear interpolation is used in decoder.
True: deconvolution is used in decoder.
Defaults to False.
"""
def __init__(self, encoder_depth, num_classes, num_filters=32, dropout_2d=0.2,
pretrained=False, is_deconv=False):
super().__init__()
self.num_classes = num_classes
self.dropout_2d = dropout_2d
if encoder_depth == 34:
self.encoder = torchvision.models.resnet34(pretrained=pretrained)
bottom_channel_nr = 512
elif encoder_depth == 101:
self.encoder = torchvision.models.resnet101(pretrained=pretrained)
bottom_channel_nr = 2048
elif encoder_depth == 152:
self.encoder = torchvision.models.resnet152(pretrained=pretrained)
bottom_channel_nr = 2048
else:
raise NotImplementedError('only 34, 101, 152 version of Resnet are implemented')
self.pool = nn.MaxPool2d(2, 2)
self.relu = nn.ReLU(inplace=True)
self.conv1 = nn.Sequential(self.encoder.conv1,
self.encoder.bn1,
self.encoder.relu,
self.pool)
self.conv2 = self.encoder.layer1
self.conv3 = self.encoder.layer2
self.conv4 = self.encoder.layer3
self.conv5 = self.encoder.layer4
self.center = DecoderBlockV2(bottom_channel_nr, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec5 = DecoderBlockV2(bottom_channel_nr + num_filters * 8, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec4 = DecoderBlockV2(bottom_channel_nr // 2 + num_filters * 8, num_filters * 8 * 2, num_filters * 8,
is_deconv)
self.dec3 = DecoderBlockV2(bottom_channel_nr // 4 + num_filters * 8, num_filters * 4 * 2, num_filters * 2,
is_deconv)
self.dec2 = DecoderBlockV2(bottom_channel_nr // 8 + num_filters * 2, num_filters * 2 * 2, num_filters * 2 * 2,
is_deconv)
self.dec1 = DecoderBlockV2(num_filters * 2 * 2, num_filters * 2 * 2, num_filters, is_deconv)
self.dec0 = ConvRelu(num_filters, num_filters)
self.final = nn.Conv2d(num_filters, num_classes, kernel_size=1)
def forward(self, x):
conv1 = self.conv1(x)
conv2 = self.conv2(conv1)
conv3 = self.conv3(conv2)
conv4 = self.conv4(conv3)
conv5 = self.conv5(conv4)
pool = self.pool(conv5) # that pool layer I would like to delete
center = self.center(pool)
dec5 = self.dec5(torch.cat([center, conv5], 1))
dec4 = self.dec4(torch.cat([dec5, conv4], 1))
dec3 = self.dec3(torch.cat([dec4, conv3], 1))
dec2 = self.dec2(torch.cat([dec3, conv2], 1))
dec1 = self.dec1(dec2)
dec0 = self.dec0(dec1)
return self.final(F.dropout2d(dec0, p=self.dropout_2d))
By deleting that pool layer from forward we come to next forward function:
def forward(self, x):
conv1 = self.conv1(x)
conv2 = self.conv2(conv1)
conv3 = self.conv3(conv2)
conv4 = self.conv4(conv3)
conv5 = self.conv5(conv4)
center = self.center(conv5) #now center connects with conv5
dec5 = self.dec5(torch.cat([center, conv5], 1))
dec4 = self.dec4(torch.cat([dec5, conv4], 1))
dec3 = self.dec3(torch.cat([dec4, conv3], 1))
dec2 = self.dec2(torch.cat([dec3, conv2], 1))
dec1 = self.dec1(dec2)
dec0 = self.dec0(dec1)
return self.final(F.dropout2d(dec0, p=self.dropout_2d))
Applying only such changes and we will face such error:
~/Desktop/ml/salt/unet_models.py in forward(self, x)
397 center = self.center(conv5)
398
--> 399 dec5 = self.dec5(torch.cat([center, conv5], 1))
400
401 dec4 = self.dec4(torch.cat([dec5, conv4], 1))
RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 1. Got 4 and 8 in dimension 2 at /pytorch/torch/lib/THC/generic/THCTensorMath.cu:111
So we have to somehow change dec4, but how?
More info:
class DecoderBlockV2(nn.Module):
def __init__(self, in_channels, middle_channels, out_channels, is_deconv=True):
super(DecoderBlockV2, self).__init__()
self.in_channels = in_channels
if is_deconv:
"""
Paramaters for Deconvolution were chosen to avoid artifacts, following
link https://distill.pub/2016/deconv-checkerboard/
"""
self.block = nn.Sequential(
ConvRelu(in_channels, middle_channels),
nn.ConvTranspose2d(middle_channels, out_channels, kernel_size=4, stride=2,
padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
else:
self.block = nn.Sequential(
nn.Upsample(scale_factor=2, mode='bilinear'),
ConvRelu(in_channels, middle_channels),
ConvRelu(middle_channels, out_channels),
)
def forward(self, x):
return self.block(x)
class ConvRelu(nn.Module):
def __init__(self, in_, out):
super().__init__()
self.conv = conv3x3(in_, out)
self.activation = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
x = self.activation(x)
return x
| Your error stems from the fact that you are trying to concat (torch.cat) center and conv5 - but the dimensions of these tensors do not match.
Originally, you had the following spatial dimensions
conv5: 4x4
pool: 2x2
center: 4x4 # upsampled
This way you can concat center and conv5 since they are both 4x4 tensors.
However, if you remove the pooling layer, you end up with
conv5: 4x4
center: 8x8 # upsampling more than you need
Now you cannot concat center and conv5 since their spatial dimensions mismatch.
What can you do?
One option is to remove center as well as the pooling, leaving you with
dec5 = self.dec5(conv5)
Another option is to remove the nn.Upsample part from the block of center, leaving you with
self.block = nn.Sequential(
ConvRelu(in_channels, middle_channels),
ConvRelu(middle_channels, out_channels),
)
| https://stackoverflow.com/questions/52192599/ |
How to free up all memory pytorch is taken from gpu memory | I have some kind of high level code, so model training and etc. are wrapped by pipeline_network class. My main goal is to train new model every new fold.
for train_idx, valid_idx in cv.split(meta_train[DEPTH_COLUMN].values.reshape(-1)):
meta_train_split, meta_valid_split = meta_train.iloc[train_idx], meta_train.iloc[valid_idx]
pipeline_network = unet(config=CONFIG, suffix = 'fold' + str(fold), train_mode=True)
But then I move on to 2nd fold everything fails out of gpu memory:
RuntimeError: cuda runtime error (2) : out of memory at /pytorch/torch/lib/THC/generic/THCStorage.cu:58
At the end of epoch I tried to manually delete that pipeline with no luck:
def clean_object_from_memory(obj): #definition
del obj
gc.collect()
torch.cuda.empty_cache()
clean_object_from_memory( clean_object_from_memory) # calling
Calling this didn't help as well:
def dump_tensors(gpu_only=True):
torch.cuda.empty_cache()
total_size = 0
for obj in gc.get_objects():
try:
if torch.is_tensor(obj):
if not gpu_only or obj.is_cuda:
del obj
gc.collect()
elif hasattr(obj, "data") and torch.is_tensor(obj.data):
if not gpu_only or obj.is_cuda:
del obj
gc.collect()
except Exception as e:
pass
How can reset pytorch then I move on to the next fold?
| Try delete the object with del and then apply torch.cuda.empty_cache(). The reusable memory will be freed after this operation.
| https://stackoverflow.com/questions/52205412/ |
PyTorch Gradient Descent | I am trying to manually implement gradient descent in PyTorch as a learning exercise. I have the following to create my synthetic dataset:
import torch
torch.manual_seed(0)
N = 100
x = torch.rand(N,1)*5
# Let the following command be the true function
y = 2.3 + 5.1*x
# Get some noisy observations
y_obs = y + 2*torch.randn(N,1)
Then I create my predictive function (y_pred) as shown below.
w = torch.randn(1, requires_grad=True)
b = torch.randn(1, requires_grad=True)
y_pred = w*x+b
mse = torch.mean((y_pred-y_obs)**2)
which uses MSE to infer the weights w,b. I use the block below to update the values according to the gradient.
gamma = 1e-2
for i in range(100):
w = w - gamma *w.grad
b = b - gamma *b.grad
mse.backward()
However, the loop only works in the first iteration. The second iteration onwards w.grad is set to None. I am fairly sure the reason this happens is because I am setting w as a function of it self (I might be wrong).
The question is how do I update the weights properly with the gradient information?
|
You should call the backward method before you apply the gradient descent.
You need to use the new weight to calculate the loss every iteration.
Create new tensor without gradient tape every iteration.
The following code works fine on my computer and gives w=5.1 & b=2.2 after 500 iterations training.
Code:
import torch
torch.manual_seed(0)
N = 100
x = torch.rand(N,1)*5
# Let the following command be the true function
y = 2.3 + 5.1*x
# Get some noisy observations
y_obs = y + 0.2*torch.randn(N,1)
w = torch.randn(1, requires_grad=True)
b = torch.randn(1, requires_grad=True)
gamma = 0.01
for i in range(500):
print(i)
# use new weight to calculate loss
y_pred = w * x + b
mse = torch.mean((y_pred - y_obs) ** 2)
# backward
mse.backward()
print('w:', w)
print('b:', b)
print('w.grad:', w.grad)
print('b.grad:', b.grad)
# gradient descent, don't track
with torch.no_grad():
w = w - gamma * w.grad
b = b - gamma * b.grad
w.requires_grad = True
b.requires_grad = True
Output:
499
w: tensor([5.1095], requires_grad=True)
b: tensor([2.2474], requires_grad=True)
w.grad: tensor([0.0179])
b.grad: tensor([-0.0576])
| https://stackoverflow.com/questions/52213282/ |
Pytorch saving and reloading model | I have the following structure for a VGG16 model:
<bound method Module.state_dict of VGG(
(features): Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU(inplace)
(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU(inplace)
(4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(6): ReLU(inplace)
(7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(8): ReLU(inplace)
(9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(11): ReLU(inplace)
(12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(13): ReLU(inplace)
(14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(15): ReLU(inplace)
(16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(18): ReLU(inplace)
(19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(20): ReLU(inplace)
(21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(22): ReLU(inplace)
(23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(25): ReLU(inplace)
(26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(27): ReLU(inplace)
(28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(29): ReLU(inplace)
(30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(classifier): Network(
(hidden_layers): ModuleList(
(0): Linear(in_features=25088, out_features=4096, bias=True)
)
(output): Linear(in_features=4096, out_features=102, bias=True)
(dropout): Dropout(p=0.5)
)
When saving the model with the following code:
checkpoint = {'input_size': 25088,
'output_size': 102,
'hidden_layers': [each.out_features for each in model.hidden_layers],
'state_dict': model.state_dict()}
torch.save(checkpoint, 'checkpoint.pth')
I get the following error:
AttributeError Traceback (most recent call last)
<ipython-input-13-b4654570e6e8> in <module>()
2 checkpoint = {'input_size': 25088,
3 'output_size': 102,
----> 4 'hidden_layers': [each.out_features for each in model.hidden_layers],
5 'state_dict': model.state_dict()}
6
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in __getattr__(self, name)
530 return modules[name]
531 raise AttributeError("'{}' object has no attribute '{}'".format(
--> 532 type(self).__name__, name))
533
534 def __setattr__(self, name, value):
AttributeError: 'VGG' object has no attribute 'hidden_layers'
However, VGG has hidden_layers.
How to save A VGG with learning transfer?
| torch.save(model.state_dict(), 'checkpoint.pth')
state_dict = torch.load('checkpoint.pth')
model.load_state_dict(state_dict)
| https://stackoverflow.com/questions/52213726/ |
Setting custom loss causes RuntimeError: Variable data has to be a tensor, but got Variable in Pytorch | I have custom class for the net definition:
class PyTorchUNet(Model):
....
def set_loss(self):
if self.activation_func == 'softmax': #this is working example
loss_function = partial(mixed_dice_cross_entropy_loss,
dice_loss=multiclass_dice_loss,
cross_entropy_loss=nn.CrossEntropyLoss(),
dice_activation='softmax',
dice_weight=self.architecture_config['model_params']['dice_weight'],
cross_entropy_weight=self.architecture_config['model_params']['bce_weight']
)
elif self.activation_func == 'sigmoid':
loss_function = designed_loss #setting will cause error on validation
else:
raise Exception('Only softmax and sigmoid activations are allowed')
self.loss_function = [('mask', loss_function, 1.0)]
def designed_loss(output, target):
target = target.long() # this should make variable to tensor
return lovasz_hinge(output, target)
# this is just as it from github
def lovasz_hinge(logits, labels, per_image=True, ignore=None):
"""
Binary Lovasz hinge loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
per_image: compute the loss per image instead of per batch
ignore: void class id
"""
if per_image:
loss = mean(lovasz_hinge_flat(*flatten_binary_scores(log.unsqueeze(0), lab.unsqueeze(0), ignore))
for log, lab in zip(logits, labels))
else:
loss = lovasz_hinge_flat(*flatten_binary_scores(logits, labels, ignore))
return loss
def lovasz_hinge_flat(logits, labels):
"""
Binary Lovasz hinge loss
logits: [P] Variable, logits at each prediction (between -\infty and +\infty)
labels: [P] Tensor, binary ground truth labels (0 or 1)
ignore: label to ignore
"""
if len(labels) == 0:
# only void pixels, the gradients should be 0
return logits.sum() * 0.
signs = 2. * labels.float() - 1.
errors = (1. - logits * Variable(signs))
errors_sorted, perm = torch.sort(errors, dim=0, descending=True)
perm = perm.data
gt_sorted = labels[perm]
grad = lovasz_grad(gt_sorted)
loss = torch.dot(F.elu(errors_sorted), Variable(grad))
return loss
def mean(l, ignore_nan=False, empty=0):
"""
nanmean compatible with generators.
"""
l = iter(l)
if ignore_nan:
l = ifilterfalse(np.isnan, l)
try:
n = 1
acc = next(l)
except StopIteration:
if empty == 'raise':
raise ValueError('Empty mean')
return empty
for n, v in enumerate(l, 2):
acc += v
if n == 1:
return acc
return acc / n
Working example:
def mixed_dice_cross_entropy_loss(output, target, dice_weight=0.5, dice_loss=None,
cross_entropy_weight=0.5, cross_entropy_loss=None, smooth=0,
dice_activation='softmax'):
num_classes_without_background = output.size(1) - 1
dice_output = output[:, 1:, :, :]
dice_target = target[:, :num_classes_without_background, :, :].long()
cross_entropy_target = torch.zeros_like(target[:, 0, :, :]).long()
for class_nr in range(num_classes_without_background):
cross_entropy_target = where(target[:, class_nr, :, :], class_nr + 1, cross_entropy_target)
if cross_entropy_loss is None:
cross_entropy_loss = nn.CrossEntropyLoss()
if dice_loss is None:
dice_loss = multiclass_dice_loss
return dice_weight * dice_loss(dice_output, dice_target, smooth,
dice_activation) + cross_entropy_weight * cross_entropy_loss(output,
cross_entropy_target)
def multiclass_dice_loss(output, target, smooth=0, activation='softmax'):
"""Calculate Dice Loss for multiple class output.
Args:
output (torch.Tensor): Model output of shape (N x C x H x W).
target (torch.Tensor): Target of shape (N x H x W).
smooth (float, optional): Smoothing factor. Defaults to 0.
activation (string, optional): Name of the activation function, softmax or sigmoid. Defaults to 'softmax'.
Returns:
torch.Tensor: Loss value.
"""
if activation == 'softmax':
activation_nn = torch.nn.Softmax2d()
elif activation == 'sigmoid':
activation_nn = torch.nn.Sigmoid()
else:
raise NotImplementedError('only sigmoid and softmax are implemented')
loss = 0
dice = DiceLoss(smooth=smooth)
output = activation_nn(output)
num_classes = output.size(1)
target.data = target.data.float()
for class_nr in range(num_classes):
loss += dice(output[:, class_nr, :, :], target[:, class_nr, :, :])
return loss / num_classes
As result I keep getting:
RuntimeError: Variable data has to be a tensor, but got Variable
How to fix the problem?
| Are you still use pytorch 0.3?
if yes, the following snippet may help
tensor = var.data
| https://stackoverflow.com/questions/52217422/ |
Use pretrained embedding in Spanish with Torchtext | I am using Torchtext in an NLP project. I have a pretrained embedding in my system, which I'd like to use. Therefore, I tried:
my_field.vocab.load_vectors(my_path)
But, apparently, this only accepts the names of a short list of pre-accepted embeddings, for some reason. In particular, I get this error:
Got string input vector "my_path", but allowed pretrained vectors are ['charngram.100d', 'fasttext.en.300d', ..., 'glove.6B.300d']
I found some people with similar problems, but the solutions I can find so far are "change Torchtext source code", which I would rather avoid if at all possible.
Is there any other way in which I can work with my pretrained embedding? A solution that allows to use another Spanish pretrained embedding is acceptable.
Some people seem to think it is not clear what I am asking. So, if the title and final question are not enough: "I need help using a pre-trained Spanish word-embedding in Torchtext".
| It turns out there is a relatively simple way to do this without changing Torchtext's source code. Inspiration from this Github thread.
1. Create numpy word-vector tensor
You need to load your embedding so you end up with a numpy array with dimensions (number_of_words, word_vector_length):
my_vecs_array[word_index] should return your corresponding word vector.
IMPORTANT. The indices (word_index) for this array array MUST be taken from Torchtext's word-to-index dictionary (field.vocab.stoi). Otherwise Torchtext will point to the wrong vectors!
Don't forget to convert to tensor:
my_vecs_tensor = torch.from_numpy(my_vecs_array)
2. Load array to Torchtext
I don't think this step is really necessary because of the next one, but it allows to have the Torchtext field with both the dictionary and vectors in one place.
my_field.vocab.set_vectors(my_field.vocab.stoi, my_vecs_tensor, word_vectors_length)
3. Pass weights to model
In your model you will declare the embedding like this:
my_embedding = toch.nn.Embedding(vocab_len, word_vect_len)
Then you can load your weights using:
my_embedding.weight = torch.nn.Parameter(my_field.vocab.vectors, requires_grad=False)
Use requires_grad=True if you want to train the embedding, use False if you want to freeze it.
EDIT: It looks like there is another way that looks a bit easier! The improvement is that apparently you can pass the pre-trained word vectors directly during the vocabulary-building step, so that takes care of steps 1-2 here.
| https://stackoverflow.com/questions/52224555/ |
How to use PNASNet5 as encoder in Unet in pytorch | I want use PNASNet5Large as encoder for my Unet here is my wrong aproach for the PNASNet5Large but working for resnet:
class UNetResNet(nn.Module):
def __init__(self, encoder_depth, num_classes, num_filters=32, dropout_2d=0.2,
pretrained=False, is_deconv=False):
super().__init__()
self.num_classes = num_classes
self.dropout_2d = dropout_2d
if encoder_depth == 34:
self.encoder = torchvision.models.resnet34(pretrained=pretrained)
bottom_channel_nr = 512
elif encoder_depth == 101:
self.encoder = torchvision.models.resnet101(pretrained=pretrained)
bottom_channel_nr = 2048
elif encoder_depth == 152: #this works
self.encoder = torchvision.models.resnet152(pretrained=pretrained)
bottom_channel_nr = 2048
elif encoder_depth == 777: #coded version for the pnasnet
self.encoder = PNASNet5Large()
bottom_channel_nr = 4320 #this unknown for me as well
self.pool = nn.MaxPool2d(2, 2)
self.relu = nn.ReLU(inplace=True)
self.conv1 = nn.Sequential(self.encoder.conv1,
self.encoder.bn1,
self.encoder.relu,
self.pool)
self.conv2 = self.encoder.layer1 #PNASNet5Large doesn't have such layers
self.conv3 = self.encoder.layer2
self.conv4 = self.encoder.layer3
self.conv5 = self.encoder.layer4
self.center = DecoderCenter(bottom_channel_nr, num_filters * 8 *2, num_filters * 8, False)
self.dec5 = DecoderBlock(bottom_channel_nr + num_filters * 8, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec4 = DecoderBlock(bottom_channel_nr // 2 + num_filters * 8, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec3 = DecoderBlock(bottom_channel_nr // 4 + num_filters * 8, num_filters * 4 * 2, num_filters * 2, is_deconv)
self.dec2 = DecoderBlock(bottom_channel_nr // 8 + num_filters * 2, num_filters * 2 * 2, num_filters * 2 * 2,
is_deconv)
self.dec1 = DecoderBlock(num_filters * 2 * 2, num_filters * 2 * 2, num_filters, is_deconv)
self.dec0 = ConvRelu(num_filters, num_filters)
self.final = nn.Conv2d(num_filters, num_classes, kernel_size=1)
def forward(self, x):
conv1 = self.conv1(x)
conv2 = self.conv2(conv1)
conv3 = self.conv3(conv2)
conv4 = self.conv4(conv3)
conv5 = self.conv5(conv4)
center = self.center(conv5)
dec5 = self.dec5(torch.cat([center, conv5], 1))
dec4 = self.dec4(torch.cat([dec5, conv4], 1))
dec3 = self.dec3(torch.cat([dec4, conv3], 1))
dec2 = self.dec2(torch.cat([dec3, conv2], 1))
dec1 = self.dec1(dec2)
dec0 = self.dec0(dec1)
return self.final(F.dropout2d(dec0, p=self.dropout_2d))
1) How to get how many bottom channels pnasnet has. It ends up following way:
...
self.cell_11 = Cell(in_channels_left=4320, out_channels_left=864,
in_channels_right=4320, out_channels_right=864)
self.relu = nn.ReLU()
self.avg_pool = nn.AvgPool2d(11, stride=1, padding=0)
self.dropout = nn.Dropout(0.5)
self.last_linear = nn.Linear(4320, num_classes)
Is 4320 the answer or not, in_channels_left and out_channels_left - something new for me
2) Resnet has somekind of 4 big layers which I use and encoders in my Unet arch, how get similar layer from pnasnet
I'm using pytorch 3.1 and this is the link to the Pnasnet directory
3) AttributeError: 'PNASNet5Large' object has no attribute 'conv1' - so doesn't have conv1 as well
UPD: tried smth like this but failed
class UNetPNASNet(nn.Module):
def init(self, encoder_depth, num_classes, num_filters=32, dropout_2d=0.2,
pretrained=False, is_deconv=False):
super().init()
self.num_classes = num_classes
self.dropout_2d = dropout_2d
self.encoder = PNASNet5Large()
bottom_channel_nr = 4320
self.center = DecoderCenter(bottom_channel_nr, num_filters * 8 *2, num_filters * 8, False)
self.dec5 = DecoderBlockV2(bottom_channel_nr + num_filters * 8, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec4 = DecoderBlockV2(bottom_channel_nr // 2 + num_filters * 8, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec3 = DecoderBlockV2(bottom_channel_nr // 4 + num_filters * 8, num_filters * 4 * 2, num_filters * 2, is_deconv)
self.dec2 = DecoderBlockV2(num_filters * 4 * 4, num_filters * 4 * 4, num_filters, is_deconv)
self.dec1 = DecoderBlockV2(num_filters * 2 * 2, num_filters * 2 * 2, num_filters, is_deconv)
self.dec0 = ConvRelu(num_filters, num_filters)
self.final = nn.Conv2d(num_filters, num_classes, kernel_size=1)
def forward(self, x):
features = self.encoder.features(x)
relued_features = self.encoder.relu(features)
avg_pooled_features = self.encoder.avg_pool(relued_features)
center = self.center(avg_pooled_features)
dec5 = self.dec5(torch.cat([center, avg_pooled_features], 1))
dec4 = self.dec4(torch.cat([dec5, relued_features], 1))
dec3 = self.dec3(torch.cat([dec4, features], 1))
dec2 = self.dec2(dec3)
dec1 = self.dec1(dec2)
dec0 = self.dec0(dec1)
return self.final(F.dropout2d(dec0, p=self.dropout_2d))
RuntimeError: Given input size: (4320x4x4). Calculated output size: (4320x-6x-6). Output size is too small at /opt/conda/conda-bld/pytorch_1525796793591/work/torch/lib/THCUNN/generic/SpatialAveragePooling.cu:63
| So you want to use PNASNetLarge instead o ResNets as encoder in your UNet architecture. Let's see how ResNets are used. In your __init__:
self.pool = nn.MaxPool2d(2, 2)
self.relu = nn.ReLU(inplace=True)
self.conv1 = nn.Sequential(self.encoder.conv1,
self.encoder.bn1,
self.encoder.relu,
self.pool)
self.conv2 = self.encoder.layer1
self.conv3 = self.encoder.layer2
self.conv4 = self.encoder.layer3
self.conv5 = self.encoder.layer4
So you use the ResNets up to layer4, which is the last block before the average pooling, the sizes you're using for resnet are the ones after the average pooling, therefore I assume there is a self.encoder.avgpool missing after self.conv5 = self.encoder.layer4. The forward of a ResNet in torchvision.models looks like this:
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
I guess you want to adopt a similar solution for PNASNet5Large (use the architecture up to the average pooling layer).
1) To get how many channels your PNASNet5Large has, you need to look at the output tensor size after the average pooling, for example by feeding a dummy tensor to it. Also notice that while ResNet are commonly used with input size (batch_size, 3, 224, 224), PNASNetLarge uses (batch_size, 3, 331, 331).
m = PNASNet5Large()
x1 = torch.randn(1, 3, 331, 331)
m.avg_pool(m.features(x1)).size()
torch.Size([1, 4320, 1, 1])
Therefore yes, bottom_channel_nr=4320 for your PNASNet.
2) Being the architecture totally different, you need to modify the __init__ and forward of your UNet. If you decide to use PNASNet, I suggest you make a new class:
class UNetPNASNet(nn.Module):
def __init__(self, encoder_depth, num_classes, num_filters=32, dropout_2d=0.2,
pretrained=False, is_deconv=False):
super().__init__()
self.num_classes = num_classes
self.dropout_2d = dropout_2d
self.encoder = PNASNet5Large()
bottom_channel_nr = 4320
self.center = DecoderCenter(bottom_channel_nr, num_filters * 8 *2, num_filters * 8, False)
self.dec5 = DecoderBlock(bottom_channel_nr + num_filters * 8, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec4 = DecoderBlock(bottom_channel_nr // 2 + num_filters * 8, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec3 = DecoderBlock(bottom_channel_nr // 4 + num_filters * 8, num_filters * 4 * 2, num_filters * 2, is_deconv)
self.dec2 = DecoderBlock(bottom_channel_nr // 8 + num_filters * 2, num_filters * 2 * 2, num_filters * 2 * 2,
is_deconv)
self.dec1 = DecoderBlock(num_filters * 2 * 2, num_filters * 2 * 2, num_filters, is_deconv)
self.dec0 = ConvRelu(num_filters, num_filters)
self.final = nn.Conv2d(num_filters, num_classes, kernel_size=1)
def forward(self, x):
features = self.encoder.features(x)
relued_features = self.encoder.relu(features)
avg_pooled_features = self.encoder.avg_pool(relued_features)
center = self.center(avg_pooled_features)
dec5 = self.dec5(torch.cat([center, conv5], 1))
dec4 = self.dec4(torch.cat([dec5, conv4], 1))
dec3 = self.dec3(torch.cat([dec4, conv3], 1))
dec2 = self.dec2(torch.cat([dec3, conv2], 1))
dec1 = self.dec1(dec2)
dec0 = self.dec0(dec1)
return self.final(F.dropout2d(dec0, p=self.dropout_2d))
3) PNASNet5Large doesn't have a conv1 attribute indeed. You can check it by
'conv1' in list(m.modules())
False
| https://stackoverflow.com/questions/52235520/ |
PyTorch - create padded tensor from sequences of variable length | I am looking for a good (efficient and preferably simple) way to create padded tensor from sequences of variable length / shape. The best way I can imagine so far is a naive approach like this:
import torch
seq = [1,2,3] # seq of variable length
max_len = 5 # maximum length of seq
t = torch.zeros(5) # padding value
for i, e in enumerate(seq):
t[i] = e
print(t)
Output:
tensor([ 1., 2., 3., 0., 0.])
Is there a better way to do so?
I haven't found something yet, but I guess there must be something better.
I'm thinking of some function to extend the sequence tensor to the desired shape with the desired padding. Or something to create the padded tensor directly from the sequence. But of course other approaches are welcome too.
| Make your variable length sequence a torch.Tensor and use torch.nn.functional.pad
import torch
import torch.nn.functional as F
seq = torch.Tensor([1,2,3]) # seq of variable length
print(F.pad(seq, pad=(0, 2), mode='constant', value=0))
1
2
3
0
0
[torch.FloatTensor of size 5]
Signature of F.pad is:
input: input tensor that is your variable length sequence.
pad: m-elem tuple, where (m/2) ≤ input dimensions and m is even. In 1D case first element is how much padding to the left and second element how much padding to the right of your sequence.
mode: fill the padding with a constant or by replicating the border or reflecting the values.
value: the fill value if you choose a constant padding.
| https://stackoverflow.com/questions/52235928/ |
How to change channel dimension of am image? | Suppose I have torch tensor with shape = [x,y,z,21] where x = batch_size, y = image_width, z= image_height. The above tensor represents batch of images with 21 channels. How should I convert it to size = [ x,y,z,3 ] ?
| [x,y,z,21] -> [x,y,z,1] -> [x,y,z,3]
for segmentation results predicts with size [x,y,z,21]
segmentation class index result with size [x,y,z,1]
# for pytorch, the right format for image is [batch, channels, height, width]
# however your image format [batch, height, width, channels]
result=predicts.argmax(-1)
the index combie the color map will help you! view voc color map for detial
| https://stackoverflow.com/questions/52238167/ |
Tensorflow vs PyTorch: convolution doesn't work | I'm trying to test if Tensorflow convolution output matches PyTorch convolution output with the same weights.
Here's my code in which I copy the weights from Tensorflow to Torch, convolve and compare outputs:
import tensorflow as tf
import numpy as np
import math
from math import floor, ceil
import os
import math
import datetime
from scipy import misc
from PIL import Image
import model
import torch
from torch import nn
import common
import torch.nn.functional as F
sess = tf.Session()
np.random.seed(1)
tf.set_random_seed(1)
#parameters
kernel_size = 3
input_feat = 4
output_feat = 4
#inputs
npo = np.random.random((1,5,5, input_feat))
x = tf.convert_to_tensor(npo, tf.float32)
x2 = torch.tensor(np.transpose(npo, [0, 3, 1, 2])).double()
#the same weights
weights = np.random.random((kernel_size,kernel_size,input_feat,output_feat))
weights_torch = np.transpose(weights, [3, 2, 1, 0])
#convolving with tensorflow
w = tf.Variable(weights, name="testconv_W", dtype=tf.float32)
res = tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding="VALID")
sess.run(tf.global_variables_initializer())
#convolving with torch
torchres = F.conv2d(x2, torch.tensor(weights_torch), padding=0, bias=torch.zeros((output_feat)).double())
#comparing the results
print(np.mean(np.transpose(sess.run(res), [0, 3, 1, 2])) - torch.mean(torchres).detach().numpy())
It outputs
0.15440369065716908
Why? Why is there such a big difference? Is the Tensorflow conv2d implementation incorrect? Why doesn't it match PyTorch? Am I doing something wrong? On kernel size 1 everything works fine.
Please help.
| You might try x2 = torch.tensor(np.transpose(npo, [0, 3, 2, 1])).double()
instead of x2 = torch.tensor(np.transpose(npo, [0, 3, 1, 2])).double()
| https://stackoverflow.com/questions/52261909/ |
Unsupported GNU version! gcc versions later than 6 are not supported! - causes importing cpp_extension | Then I import it says before error this:
/home/dex/anaconda3/lib/python3.6/site-packages/torch/utils/cpp_extension.py:118: UserWarning:
!! WARNING !!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Your compiler (c++) may be ABI-incompatible with PyTorch!
Please use a compiler that is ABI-compatible with GCC 4.9 and above.
See https://gcc.gnu.org/onlinedocs/libstdc++/manual/abi.html.
See https://gist.github.com/goldsborough/d466f43e8ffc948ff92de7486c5216d6
for instructions on how to install GCC 4.9 or higher.
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!! WARNING !!
warnings.warn(ABI_INCOMPATIBILITY_WARNING.format(compiler))
But following gist trying to install 4.9 and 5.9 same errors
Cant get installed, also on 18.04 but with other error:
dex@dexpc:~$ sudo apt-get install software-properties-common
[sudo] password for dex:
Reading package lists... Done
Building dependency tree
Reading state information... Done
software-properties-common is already the newest version (0.96.24.32.4).
0 upgraded, 0 newly installed, 0 to remove and 2 not upgraded.
dex@dexpc:~$ sudo apt-get update
Ign:1 http://dl.google.com/linux/chrome/deb stable InRelease
Hit:2 http://archive.ubuntu.com/ubuntu bionic InRelease
Get:3 http://security.ubuntu.com/ubuntu xenial-security InRelease [107 kB]
Hit:4 http://ppa.launchpad.net/graphics-drivers/ppa/ubuntu bionic InRelease
Hit:5 http://dl.google.com/linux/chrome/deb stable Release
Hit:6 http://ppa.launchpad.net/noobslab/apps/ubuntu bionic InRelease
Hit:7 https://download.docker.com/linux/ubuntu bionic InRelease
Hit:8 http://us.archive.ubuntu.com/ubuntu xenial InRelease
Hit:9 http://ppa.launchpad.net/teejee2008/ppa/ubuntu bionic InRelease
Get:10 http://us.archive.ubuntu.com/ubuntu xenial-updates InRelease [109 kB]
Hit:11 http://ppa.launchpad.net/ubuntu-toolchain-r/test/ubuntu bionic InRelease
Ign:13 http://ppa.launchpad.net/upubuntu-com/ppa/ubuntu bionic InRelease
Err:14 http://ppa.launchpad.net/upubuntu-com/ppa/ubuntu bionic Release
404 Not Found [IP: 91.189.95.83 80]
Reading package lists... Done
E: The repository 'http://ppa.launchpad.net/upubuntu-com/ppa/ubuntu bionic Release' does not have a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
dex@dexpc:~$ sudo apt-get install gcc-5.9 g++-5.9
Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package gcc-5.9
E: Couldn't find any package by glob 'gcc-5.9'
E: Couldn't find any package by regex 'gcc-5.9'
E: Unable to locate package g++-5.9
E: Couldn't find any package by glob 'g++-5.9'
E: Couldn't find any package by regex 'g++-5.9'
dex@dexpc:~$ gcc --version
gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0
| Two steps to fix the problem:
1)
There should be a copy of sources.list at /usr/share/doc/apt/examples/sources.list Copy your /etc/apt/sources.list to save the ppa changes you entered and start with the fresh copy. Then run the
sudo apt-get update
sudo apt-get dist-upgrade
Then add in your ppas from your saved copy of sources list, and repeat the
sudo apt-get update
sudo apt-get dist-upgrade
Just in case, here's the contents of the fresh file:
# See sources.list(5) manpage for more information
# Remember that CD-ROMs, DVDs and such are managed through the apt-cdrom tool.
deb http://us.archive.ubuntu.com/ubuntu xenial main restricted
deb-src http://us.archive.ubuntu.com/ubuntu xenial main restricted
deb http://security.ubuntu.com/ubuntu xenial-security main restricted
deb-src http://security.ubuntu.com/ubuntu xenial-security main restricted
deb http://us.archive.ubuntu.com/ubuntu xenial-updates main restricted
deb-src http://us.archive.ubuntu.com/ubuntu xenial-updates main restricted
2) To get rif off obsolete ppa
sudo apt-add-repository -r ppa:armagetronad-dev/ppa
sudo apt update -q
| https://stackoverflow.com/questions/52264375/ |
Pytorch saving and loading a VGG16 with knowledge transfer | I am saving a VGG16 with knowledge transfer by using the following statement:
torch.save(model.state_dict(), 'checkpoint.pth')
and reloading by using the following statement:
state_dict = torch.load('checkpoint.pth')
model.load_state_dict(state_dict)
That works as long as I reload the VGG16 model and give it the same settings as before with the following code:
model = models.vgg16(pretrained=True)
model.cuda()
for param in model.parameters(): param.requires_grad = False
class Network(nn.Module):
def __init__(self, input_size, output_size, hidden_layers, drop_p=0.5):
# input_size: integer, size of the input
# output_size: integer, size of the output layer
# hidden_layers: list of integers, the sizes of the hidden layers
# drop_p: float between 0 and 1, dropout probability
super().__init__()
# Add the first layer, input to a hidden layer
self.hidden_layers = nn.ModuleList([nn.Linear(input_size, hidden_layers[0])])
# Add a variable number of more hidden layers
layer_sizes = zip(hidden_layers[:-1], hidden_layers[1:])
self.hidden_layers.extend([nn.Linear(h1, h2) for h1, h2 in layer_sizes])
self.output = nn.Linear(hidden_layers[-1], output_size)
self.dropout = nn.Dropout(p=drop_p)
def forward(self, x):
''' Forward pass through the network, returns the output logits '''
# Forward through each layer in `hidden_layers`, with ReLU activation and dropout
for linear in self.hidden_layers:
x = F.relu(linear(x))
x = self.dropout(x)
x = self.output(x)
return F.log_softmax(x, dim=1)
classifier = Network(25088, 102, [4096], drop_p=0.5)
model.classifier = classifier
How to avoid this?
How can I reload the model without having to reload a VGG16 and redefine a classifier?
| Why not redefine a VGG16 like model directly?
view vgg.py for detail
class VGG_New(nn.Module):
def __init__(self, features, num_classes=1000, init_weights=True):
super(VGG, self).__init__()
self.features = features
# change here with you code
self.classifier = nn.Sequential(
nn.Linear(512 * 7 * 7, 4096),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(True),
nn.Dropout(),
nn.Linear(4096, num_classes),
)
if init_weights:
self._initialize_weights()
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
return x
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
if m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
nn.init.normal_(m.weight, 0, 0.01)
nn.init.constant_(m.bias, 0)
then load weight for features only
pretrained_dict=torch.load(vgg_weight)
model_dict=vgg_new.state_dict()
# 1. filter out unnecessary keys
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
# or filter with key value
# pretrained_dict = {k: v for k, v in pretrained_dict.items() if k.find('classifier')==-1}
# 2. overwrite entries in the existing state dict
model_dict.update(pretrained_dict)
vgg_new.load_state_dict(model_dict)
| https://stackoverflow.com/questions/52268048/ |
Assign Torch and Tensorflow models two separate GPUs | I am comparing two pre-trained models, one is in Tensorflow and one is in Pytorch, on a machine that has multiple GPUs. Each model fits on one GPU. They are both loaded in the same Python script. How can I assign one GPU to the Tensorflow model and another GPU to the Pytorch model?
Setting CUDA_VISIBLE_DEVICES=0,1 only tells both models that these GPUs are available - how can I (within Python I guess), make sure that Tensorflow takes GPU 0 and Pytorch takes GPU 1?
| You can refer to torch.device. https://pytorch.org/docs/stable/tensor_attributes.html?highlight=device#torch.torch.device
In particular do
device=torch.device("gpu:0")
tensor = tensor.to(device)
or to load a pretrained model
device=torch.device("gpu:0")
model = model.to(device)
to put tensor/model on gpu 0.
Similarly tensorflow has tf.device. https://www.tensorflow.org/api_docs/python/tf/device. Its usage is described here https://www.tensorflow.org/guide/using_gpu
for tensorflow to load model on gpu:0 do,
with tf.device("gpu:0"):
load_model_function(model_path)
| https://stackoverflow.com/questions/52273113/ |
Pytorch saving model UserWarning: Couldn't retrieve source code for container of type Network | When saving model in Pytorch by using:
torch.save(model, 'checkpoint.pth')
I get the following warning:
/opt/conda/lib/python3.6/site-packages/torch/serialization.py:193:
UserWarning: Couldn't retrieve source code for container of type
Network. It won't be checked for correctness upon loading. "type " +
obj.name + ". It won't be checked "
When I load it I get the following error:
state_dict = torch.load('checkpoint_state_dict.pth')
model = torch.load('checkpoint.pth')
model.load_state_dict(state_dict)
AttributeError Traceback (most recent call last)
<ipython-input-2-6a79854aef0f> in <module>()
2 state_dict = torch.load('checkpoint_state_dict.pth')
3 model = 0
----> 4 model = torch.load('checkpoint.pth')
5 model.load_state_dict(state_dict)
/opt/conda/lib/python3.6/site-packages/torch/serialization.py in load(f, map_location, pickle_module)
301 f = open(f, 'rb')
302 try:
--> 303 return _load(f, map_location, pickle_module)
304 finally:
305 if new_fd:
/opt/conda/lib/python3.6/site-packages/torch/serialization.py in _load(f, map_location, pickle_module)
467 unpickler = pickle_module.Unpickler(f)
468 unpickler.persistent_load = persistent_load
--> 469 result = unpickler.load()
470
471 deserialized_storage_keys = pickle_module.load(f)
AttributeError: Can't get attribute 'Network' on <module '__main__'>
Why is not possible to save a model and reload it entirely?
| Saving
torch.save({'state_dict': model.state_dict()}, 'checkpoint.pth.tar')
Loading
model = describe_model()
checkpoint = torch.load('checkpoint.pth.tar')
model.load_state_dict(checkpoint['state_dict'])
| https://stackoverflow.com/questions/52277083/ |
How do deep learning frameworks such as PyTorch handle memory when using multiple GPUs? | I have recently run into a situation where I am running out of memory on a single Nvidia V100. I have limited experience using multiple GPUs to train networks so I'm a little unsure on how the data parallelization process works. Lets say I'm using a model and batch size that requires something like 20-25GB of memory. Is there any way to take advantage of the full 32GB of memory I have between two 16GB V100s? Would PyTorch's DataParallel functionality achieve this? I suppose there is also the possibility of breaking the model up and using model parallelism as well. Please excuse my lack of knowledge on this subject. Thanks in advance for any help or clarification!
| You should keep model parallelism as your last resource and only if your model doesn't fit in the memory of a single GPU (with 16GB/GPU you have plenty of room for a gigantic model).
If you have two GPUs, I would use data parallelism. In data parallelism you have a copy of your model on each GPU and each copy is fed with a batch. The gradients are then gathered and used to update the copies.
Pytorch makes it really easy to achieve data parallelism, as you just need to wrap you model instance in nn.DataParallel:
model = torch.nn.DataParallel(model, device_ids=[0, 1])
output = model(input_var)
| https://stackoverflow.com/questions/52285621/ |
How do I use torch.stack? | How do I use torch.stack to stack two tensors with shapes a.shape = (2, 3, 4) and b.shape = (2, 3) without an in-place operation?
| Stacking requires same number of dimensions. One way would be to unsqueeze and stack. For example:
a.size() # 2, 3, 4
b.size() # 2, 3
b = torch.unsqueeze(b, dim=2) # 2, 3, 1
# torch.unsqueeze(b, dim=-1) does the same thing
torch.stack([a, b], dim=2) # 2, 3, 5
| https://stackoverflow.com/questions/52288635/ |
Pytorch: List of layers returns 'optimizer got an empty parameter list' | I have a defined model and defined layer, I add n instances of my defined layer to a list in the init function of my model as follow:
self.layers = []
for i in range(len(nhid)-1):
self.layers.append(MyLayer(nhid[i], nhid[i+1]))
but when I create optimizer by
optim.Adam(model.parameters(),lr=args.lr, weight_decay=args.weight_decay)
it says:
ValueError: optimizer got an empty parameter list
But when I write it for two layers as follow I got no error:
self.layer1 = MyLayer[nhid[0],nhid[1]]
self.layer2 = MyLayer[nhid[1],nhid[2]]
| I solved the problem by using nn.ModuleList() as follow:
temp = []
for i in range(len(nhid)-1):
temp.append(MyLayer(nhid[i], nhid[i+1]))
self.layers = nn.ModuleList(temp)
I also read about nn.Sequential(), but I didn't find out how to use it in a correct way.
| https://stackoverflow.com/questions/52298179/ |
PyTorch autograd -- grad can be implicitly created only for scalar outputs | I am using the autograd tool in PyTorch, and have found myself in a situation where I need to access the values in a 1D tensor by means of an integer index. Something like this:
def basic_fun(x_cloned):
res = []
for i in range(len(x)):
res.append(x_cloned[i] * x_cloned[i])
print(res)
return Variable(torch.FloatTensor(res))
def get_grad(inp, grad_var):
A = basic_fun(inp)
A.backward()
return grad_var.grad
x = Variable(torch.FloatTensor([1, 2, 3, 4, 5]), requires_grad=True)
x_cloned = x.clone()
print(get_grad(x_cloned, x))
I am getting the following error message:
[tensor(1., grad_fn=<ThMulBackward>), tensor(4., grad_fn=<ThMulBackward>), tensor(9., grad_fn=<ThMulBackward>), tensor(16., grad_fn=<ThMulBackward>), tensor(25., grad_fn=<ThMulBackward>)]
Traceback (most recent call last):
File "/home/mhy/projects/pytorch-optim/predict.py", line 74, in <module>
print(get_grad(x_cloned, x))
File "/home/mhy/projects/pytorch-optim/predict.py", line 68, in get_grad
A.backward()
File "/home/mhy/.local/lib/python3.5/site-packages/torch/tensor.py", line 93, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/home/mhy/.local/lib/python3.5/site-packages/torch/autograd/__init__.py", line 90, in backward
allow_unreachable=True) # allow_unreachable flag
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
I am in general, a bit skeptical about how using the cloned version of a variable is supposed to keep that variable in gradient computation. The variable itself is effectively not used in the computation of A, and so when you call A.backward(), it should not be part of that operation.
I appreciate your help with this approach or if there is a better way to avoid losing the gradient history and still index through a 1D tensor with requires_grad=True!
**Edit (September 15):**
res is a list of zero-dimensional tensors containing squared values of 1 to 5. To concatenate in a single tensor containing [1.0, 4.0, ..., 25.0], I changed return Variable(torch.FloatTensor(res)) to torch.stack(res, dim=0), which produces tensor([ 1., 4., 9., 16., 25.], grad_fn=<StackBackward>).
However, I am getting this new error, caused by the A.backward() line.
Traceback (most recent call last):
File "<project_path>/playground.py", line 22, in <module>
print(get_grad(x_cloned, x))
File "<project_path>/playground.py", line 16, in get_grad
A.backward()
File "/home/mhy/.local/lib/python3.5/site-packages/torch/tensor.py", line 93, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/home/mhy/.local/lib/python3.5/site-packages/torch/autograd/__init__.py", line 84, in backward
grad_tensors = _make_grads(tensors, grad_tensors)
File "/home/mhy/.local/lib/python3.5/site-packages/torch/autograd/__init__.py", line 28, in _make_grads
raise RuntimeError("grad can be implicitly created only for scalar outputs")
RuntimeError: grad can be implicitly created only for scalar outputs
| I changed my basic_fun to the following, which resolved my problem:
def basic_fun(x_cloned):
res = torch.FloatTensor([0])
for i in range(len(x)):
res += x_cloned[i] * x_cloned[i]
return res
This version returns a scalar value.
| https://stackoverflow.com/questions/52317407/ |
Linear Regression with CNN using Pytorch: input and target shapes do not match: input [400 x 1], target [200 x 1] | Let me explain the objective first. Let's say I have 1000 images each with an associated quality score [in range of 0-10]. Now, I am trying to perform the image quality assessment using CNN with regression(in PyTorch). I have divided the images into equal size patches. Now, I have created a CNN network in order to perform the linear regression.
Following is the code:
class MultiLabelNN(nn.Module):
def __init__(self):
super(MultiLabelNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(32, 64, 5)
self.fc1 = nn.Linear(3200,1024)
self.fc2 = nn.Linear(1024, 512)
self.fc3 = nn.Linear(512, 1)
def forward(self, x):
x = self.conv1(x)
x = F.relu(x)
x = self.pool(x)
x = self.conv2(x)
x = F.relu(x)
x = x.view(-1, 3200)
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return x
While running this code of network I am getting following error
input and target shapes do not match: input [400 x 1], target [200 x 1]
the target shape is [200x1] is because I have taken the batch size of 200. I found the solution that if I change "self.fc1 = nn.Linear(3200,1024)" and "x = x.view(-1, 3200)" here from 3200 to 6400 my code runs without any error.
Similarly, It will throw an error input and target shapes do not match: input [100 x 1], target [200 x 1] if I put 12800 instead of 6400
Now my doubt is that I am not able to understand the reason behind this. If I am giving 200 images as input to my network then why the input shape is getting affected while changing the parameters when I move from convolutional layer to fully connected layer. I hope I have clearly mentioned my doubt. Even though I anybody has any doubt please ask me. It will be a great help. Thanks in advance.
| class MultiLabelNN(nn.Module):
def __init__(self):
super(MultiLabelNN, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(32, 64, 5)
self.fc1 = nn.Linear(6400,1024)
self.fc2 = nn.Linear(1024, 512)
self.fc3 = nn.Linear(512, 1)
def forward(self, x):
#shape of x is (b_s, 32,32,1)
x = self.conv1(x) #shape of x is (b_s, 28,28,132)
x = F.relu(x)
x = self.pool(x) #shape of x now becomes (b_s X 14 x 14 x 32)
x = self.conv2(x) # shape(b_s, 10x10x64)
x = F.relu(x)#size is (b_s x 10 x 10 x 64)
x = x.view(-1, 3200) # shape of x is now(b_s*2, 3200)
#this is the problem
#you can fc1 to be of shape (6400,1024) and that will work
x = self.fc1(x)
x = F.relu(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return x
I think this should work. Let me know if some errors still remain.
| https://stackoverflow.com/questions/52324713/ |
How is a 3-d tensor indexed by two 2d tensors? | Here's a snapshot from line 15-20 in DIM
def random_permute(X):
X = X.transpose(1, 2)
b = torch.rand((X.size(0), X.size(1))).cuda()
idx = b.sort(0)[1]
adx = torch.range(0, X.size(1) - 1).long()
X = X[idx, adx[None, :]].transpose(1, 2)
return X
where X is a tensor of size [64, 64, 128], idx a tensor of size [64, 64], adx a tensor of size [64].
How does X = X[idx, adx[None, :]] work? How can we use two 2d tensors to index a 3d tensor? What really happens to X after this indexing?
| Things will be more clear if we consider a smaller concrete example. Let
x = np.arange(8).reshape(2, 2, 2)
b = np.random.rand(2, 2)
idx = b.argsort(0) # e.g. idx=[[1, 1], [0, 0]]
adx = np.arange(2)[None, :] # [[0, 1]]
y = x[idx, adx] # implicitly expanding 'adx' to [[0, 1], [0, 1]]
In this example, we'll have y as
y[0, 0] = x[idx[0, 0], adx[0, 0]]=x[1, 0]
y[0, 1] = x[idx[0, 1], adx[0, 1]]=x[1, 1]
y[1, 0] = x[idx[1, 0], adx[1, 0]]=x[0, 0]
...
It may be helpful to see how we do the same in tensorflow:
d0, d1, d2 = x.shape.as_list()
b = np.random.rand(d0, d1)
idx = np.argsort(b, 0)
idx = idx.reshape(-1)
adx = np.arange(0, d1)
adx = np.tile(adx, d0)
y = tf.reshape(tf.gather_nd(x, zip(idx, adx)), (d0, d1, d2))
| https://stackoverflow.com/questions/52342514/ |
Pytorch: Size Mismatch during running a test image through a trained CNN | I am going through tutorials to train/test a convolutional neural network(CNN), and I am having an issue with prepping a test image to run it through the trained network. My initial guess is that it has something to do with having a correct format of the tensor input for the net.
Here is the code for the Net.
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as I
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
## 1. This network takes in a square (same width and height), grayscale image as input
## 2. It ends with a linear layer that represents the keypoints
## this last layer output 136 values, 2 for each of the 68 keypoint (x, y) pairs
# input size 224 x 224
# after the first conv layer, (W-F)/S + 1 = (224-5)/1 + 1 = 220
# after one pool layer, this becomes (32, 110, 110)
self.conv1 = nn.Conv2d(1, 32, 5)
# maxpool layer
# pool with kernel_size = 2, stride = 2
self.pool = nn.MaxPool2d(2,2)
# second conv layer: 32 inputs, 64 outputs , 3x3 conv
## output size = (W-F)/S + 1 = (110-3)/1 + 1 = 108
## output dimension: (64, 108, 108)
## after another pool layer, this becomes (64, 54, 54)
self.conv2 = nn.Conv2d(32, 64, 3)
# third conv layer: 64 inputs, 128 outputs , 3x3 conv
## output size = (W-F)/S + 1 = (54-3)/1 + 1 = 52
## output dimension: (128, 52, 52)
## after another pool layer, this becomes (128, 26, 26)
self.conv3 = nn.Conv2d(64,128,3)
self.conv_drop = nn.Dropout(p = 0.2)
self.fc_drop = nn.Dropout(p = 0.4)
# 64 outputs * 5x5 filtered/pooled map = 186624
self.fc1 = nn.Linear(128*26*26, 1000)
#
self.fc2 = nn.Linear(1000, 1000)
self.fc3 = nn.Linear(1000, 136)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = self.pool(F.relu(self.conv3(x)))
x = self.conv_drop(x)
# prep for linear layer
# flattening
x = x.view(x.size(0), -1)
# two linear layers with dropout in between
x = F.relu(self.fc1(x))
x = self.fc_drop(x)
x = self.fc2(x)
x = self.fc_drop(x)
x = self.fc3(x)
return x
Maybe my calculation in layer inputs is wrong?
And here is the test-running code block: (you can think of 'roi' as a standard numpy image.)
# loop over the detected faces from your haar cascade
for i, (x,y,w,h) in enumerate(faces):
plt.figure(figsize=(10,5))
ax = plt.subplot(1, len(faces), i+1)
# Select the region of interest that is the face in the image
roi = image_copy[y:y+h, x:x+w]
## TODO: Convert the face region from RGB to grayscale
roi = cv2.cvtColor(roi, cv2.COLOR_RGB2GRAY)
## TODO: Normalize the grayscale image so that its color range falls in [0,1] instead of [0,255]
roi = np.multiply(roi, 1/255)
## TODO: Rescale the detected face to be the expected square size for your CNN (224x224, suggested)
roi = cv2.resize(roi, (244,244))
roi = roi.reshape(roi.shape[0], roi.shape[1], 1)
roi = roi.transpose((2, 0, 1))
## TODO: Change to tensor
roi = torch.from_numpy(roi)
roi = roi.type(torch.FloatTensor)
roi = roi.unsqueeze(0)
print (roi.shape)
## TODO: run it through the net
output_pts = net(roi)
And I get the error message saying:
RuntimeError: size mismatch, m1: [1 x 100352], m2: [86528 x 1000] at /opt/conda/conda-bld/pytorch_1524584710464/work/aten/src/TH/generic/THTensorMath.c:2033
The caveat is if I run my trained network in the provided test suite (where the tensor inputs are already prepped), it gives no errors there and runs as it is supposed to. I think that means there's nothing wrong with the design of the network architecture itself. I think there's something wrong with the way that I am prepping the image.
The output of the 'roi.shape' is:
torch.Size([1, 1, 244, 244])
Which should be okay because ([batch_size, color_channel, x, y]).
UPDATE: I have printed out the shape of the layers during running through the net. It turns out the matching input dimensions for FC are different for the test image for the task and the given test images from the test suite. Then I'm almost 80% sure that my prepping the input image for the net is wrong. But how can they have different matching dimensions if the input tensor for both has the exact same dimension ([1,1,244,244])?
when using the provided test suite (where it runs fine):
input: torch.Size([1, 1, 224, 224])
layer before 1st CV: torch.Size([1, 1, 224, 224])
layer after 1st CV pool: torch.Size([1, 32, 110, 110])
layer after 2nd CV pool: torch.Size([1, 64, 54, 54])
layer after 3rd CV pool: torch.Size([1, 128, 26, 26])
flattend layer for the 1st FC: torch.Size([1, 86528])
When prepping/running the test image:
input: torch.Size([1, 1, 244, 244])
layer before 1st CV: torch.Size([1, 1, 244, 244])
layer after 1st CV pool: torch.Size([1, 32, 120, 120]) #<- what happened here??
layer after 2nd CV pool: torch.Size([1, 64, 59, 59])
layer after 3rd CV pool: torch.Size([1, 128, 28, 28])
flattend layer for the 1st FC: torch.Size([1, 100352])
| Did you noticed you have this line in the image preparation.
## TODO: Rescale the detected face to be the expected square size for your CNN (224x224, suggested)
roi = cv2.resize(roi, (244,244))
so you just resized it to 244x244 and not to 224x224.
| https://stackoverflow.com/questions/52358887/ |
Perform a batch matrix - multiple weight matrices multiplications in pytorch | I have a batch of matrices A with size torch.Size([batch_size, 9, 5]) and weight matrices B with size torch.Size([3, 5, 6]). In Keras, a simple K.dot(A, B) is able to handle the matrix multiplication to give an output with size (batch_size, 9, 3, 6). Here, each row in A is multiplied to the 3 matrices in B to form a (3x6) matrix.
How do you perform a similar operation in torch. From the documentation, torch.bmm requires that A and B must have the same batch size, so I tried this:
B = B.unsqueeze(0).repeat((batch_size, 1, 1, 1))
B.size() # torch.Size([batch_size, 3, 5, 6])
torch.bmm(A,B) # gives an error
RuntimeError: invalid argument 2: expected 3D tensor, got 4D
Well, the error is expected but how do I perform such an operation?
| You can use einstein notation to describe the operation you want as bxy,iyk->bxik. So, you can use einsum to calculate it.
torch.einsum('bxy,iyk->bxik', (A, B)) will give you the answer you want.
| https://stackoverflow.com/questions/52361735/ |
Changing the np array does not change the Torch Tensor automatically? | I was going through the basic tutorials of PyTorch and came across conversion between NumPy arrays and Torch tensors. The documentation says:
The Torch Tensor and NumPy array will share their underlying memory locations, and changing one will change the other.
But, this does not seem to be the case in the below code:
import numpy as np
a = np.ones((3,3))
b = torch.from_numpy(a)
np.add(a,1,out=a)
print(a)
print(b)
In the above case I see the changes automatically reflected in the output:
[[2. 2. 2.]
[2. 2. 2.]
[2. 2. 2.]]
tensor([[2., 2., 2.],
[2., 2., 2.],
[2., 2., 2.]], dtype=torch.float64)
But same doesn't happen when I write something like this:
a = np.ones((3,3))
b = torch.from_numpy(a)
a = a + 1
print(a)
print(b)
I get the following output:
[[2. 2. 2.]
[2. 2. 2.]
[2. 2. 2.]]
tensor([[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]], dtype=torch.float64)
What am I missing here?
| Any time you write a = sign in Python you are creating a new object.
So the right-hand side of your expression in the second case uses the original a and then evaluates to a new object i.e. a + 1, which replaces this original a. b still points to the memory location of the original a, but now a points to a new object in memory.
In other words, in a = a + 1, the expression a + 1 creates a new object, and then Python assigns that new object to the name a.
Whereas, with a += 1, Python calls a's in-place addition method (__iadd__) with the argument 1.
The numpy code: np.add(a,1,out=a) , in the first case takes care of adding that value to the existing array in-place.
(Thanks to @Engineero and @Warren Weckesser for pointing out these explanations in the comments)
| https://stackoverflow.com/questions/52374062/ |
Compile PyTorch with additional linker options | I have a modified version of the gloo library. I am able to compile and run programs that use this library (similar to what you can find in gloo/gloo/examples).
Now, I want to build pytorch with my library.
I replaced the third_party/gloo folder in PyTorch with my version of gloo and I am trying to compile it.
However, my version of gloo requires some additional libraries and special linker options. Where should these linker options be added in the pytorch build system?
Without these linker options, my compilation stops with the linker error:
/pytorch/build/lib/libcaffe2_gpu.so: undefined reference to <my code>
/pytorch/build/lib/libcaffe2.so: undefined reference to <my code>
| The additional linker options should be added to:
the Caffe2_DEPENDENCY_LIBS variable in pytorch/caffe2/CMakeLists.txt with the command:
list(APPEND Caffe2_DEPENDENCY_LIBS <linker_options>)
the C10D_LIBS variable in pytorch/torch/lib/c10d/CMakeLists.txt with the command:
list(APPEND C10D_LIBS <linker_options>)
The additional libraries should have Position Independent Code (they must be compiled with the -fPIC flag).
| https://stackoverflow.com/questions/52384628/ |
How does a 2x2 deconv kernel with stride=2 work? | For example, if the feature map is 8x8, than I use such a deconv and the feature map becomes 16x16, I'm confused that what the difference between:
deconv(kernel_size=2, stride=2, padding='valid')
and
deconv(kernel_size=3, stride=2, padding='same')
Since they will both make feature map 2 times larger, how do they work respectively?
| I think you'll find the explanations and interactive demo on this web page very helpful.
Specifically, setting stride=2 will double your output shape regardless of kernel size.
kernel_size determine how many output pixels are affected by each input pixel.
Setting stride=2 and kernel_size=2 simply "duplicates" your kernel on the output. Consider this 1D example. Suppose your kernel is [a, b] and your input is [A, B, ...], then the output is
[A*a, A*b, B*a, B*b, ...]
For kernel_size=3, the output becomes
[A*a, A*b, A*c+B*a, B*b, B*c+C*a, ...]
| https://stackoverflow.com/questions/52401088/ |
Expected tensor for argument #1 'input' to have the same dimension | Using below code I create 10 instances of each training data of which each has 100 dimensions.
Each of the 100 dimension contains 3 dimensions. Therefore it's shape is : (3, 100, 10). This emulates 10 instances of 100 pixels each with 3 channels to emulate an RGB value
I've set this model to just classify between 1 and 0.
When applying the softmax layer I receive the error :
RuntimeError: Expected tensor for argument #1 'input' to have the same
dimension as tensor for 'result'; but 4 does not equal 3 (while
checking arguments for cudnn_convolution)
I'm using 0.4.0 (checked using print(torch.__version__) )
How to correctly set the dimension for the softmax layer? As I think my dimensions are correct?
%reset -f
import os
import torch
from skimage import io, transform
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
import torch.utils.data as data_utils
import torchvision
import numpy as np
from sklearn.preprocessing import scale
import torch.nn.functional as F
import torch.nn as nn
import torch.nn.functional as F
from random import randint
batch_size_value = 10
train_dataset = []
mu, sigma = 0, 0.1 # mean and standard deviation
num_instances = 10
# Create 3000 instance and reshape to (3 , 100, 10) , this emulates 10 instances of 100 pixels
# each with 3 channels to emulate an RGB value
for i in range(num_instances) :
image = []
image_x = np.random.normal(mu, sigma, 3000).reshape((3 , 100, 10))
train_dataset.append(image_x)
mu, sigma = 100, 0.80 # mean and standard deviation
for i in range(num_instances) :
image = []
image_x = np.random.normal(mu, sigma, 3000).reshape((3 , 100, 10))
train_dataset.append(image_x)
labels_1 = [1 for i in range(num_instances)]
labels_0 = [0 for i in range(num_instances)]
labels = labels_1 + labels_0
print(labels)
x2 = torch.tensor(train_dataset).float()
y2 = torch.tensor(labels).long()
my_train2 = data_utils.TensorDataset(x2, y2)
train_loader2 = data_utils.DataLoader(my_train2, batch_size=batch_size_value, shuffle=False)
# print(x2)
# Device configuration
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
print('device' , device)
# device = 'cpu'
# Hyper parameters
num_epochs = 10
num_classes = 2
batch_size = 5
learning_rate = 0.001
# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, kernel_size=5)
self.conv2 = nn.Conv2d(6, 16, kernel_size=5)
self.fc1 = nn.Linear(864, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, num_classes)
def forward(self, x):
out = F.relu(self.conv1(x))
out = F.max_pool2d(out, 2)
out = F.relu(self.conv2(out))
out = F.max_pool2d(out, 2)
out = out.view(out.size(0), -1)
out = F.relu(self.fc1(out))
out = F.relu(self.fc2(out))
out = self.fc3(out)
model = ConvNet().to(device)
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
total_step = len(train_loader2)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader2):
images = images.to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
# print(images)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i % 10) == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
Update :
Removing these lines :
out = F.relu(self.conv2(out))
out = F.max_pool2d(out, 2)
fixes issue of dimensions being smaller than kernel.
| There is one structured problem and one bug in your code. Here is the solution.
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.conv1 = nn.Conv2d(3, 6, kernel_size=5)
self.conv2 = nn.Conv2d(6, 16, kernel_size=1) # kernel_size 5----> 1
self.fc1 = nn.Linear(384, 120) # FC NodeCount864--> 384
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, num_classes)
def forward(self, x):
out = F.relu(self.conv1(x))
out = F.max_pool2d(out, 2)
out = F.relu(self.conv2(out))
out = F.max_pool2d(out, 2)
out = out.view(out.size(0), -1)
out = F.relu(self.fc1(out))
out = F.relu(self.fc2(out))
out = self.fc3(out)
return out # Don't forget to return the output
| https://stackoverflow.com/questions/52408753/ |
TypeError: unhashable type: 'list' when calling .iloc() | I'm currently doing some AI research for a project and for that I have to get used to a framework called "Pytorch". That's fine and all but following the official tutorial (found here) the code doesn't run properly.
The idea is that I analyse a set of facial features from a prepared dataset and then do something with it (haven't gotten to that part yet). But when I run this piece of code:
img_name = os.path.join(self.root_dir, self.landmarks_frame.iloc([index, 0])) # At this point 'index' is 0
The dataset is initialized like this:
face_dataset = fDataset(csv_file='faces/face_landmarks.csv', root_dir='faces/')
And here is where the error pops up:
for i in range(len(face_dataset)):
sample = face_dataset[i] # <-- right there
That leads to the getter function:
def __getitem__(self, index):
img_name = os.path.join(self.root_dir, self.landmarks_frame.iloc([index, 0]))
image = io.imread(img_name)
landmarks = self.landmarks_frame.iloc[index, 1:].as_matrix()
landmarks = landmarks.astype('float').reshape(-1, 2)
sample = {'image': image, 'landmarks': landmarks}
Found in my FaceLandmarksDataset(Dataset): class I simply get the error of the title. This is strange I find, because I can read the dataset just fine as a frame in PyCharm:
Where the first picture is clearly visible. I have checked as well that it is in the folder that I'm looking in.
Can anyone help out? :)
| You don't need the parentheses with iloc:
self.landmarks_frame.iloc[index, 0]
| https://stackoverflow.com/questions/52428472/ |
NVidia 1080ti eGPU Ubuntu 16.04.5 LTS - PyTorch / Tensorflow without root permissions | I have some trouble in setting up my system properly. My system consists of:
Intel NUC7i7BNH
ASUS ROG with a NVidia 1080ti
My GPU is correctly detected by lspci:
06:00.0 VGA compatible controller: NVIDIA Corporation Device 1b06 (rev a1) (prog-if 00 [VGA controller])
Subsystem: ASUSTeK Computer Inc. Device 85ea
Control: I/O+ Mem+ BusMaster+ SpecCycle- MemWINV- VGASnoop- ParErr- Stepping- SERR- FastB2B- DisINTx-
Status: Cap+ 66MHz- UDF- FastB2B- ParErr- DEVSEL=fast >TAbort- <TAbort- <MAbort- >SERR- <PERR- INTx-
Latency: 0, Cache Line Size: 128 bytes
Interrupt: pin A routed to IRQ 18
Region 0: Memory at c4000000 (32-bit, non-prefetchable) [size=16M]
Region 1: Memory at a0000000 (64-bit, prefetchable) [size=256M]
Region 3: Memory at b0000000 (64-bit, prefetchable) [size=32M]
Region 5: I/O ports at 2000 [size=128]
Expansion ROM at c5000000 [disabled] [size=512K]
Capabilities: <access denied>
Kernel driver in use: nvidia
Kernel modules: nvidiafb, nouveau, nvidia_384_drm, nvidia_384
and with the commands below I installed drivers for the GPU, CUDA and cuDNN:
# Show thunderbolt port / authorize eGPU
$ cat /sys/bus/thunderbolt/devices/0-1/device_name
$ echo 1 | sudo tee -a /sys/bus/thunderbolt/devices/0-1/authorized
# eGPU - on Ubuntu 16.04 - nvidia-384
$ sudo ubuntu-drivers devices
$ sudo ubuntu-drivers autoinstall
$ sudo apt-get install nvidia-modprobe
# CUDA - Download CUDA from Nvidia - http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/
$ wget https://developer.nvidia.com/compute/cuda/9.0/Prod/local_installers/cuda_9.0.176_384.81_linux-run
$ chmod +x cuda_9.0.176_384.81_linux-run
$ ./cuda_9.0.176_384.81_linux-run --extract=$HOME
$ sudo ./cuda-linux.9.0.176-22781540.run
$ sudo ./cuda-samples.9.0.176-22781540-linux.run
$ sudo bash -c "echo /usr/local/cuda/lib64/ > /etc/ld.so.conf.d/cuda.conf"
$ sudo ldconfig
# add :/usr/local/cuda/bin (including the ":") at the end of the PATH="/blah:/blah/blah" string (inside the quotes).
$ sudo nano /etc/environments
# CUDA samples - Check installation
$ cd /usr/local/cuda-9.0/samples
$ sudo make
$ /usr/local/cuda/samples/bin/x86_64/linux/release/deviceQuery
# cuDNN
$ wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/libcudnn7_7.0.5.15-1+cuda9.0_amd64.deb
$ dpkg -i libcudnn7_7.0.5.15-1+cuda9.0_amd64.deb
# Authorization (Security risk!)
$ sudo nano /etc/udev/rules.d/99-local.rules
# Add
ACTION=="add", SUBSYSTEM=="thunderbolt", ATTR{authorized}=="0", ATTR{authorized}="1"
With sudo prime-select nvidia I can switch between the eGPU and the Intel integrated one. After a logout + login the eGPU seems to work (nvidia-smi):
Fri Sep 21 09:25:18 2018
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 384.130 Driver Version: 384.130 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC |
| Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. |
|===============================+======================+======================|
| 0 GeForce GTX 108... Off | 00000000:06:00.0 Off | N/A |
| 0% 47C P0 84W / 275W | 214MiB / 11172MiB | 4% Default |
+-------------------------------+----------------------+----------------------+
+-----------------------------------------------------------------------------+
| Processes: GPU Memory |
| GPU PID Type Process name Usage |
|=============================================================================|
| 0 6734 G /usr/lib/xorg/Xorg 138MiB |
| 0 7081 G kwin_x11 23MiB |
| 0 7084 G /usr/bin/krunner 2MiB |
| 0 7092 G /usr/bin/plasmashell 47MiB |
+-----------------------------------------------------------------------------+
The CUDA samples work also:
$ /usr/local/cuda/samples/bin/x86_64/linux/release/deviceQuery
/usr/local/cuda/samples/bin/x86_64/linux/release/deviceQuery Starting...
CUDA Device Query (Runtime API) version (CUDART static linking)
Detected 1 CUDA Capable device(s)
Device 0: "GeForce GTX 1080 Ti"
CUDA Driver Version / Runtime Version 9.0 / 9.0
CUDA Capability Major/Minor version number: 6.1
Total amount of global memory: 11172 MBytes (11715084288 bytes)
(28) Multiprocessors, (128) CUDA Cores/MP: 3584 CUDA Cores
GPU Max Clock rate: 1683 MHz (1.68 GHz)
Memory Clock rate: 5505 Mhz
Memory Bus Width: 352-bit
L2 Cache Size: 2883584 bytes
Maximum Texture Dimension Size (x,y,z) 1D=(131072), 2D=(131072, 65536), 3D=(16384, 16384, 16384)
Maximum Layered 1D Texture Size, (num) layers 1D=(32768), 2048 layers
Maximum Layered 2D Texture Size, (num) layers 2D=(32768, 32768), 2048 layers
Total amount of constant memory: 65536 bytes
Total amount of shared memory per block: 49152 bytes
Total number of registers available per block: 65536
Warp size: 32
Maximum number of threads per multiprocessor: 2048
Maximum number of threads per block: 1024
Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
Max dimension size of a grid size (x,y,z): (2147483647, 65535, 65535)
Maximum memory pitch: 2147483647 bytes
Texture alignment: 512 bytes
Concurrent copy and kernel execution: Yes with 2 copy engine(s)
Run time limit on kernels: Yes
Integrated GPU sharing Host Memory: No
Support host page-locked memory mapping: Yes
Alignment requirement for Surfaces: Yes
Device has ECC support: Disabled
Device supports Unified Addressing (UVA): Yes
Supports Cooperative Kernel Launch: Yes
Supports MultiDevice Co-op Kernel Launch: Yes
Device PCI Domain ID / Bus ID / location ID: 0 / 6 / 0
Compute Mode:
< Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >
deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 9.0, CUDA Runtime Version = 9.0, NumDevs = 1
Result = PASS
Let's come to the problem: The following snippet works only, if I execute python with root permissions.
$ python
Python 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 17:14:51)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
True
>>> torch.Tensor([0]).cuda()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: CUDA error: unknown error
vs.
$ sudo ~/miniconda3/envs/PyTorch/bin/python
Python 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 17:14:51)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
True
>>> torch.Tensor([0]).cuda()
tensor([0.], device='cuda:0')
TLDR:
My CUDA installation seems to work and my eGPU is correctly recognized by the system. However in PyTorch (and also Tensorflow) an 'Unknown Error' is thrown, when I try to move same data onto the eGPU, although it is recognized by the frameworks. When I execute the same code with root permissions everything works like a charm. Does somebody know, where I have to adopt some permissions, such that the code can be executed as standard user?
| After trying out different versions of the nvidia driver, I came to the conclusion, that there is a problem with version 384.
I deleted all nvidia driver related stuff via sudo apt-get purge nvidia. and installed version 390:
$ sudo add-apt-repository ppa:graphics-drivers/ppa
$ sudo ubuntu-drivers devices
$ sudo apt install nvidia-390
And here the result:
(PyTorch) max@MaxKubuntuNUC:~$ python
Python 3.6.6 |Anaconda, Inc.| (default, Jun 28 2018, 17:14:51)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
True
>>> torch.tensor([1]).cuda()
tensor([1], device='cuda:0')
Now everything works like a charm.
| https://stackoverflow.com/questions/52439295/ |
How to convert RGB images to grayscale in PyTorch dataloader? | I've downloaded some sample images from the MNIST dataset in .jpg format. Now I'm loading those images for testing my pre-trained model.
# transforms to apply to the data
trans = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
# MNIST dataset
test_dataset = dataset.ImageFolder(root=DATA_PATH, transform=trans)
# Data loader
test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
Here DATA_PATH contains a subfolder with the sample image.
Here's my network definition
# Convolutional neural network (two convolutional layers)
class ConvNet(nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.network2D = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=2),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Conv2d(32, 64, kernel_size=5, stride=1, padding=2),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.network1D = nn.Sequential(
nn.Dropout(),
nn.Linear(7 * 7 * 64, 1000),
nn.Linear(1000, 10))
def forward(self, x):
out = self.network2D(x)
out = out.reshape(out.size(0), -1)
out = self.network1D(out)
return out
And this is my inference part
# Test the model
model = torch.load("mnist_weights_5.pth.tar")
model.eval()
for images, labels in test_loader:
outputs = model(images.cuda())
When I run this code, I get the following error:
RuntimeError: Given groups=1, weight of size [32, 1, 5, 5], expected input[1, 3, 28, 28] to have 1 channels, but got 3 channels instead
I understand that the images are getting loaded as 3 channels (RGB). So how do I convert them to single channel in the dataloader?
Update:
I changed transforms to include Grayscale option
trans = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)), transforms.Grayscale(num_output_channels=1)])
But now I get this error
TypeError: img should be PIL Image. Got <class 'torch.Tensor'>
| I found an extremely simple solution to this problem. The required dimensions of the tensor are [1,1,28,28] whereas the input tensor is of the form [1,3,28,28]. So I need to read just 1 channel from it
images = images[:,0,:,:]
This gives me a tensor of the form [1,28,28]. Now I need to convert this to a tensor of the form [1,1,28,28]. Which can be done like this
images = images.unsqueeze(0)
So putting the above two lines together, the prediction part of the code can be written like this
for images, labels in test_loader:
images = images[:,0,:,:].unsqueeze(0) ## Extract single channel and reshape the tensor
outputs = model(images.cuda())
| https://stackoverflow.com/questions/52439364/ |
How does the reshape work before the fully connected layer in the following CNN model? | Consider the convolutional neural network (two convolutional layers):
class ConvNet(nn.Module):
def __init__(self, num_classes=10):
super(ConvNet, self).__init__()
self.layer1 = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.layer2 = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=5, stride=1, padding=2),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2, stride=2))
self.fc = nn.Linear(7*7*32, num_classes)
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = out.reshape(out.size(0), -1)
out = self.fc(out)
return out
The fully connected layer fc is to have 7*7*32 inputs coming in. The above:
out = out.reshape(out.size(0), -1) leads to a tensor with size of (32, 49).
This doesn't seem right as the dimensions of input for the dense layer is different. What am I missing here?
[Note that in Pytorch the input is in the following format: [N, C, W, H] so no. of channels comes before the width and height of image]
source: https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/02-intermediate/convolutional_neural_network/main.py#L35-L56
| If you look at the output of each layer you can easily understand what you are missing.
def forward(self, x):
print ('input', x.size())
out = self.layer1(x)
print ('layer1-output', out.size())
out = self.layer2(out)
print ('layer2-output', out.size())
out = out.reshape(out.size(0), -1)
print ('reshape-output', out.size())
out = self.fc(out)
print ('Model-output', out.size())
return out
test_input = torch.rand(4,1,28,28)
model(test_input)
OUTPUT:
('input', (4, 1, 28, 28))
('layer1-output', (4, 16, 14, 14))
('layer2-output', (4, 32, 7, 7))
('reshape-output', (4, 1568))
('Model-output', (4, 10))
Conv2d layer doesn't change the height and width of the tensor. only changes the channel of tensor because of stride and padding. MaxPool2d layer halves the height and width of the tensor.
inpt = 4,1,28,28
conv1_output = 4,16,28,28
max_output = 4,16,14,14
conv2_output = 4,32,14,14
max2_output = 4,32,7,7
reshapeutput = 4,1585 (32*7*7)
fcn_output = 4,10
N --> Input Size, F --> Filter Size, stride-> Stride Size, pdg-> Padding size
ConvTranspose2d;
OutputSize = N*stride + F - stride - pdg*2
Conv2d;
OutputSize = (N - F)/stride + 1 + pdg*2/stride [e.g. 32/3=10 it ignores after the comma]
| https://stackoverflow.com/questions/52451797/ |
Training on variable length data - EEG data classification | I'm a student working on a project involving using EEG data to perform lie detection. I will be working with raw EEG data from 2 channels and will record the EEG data during the duration that the subject is replying to the question. Thus, the data will be a 2-by-variable length array stored in a csv file, which holds the sensor readings from each of the two sensors. For example, it would look something like this:
Time (ms) | Sensor 1 | Sensor 2|
--------------------------------
10 | 100.2 | -324.5 |
20 | 123.5 | -125.8 |
30 | 265.6 | -274.9 |
40 | 121.6 | -234.3 |
....
2750 | 100.2 | -746.2 |
I want to predict, based on this data, whether the subject is lying or telling the truth (thus, binary classification.) I was planning on simply treating this as structured data and training based on that. However, on second thought, that wouldn't work at all because of a few reasons:
The order in which the data is organized matters as it is continuous time data.
The length of the data is variable as, again, it's time data and the time it takes for the subject to lie/tell the truth is inconsistent.
I don't know how to deal with there being multiple channels of data.
How would I go about setting up a training model for this type of data? I think this is a "time series classification" problem, but I'm not sure. Any kind of help would be greatly appreciated. Thank you in advance!
| After doing some more research, I decided to use an LSTM network with the Keras framework running on top of TensorFlow. LSTMs deal with time series data and the Keras layer allows for multiple feature time series data to be fed into the network, so if anyone is having a similar problem as mine, then LSTMs or RNNs are the way to go.
| https://stackoverflow.com/questions/52454828/ |
Getting rid of maxpooling layer causes running cuda out memory error pytorch | Video card: gtx1070ti 8Gb, batchsize 64, input image size 128*128.
I had such UNET with resnet152 as encoder wich worket pretty fine:
class UNetResNet(nn.Module):
def __init__(self, encoder_depth, num_classes, num_filters=32, dropout_2d=0.2,
pretrained=False, is_deconv=False):
super().__init__()
self.num_classes = num_classes
self.dropout_2d = dropout_2d
if encoder_depth == 34:
self.encoder = torchvision.models.resnet34(pretrained=pretrained)
bottom_channel_nr = 512
elif encoder_depth == 101:
self.encoder = torchvision.models.resnet101(pretrained=pretrained)
bottom_channel_nr = 2048
elif encoder_depth == 152:
self.encoder = torchvision.models.resnet152(pretrained=pretrained)
bottom_channel_nr = 2048
else:
raise NotImplementedError('only 34, 101, 152 version of Resnet are implemented')
self.pool = nn.MaxPool2d(2, 2)
self.relu = nn.ReLU(inplace=True)
self.conv1 = nn.Sequential(self.encoder.conv1,
self.encoder.bn1,
self.encoder.relu,
self.pool) #from that pool layer I would like to get rid off
self.conv2 = self.encoder.layer1
self.conv3 = self.encoder.layer2
self.conv4 = self.encoder.layer3
self.conv5 = self.encoder.layer4
self.center = DecoderCenter(bottom_channel_nr, num_filters * 8 *2, num_filters * 8, False)
self.dec5 = DecoderBlockV(bottom_channel_nr + num_filters * 8, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec4 = DecoderBlockV(bottom_channel_nr // 2 + num_filters * 8, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec3 = DecoderBlockV(bottom_channel_nr // 4 + num_filters * 8, num_filters * 4 * 2, num_filters * 2, is_deconv)
self.dec2 = DecoderBlockV(bottom_channel_nr // 8 + num_filters * 2, num_filters * 2 * 2, num_filters * 2 * 2,
is_deconv)
self.dec1 = DecoderBlockV(num_filters * 2 * 2, num_filters * 2 * 2, num_filters, is_deconv)
self.dec0 = ConvRelu(num_filters, num_filters)
self.final = nn.Conv2d(num_filters, num_classes, kernel_size=1)
def forward(self, x):
conv1 = self.conv1(x)
conv2 = self.conv2(conv1)
conv3 = self.conv3(conv2)
conv4 = self.conv4(conv3)
conv5 = self.conv5(conv4)
center = self.center(conv5)
dec5 = self.dec5(torch.cat([center, conv5], 1))
dec4 = self.dec4(torch.cat([dec5, conv4], 1))
dec3 = self.dec3(torch.cat([dec4, conv3], 1))
dec2 = self.dec2(torch.cat([dec3, conv2], 1))
dec1 = self.dec1(dec2)
dec0 = self.dec0(dec1)
return self.final(F.dropout2d(dec0, p=self.dropout_2d))
# blocks
class DecoderBlockV(nn.Module):
def __init__(self, in_channels, middle_channels, out_channels, is_deconv=True):
super(DecoderBlockV2, self).__init__()
self.in_channels = in_channels
if is_deconv:
self.block = nn.Sequential(
ConvRelu(in_channels, middle_channels),
nn.ConvTranspose2d(middle_channels, out_channels, kernel_size=4, stride=2,
padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
else:
self.block = nn.Sequential(
nn.Upsample(scale_factor=2, mode='bilinear'),
ConvRelu(in_channels, middle_channels),
ConvRelu(middle_channels, out_channels),
)
def forward(self, x):
return self.block(x)
class DecoderCenter(nn.Module):
def __init__(self, in_channels, middle_channels, out_channels, is_deconv=True):
super(DecoderCenter, self).__init__()
self.in_channels = in_channels
if is_deconv:
"""
Paramaters for Deconvolution were chosen to avoid artifacts, following
link https://distill.pub/2016/deconv-checkerboard/
"""
self.block = nn.Sequential(
ConvRelu(in_channels, middle_channels),
nn.ConvTranspose2d(middle_channels, out_channels, kernel_size=4, stride=2,
padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
else:
self.block = nn.Sequential(
ConvRelu(in_channels, middle_channels),
ConvRelu(middle_channels, out_channels)
)
def forward(self, x):
return self.block(x)
Then I edited my class looks to make it work without pooling layer:
class UNetResNet(nn.Module):
def __init__(self, encoder_depth, num_classes, num_filters=32, dropout_2d=0.2,
pretrained=False, is_deconv=False):
super().__init__()
self.num_classes = num_classes
self.dropout_2d = dropout_2d
if encoder_depth == 34:
self.encoder = torchvision.models.resnet34(pretrained=pretrained)
bottom_channel_nr = 512
elif encoder_depth == 101:
self.encoder = torchvision.models.resnet101(pretrained=pretrained)
bottom_channel_nr = 2048
elif encoder_depth == 152:
self.encoder = torchvision.models.resnet152(pretrained=pretrained)
bottom_channel_nr = 2048
else:
raise NotImplementedError('only 34, 101, 152 version of Resnet are implemented')
self.relu = nn.ReLU(inplace=True)
self.input_adjust = nn.Sequential(self.encoder.conv1,
self.encoder.bn1,
self.encoder.relu)
self.conv1 = self.encoder.layer1
self.conv2 = self.encoder.layer2
self.conv3 = self.encoder.layer3
self.conv4 = self.encoder.layer4
self.dec4 = DecoderBlockV(bottom_channel_nr, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec3 = DecoderBlockV(bottom_channel_nr // 2 + num_filters * 8, num_filters * 8 * 2, num_filters * 8, is_deconv)
self.dec2 = DecoderBlockV(bottom_channel_nr // 4 + num_filters * 8, num_filters * 4 * 2, num_filters * 2, is_deconv)
self.dec1 = DecoderBlockV(bottom_channel_nr // 8 + num_filters * 2, num_filters * 2 * 2, num_filters * 2 * 2,is_deconv)
self.final = nn.Conv2d(num_filters * 2 * 2, num_classes, kernel_size=1)
def forward(self, x):
input_adjust = self.input_adjust(x)
conv1 = self.conv1(input_adjust)
conv2 = self.conv2(conv1)
conv3 = self.conv3(conv2)
center = self.conv4(conv3)
dec4 = self.dec4(center) #now without centblock
dec3 = self.dec3(torch.cat([dec4, conv3], 1))
dec2 = self.dec2(torch.cat([dec3, conv2], 1))
dec1 = F.dropout2d(self.dec1(torch.cat([dec2, conv1], 1)), p=self.dropout_2d)
return self.final(dec1)
is_deconv - in both cases True. After changing it stop to work with batchsize 64, only with with size of 16 or with batchsize 64 but with resnet16 only - otherwise out of cuda memory. What am I doing wrong?
Full stack of error:
~/Desktop/ml/salt/open-solution-salt-identification-master/common_blocks/unet_models.py in forward(self, x)
418 conv1 = self.conv1(input_adjust)
419 conv2 = self.conv2(conv1)
--> 420 conv3 = self.conv3(conv2)
421 center = self.conv4(conv3)
422 dec4 = self.dec4(center)
~/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
355 result = self._slow_forward(*input, **kwargs)
356 else:
--> 357 result = self.forward(*input, **kwargs)
358 for hook in self._forward_hooks.values():
359 hook_result = hook(self, input, result)
~/anaconda3/lib/python3.6/site-packages/torch/nn/modules/container.py in forward(self, input)
65 def forward(self, input):
66 for module in self._modules.values():
---> 67 input = module(input)
68 return input
69
~/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
355 result = self._slow_forward(*input, **kwargs)
356 else:
--> 357 result = self.forward(*input, **kwargs)
358 for hook in self._forward_hooks.values():
359 hook_result = hook(self, input, result)
~/anaconda3/lib/python3.6/site-packages/torchvision-0.2.0-py3.6.egg/torchvision/models/resnet.py in forward(self, x)
79
80 out = self.conv2(out)
---> 81 out = self.bn2(out)
82 out = self.relu(out)
| The problem is that you do not have enough memory, as already mentioned in the comments.
To be more specific, the problem lies in the increased size due to the removal of the max pooling, as you already correctly narrowed it down. The point of max pooling - aside from the increased invariance of the setting - is to reduce the image size, such that it costs you less memory because you need to store less activations for the backpropagation part.
A good answer of what max pooling does might be helpful. My go-to one is the one on Quora.
As you also correctly figured out already is the fact that the batch size also plays a huge role in terms of memory consumption. Generally, it is also preferred to use smaller batch sizes anyways, as long as you don't have a skyrocketing processing time after.
| https://stackoverflow.com/questions/52455658/ |
Why would Pytorch (CUDA) be running slow on GPU | I have been playing around with Pytorch on Linux for some time now and recently decided to try get more scripts to run with my GPU on my Windows desktop. Since trying this I have noticed a massive performance difference between my GPU execution time and my CPU execution time, on the same scripts, such that my GPU is significantly slow than CPU. To illustrate this I just a tutorial program found here (https://pytorch.org/tutorials/beginner/pytorch_with_examples.html#pytorch-tensors)
import torch
import datetime
print(torch.__version__)
dtype = torch.double
#device = torch.device("cpu")
device = torch.device("cuda:0")
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random input and output data
x = torch.randn(N, D_in, device=device, dtype=dtype)
y = torch.randn(N, D_out, device=device, dtype=dtype)
# Randomly initialize weights
w1 = torch.randn(D_in, H, device=device, dtype=dtype)
w2 = torch.randn(H, D_out, device=device, dtype=dtype)
start = datetime.datetime.now()
learning_rate = 1e-6
for t in range(5000):
# Forward pass: compute predicted y
h = x.mm(w1)
h_relu = h.clamp(min=0)
y_pred = h_relu.mm(w2)
# Compute and print loss
loss = (y_pred - y).pow(2).sum().item()
#print(t, loss)
# Backprop to compute gradients of w1 and w2 with respect to loss
grad_y_pred = 2.0 * (y_pred - y)
grad_w2 = h_relu.t().mm(grad_y_pred)
grad_h_relu = grad_y_pred.mm(w2.t())
grad_h = grad_h_relu.clone()
grad_h[h < 0] = 0
grad_w1 = x.t().mm(grad_h)
# Update weights using gradient descent
w1 -= learning_rate * grad_w1
w2 -= learning_rate * grad_w2
end = datetime.datetime.now()
print(end-start)
I increased the number of Epoch's from 500 to 5000 as I have read that the first CUDA call is very slow due to initialisation. However the performance issue still exists.
With device = torch.device("cpu") the final time printed out is normal around 3-4 seconds, well device = torch.device("cuda:0") executes in around 13-15 seconds
I have reinstalled Pytorch a number of different ways (uninstalling the previous installation of course) and the problem still persists. I am hoping that someone can help me, if I have perhaps missed a set (didn't install some other API/program) or am doing something wrong in the code.
Python: v3.6
Pytorch:v0.4.1
GPU: NVIDIA GeForce GTX 1060 6GB
Any help would be appreciated :slight_smile:
| Running on gpu could be expensive when you run with smaller batch size. If you put more data to gpu, means increasing the batch size, then you could observe significance amount of increase in data. Yes gpu is running better with float32 than double.
Try this
**
N, D_in, H, D_out = 128, 1000, 500, 10
dtype = torch.float32
**
| https://stackoverflow.com/questions/52458508/ |
pyTorch can backward twice without setting retain_graph=True | As indicated in pyTorch tutorial,
if you even want to do the backward on some part of the graph twice,
you need to pass in retain_graph = True during the first pass.
However, I found the following codes snippet actually worked without doing so. I'm using pyTorch-0.4
x = torch.ones(2, 2, requires_grad=True)
y = x + 2
y.backward(torch.ones(2, 2)) # Note I do not set retain_graph=True
y.backward(torch.ones(2, 2)) # But it can still work!
print x.grad
output:
tensor([[ 2., 2.],
[ 2., 2.]])
Could anyone explain? Thanks in advance!
|
The reason why it works w/o retain_graph=True in your case is you have very simple graph that probably would have no internal intermediate buffers, in turn no buffers will be freed, so no need to use retain_graph=True.
But everything is changing when adding one more extra computation to your graph:
Code:
x = torch.ones(2, 2, requires_grad=True)
v = x.pow(3)
y = v + 2
y.backward(torch.ones(2, 2))
print('Backward 1st time w/o retain')
print('x.grad:', x.grad)
print('Backward 2nd time w/o retain')
try:
y.backward(torch.ones(2, 2))
except RuntimeError as err:
print(err)
print('x.grad:', x.grad)
Output:
Backward 1st time w/o retain
x.grad: tensor([[3., 3.],
[3., 3.]])
Backward 2nd time w/o retain
Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.
x.grad: tensor([[3., 3.],
[3., 3.]]).
In this case additional internal v.grad will be computed, but torch doesn't store intermediate values (intermediate gradients etc), and with retain_graph=False v.grad will be freed after first backward.
So, if you want to backprop second time you need to specify retain_graph=True to "keep" the graph.
Code:
x = torch.ones(2, 2, requires_grad=True)
v = x.pow(3)
y = v + 2
y.backward(torch.ones(2, 2), retain_graph=True)
print('Backward 1st time w/ retain')
print('x.grad:', x.grad)
print('Backward 2nd time w/ retain')
try:
y.backward(torch.ones(2, 2))
except RuntimeError as err:
print(err)
print('x.grad:', x.grad)
Output:
Backward 1st time w/ retain
x.grad: tensor([[3., 3.],
[3., 3.]])
Backward 2nd time w/ retain
x.grad: tensor([[6., 6.],
[6., 6.]])
| https://stackoverflow.com/questions/52463439/ |
How do I visualize a net in Pytorch? | import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision.models as models
import torchvision.datasets as dset
import torchvision.transforms as transforms
from torch.autograd import Variable
from torchvision.models.vgg import model_urls
from torchviz import make_dot
batch_size = 3
learning_rate =0.0002
epoch = 50
resnet = models.resnet50(pretrained=True)
print resnet
make_dot(resnet)
I want to visualize resnet from the pytorch models. How can I do it? I tried to use torchviz but it gives an error:
'ResNet' object has no attribute 'grad_fn'
| The make_dot expects a variable (i.e., tensor with grad_fn), not the model itself.
try:
x = torch.zeros(1, 3, 224, 224, dtype=torch.float, requires_grad=False)
out = resnet(x)
make_dot(out) # plot graph of variable, not of a nn.Module
| https://stackoverflow.com/questions/52468956/ |
Split dataset based on file names in pytorch Dataset | Is there a way to divide the dataset into training and testing based on the filenames. I have a folder containing two folders: input and output. Input folder has the images and output are the labels for that image. The file names in the input folder are something like input01_train.png and input01_test.png like shown below.
Dataset
/ \
Input Output
| |
input01_train.png output01_train.png
. .
. .
input01_test.png output01_test.png
The code I have only divides the dataset into inputs and labels not test and train.
class CancerDataset(Dataset):
def __init__(self, dataset_folder):#,label_folder):
self.dataset_folder = torchvision.datasets.ImageFolder(dataset_folder ,transform = transforms.Compose([transforms.Resize(512),transforms.ToTensor()]))
self.label_folder = torchvision.datasets.ImageFolder(dataset_folder ,transform = transforms.Compose([transforms.Resize(512),transforms.ToTensor()]))
def __getitem__(self,index):
img = self.dataset_folder[index]
label = self.label_folder[index]
return img,label
def __len__(self):
return len(self.dataset_folder)
trainset = CancerDataset(dataset_folder = '/content/drive/My Drive/cancer_data/')
trainsetloader = DataLoader(trainset,batch_size = 1, shuffle = True,num_workers = 0,pin_memory = True)
I would like to be able to divide the train and test set by their names if that is possible .
| You could load the images yourself in __getitem__, selecting only those that contain '_train.png' or '_test.png'.
class CancerDataset(Dataset):
def __init__(self, datafolder, datatype='train', transform = transforms.Compose([transforms.Resize(512),transforms.ToTensor()]):
self.datafolder = datafolder
self.image_files_list = [s for s in os.listdir(datafolder) if
'_%s.png' % datatype in s]
# Same for the labels files
self.label_files_list = ...
self.transform = transform
def __len__(self):
return len(self.image_files_list)
def __getitem__(self, idx):
img_name = os.path.join(self.datafolder,
self.image_files_list[idx])
image = Image.open(img_name)
image = self.transform(image)
# Same for the labels files
label = .... # Load in etc
label = self.transform(label)
return image, label
Now you could make two datasets (trainset and testset).
trainset = CancerDataset(dataset_folder = '/content/drive/My Drive/cancer_data/', datatype='train')
testset = CancerDataset(dataset_folder = '/content/drive/My Drive/cancer_data/', datatype='test')
| https://stackoverflow.com/questions/52473516/ |
How can I specify the flatten layer input size after many conv layers in PyTorch? | Here is my problem, I do a small test on CIFAR10 dataset, how can I specify the flatten layer input size in PyTorch? like the following, the input size is 16*5*5, however I don't know how to calculate this and I want to get the input size through some function.Can someone just write a simple function in this Net class and solve this?
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3,6,5)
self.conv2 = nn.Conv2d(6,16,5)
# HERE , the input size is 16*5*5, but I don't know how to get it.
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120,84)
self.fc3 = nn.Linear(84,10)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)),(2,2))
x = F.max_pool2d(F.relu(self.conv2(x)),2)
x = x.view(x.size()[0],-1)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
| There is no Flatten Layer in the Pytorch default. You can create a class like below. Cheers
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.flatten = Flatten() ## describing the layer
self.conv1 = nn.Conv2d(3,6,5)
self.conv2 = nn.Conv2d(6,16,5)
# HERE , the input size is 16*5*5, but I don't know how to get it.
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120,84)
self.fc3 = nn.Linear(84,10)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)),(2,2))
x = F.max_pool2d(F.relu(self.conv2(x)),2)
#x = x.view(x.size()[0],-1)
x = self.flatten(x) ### using of flatten layer
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
| https://stackoverflow.com/questions/52474439/ |
The similar function of "tf.Session().partial_run()" in Pytorch | I am trying to use Pytorch to reimplement a project, but I have some troubles to find a similar function of "partial_run" of Tensorflow. Can you show me what it is?
Thanks.
| You don't need the partial run function, as Pytorch objects hold actual values (and are not just abstracted computation/input nodes in a graph that only hold values once the computation graph is triggered - with Session.(partial)run).
So when you code something in pytorch, you can (mostly) just think of it as writing numpy code. There, too, the objects you create when writing your code will hold actual values that you can manipulate.
Besides being more "traditional" this has the great consequence that Pytorch thus allows you to debug code using a traditional python debugger.
| https://stackoverflow.com/questions/52489357/ |
Data preprocessing for custom dataset in pytorch (transform.Normalize) | I am new to Pytorch and CNN. I am kind of confused about Data Preprocessing. Not sure how to go about transform.Normalising the dataset (in essence how do you calculate mean and std v for your custom dataset ?)
I am loading my data using ImageFolder. The images are of different sizes.
train_transforms = transforms.Compose([transforms.Resize(size=224),
transforms.ToTensor(), transforms.Normalize((?), (?))
])
train_dataset = datasets.ImageFolder(root='roota/',
transform=train_transforms)
| If you're planning to train your network from scratch, you can calculate your dataset's statistics. The statistics of the dataset are calculated beforehand. You can use the ImageFolder to loop through the images to calculate the dataset statistics. For example, pseudo code -
for inputs, labels in dataloaders:
# Calculate mean and std dev
# save for later processing
Typically, CNNs are pretrained with other larger datasets, such as Imagenet, primarily to reduce the training time. If you are using a pretrained network, you can use the mean and std dev of the original dataset for your training.
| https://stackoverflow.com/questions/52489460/ |
How to use CUDA stream in Pytorch? | I wanna use CUDA stream in Pytorch to parallel some computations, but I don't know how to do it.
For instance, if there's 2 tasks, A and B, need to be parallelized, I wanna do the following things:
stream0 = torch.get_stream()
stream1 = torch.get_stream()
with torch.now_stream(stream0):
// task A
with torch.now_stream(stream1):
// task B
torch.synchronize()
// get A and B's answer
How can I achieve the goal in real python code?
| s1 = torch.cuda.Stream()
s2 = torch.cuda.Stream()
# Initialise cuda tensors here. E.g.:
A = torch.rand(1000, 1000, device = 'cuda')
B = torch.rand(1000, 1000, device = 'cuda')
# Wait for the above tensors to initialise.
torch.cuda.synchronize()
with torch.cuda.stream(s1):
C = torch.mm(A, A)
with torch.cuda.stream(s2):
D = torch.mm(B, B)
# Wait for C and D to be computed.
torch.cuda.synchronize()
# Do stuff with C and D.
| https://stackoverflow.com/questions/52498690/ |
RuntimeError: expected stride to be a single integer value | I am new at Pytorch sorry for the basic question. The model gives me dimension mismatch error how to solve this ?
Maybe more than one problems in it.
Any help would be appriciated.
Thanks
class PR(nn.Module):
def __init__(self):
super(PR, self).__init__()
self.conv1 = nn.Conv2d(3,6,kernel_size=5)
self.conv2 = nn.Conv2d(6,1,kernel_size=2)
self.dens1 = nn.Linear(300, 256)
self.dens2 = nn.Linear(256, 256)
self.dens3 = nn.Linear(512, 24)
self.drop = nn.Dropout()
def forward(self, x):
out = self.conv1(x)
out = self.conv2(x)
out = self.dens1(x)
out = self.dens2(x)
out = self.dens3(x)
return out
model = PR()
input = torch.rand(28,28,3)
output = model(input)
| Please have a look at the corrected code. I numbered the lines where I did corrections and described them below.
class PR(torch.nn.Module):
def __init__(self):
super(PR, self).__init__()
self.conv1 = torch.nn.Conv2d(3,6, kernel_size=5) # (2a) in 3x28x28 out 6x24x24
self.conv2 = torch.nn.Conv2d(6,1, kernel_size=2) # (2b) in 6x24x24 out 1x23x23 (6)
self.dens1 = torch.nn.Linear(529, 256) # (3a)
self.dens2 = torch.nn.Linear(256, 256)
self.dens3 = torch.nn.Linear(256, 24) # (4)
self.drop = torch.nn.Dropout()
def forward(self, x):
out = self.conv1(x)
out = self.conv2(out) # (5)
out = out.view(-1, 529) # (3b)
out = self.dens1(out)
out = self.dens2(out)
out = self.dens3(out)
return out
model = PR()
ins = torch.rand(1, 3, 28, 28) # (1)
output = model(ins)
First of all, pytorch handles image tensors (you perform 2d convolution therefore I assume this is an image input) as follows: [batch_size x image_depth x height width]
It is important to understand how the convolution with kernel, padding and stride works. In your case kernel_size is 5 and you have no padding (and stride 1). This means that the dimensions of the feature-map gets reduced (as depicted). In your case the first conv. layer takes a 3x28x28 tensor and produces a 6x24x24 tensor, the second one takes 6x24x24 out 1x23x23. I find it very useful to have comments with the in and out tensor dimensions next to the definition conv layers (see in the code above)
Here you need to "flatten" the [batch_size x depth x height x width] tensor to [batch_size x fully connected input]. This can be done via tensor.view().
There was a wrong input for the linear layer
Each operation in the forward-pass took the input value x, instead I think you might want to pass the results of each layer to the next one
Altough this code is now runnable, it does not mean that it makes perfect sense. The most important thing (for neural networks in general i would say) are activation functions. These are missing completely.
For getting started with neural networks in pytorch I can highly recommend the great pytorch tutorials: https://pytorch.org/tutorials/ (I would start with the 60min blitz tutorial)
Hope this helps!
| https://stackoverflow.com/questions/52503695/ |
Pytorch not building with cmake in Developer Console | I've mostly used languages with simple IDEs until now, so I don't have the best knowledge of compiling and running git and cmake and everything else through command line. I need to use Pytorch for a project though, so it's necessary to use those skills. I'm installing it according to the tutorial for windows found here:
https://caffe2.ai/docs/getting-started.html?platform=windows&configuration=compile
I've gotten to the point where I'm running build_windows.bat, but I'm getting this output with an error from the Developer Command Prompt.
The system cannot find the drive specified.
Requirement already satisfied: pyyaml in g:\programs\python27\lib\site-packages (3.13)
CAFFE2_ROOT=G:\Programs\Caffe2\pytorch\scripts\..
CMAKE_GENERATOR="Visual Studio 14 2015 Win64"
CMAKE_BUILD_TYPE=Release
-- Selecting Windows SDK version to target Windows 10.0.17134.
CMake Error at CMakeLists.txt:6 (project):
Failed to run MSBuild command:
MSBuild.exe
to get the value of VCTargetsPath:
Microsoft (R) Build Engine version 15.8.169+g1ccb72aefa for .NET Framework
Copyright (C) Microsoft Corporation. All rights reserved.
Build started 9/25/2018 4:20:32 PM.
Project "G:\Programs\Caffe2\pytorch\build\CMakeFiles\3.12.2\VCTargetsPath.vcxproj" on node 1 (default targets).
G:\Programs\Caffe2\pytorch\build\CMakeFiles\3.12.2\VCTargetsPath.vcxproj(14,2): error MSB4019: The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Default.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
Done Building Project "G:\Programs\Caffe2\pytorch\build\CMakeFiles\3.12.2\VCTargetsPath.vcxproj" (default targets) -- FAILED.
Build FAILED.
"G:\Programs\Caffe2\pytorch\build\CMakeFiles\3.12.2\VCTargetsPath.vcxproj" (default target) (1) ->
G:\Programs\Caffe2\pytorch\build\CMakeFiles\3.12.2\VCTargetsPath.vcxproj(14,2): error MSB4019: The imported project "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\VC\VCTargets\Microsoft.Cpp.Default.props" was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:00.15
Exit code: 1
-- Configuring incomplete, errors occurred!
See also "G:/Programs/Caffe2/pytorch/build/CMakeFiles/CMakeOutput.log".
"Caffe2 building failed"
The CMakeOutput.log file only contains this:
The system is: Windows - 10.0.17134 - AMD64
Which isn't very useful. I'm not sure what I'm doing wrong here.
| If you just need to test or experiment with pytorch I suggest that you first try to install it through the pip package. It is much easier.
If you really need to install it from source, then I suggest that you read the build_windows.bat file to check that it really suits your configuration and modify it if needed. Make sure you are targeting the correct Visual Studio version for example.
The error you are getting doesn't seem to come from the pytorch project itself.
| https://stackoverflow.com/questions/52506991/ |
PyTorch softmax with dim | Which dimension should softmax be applied to ?
This code :
%reset -f
import torch.nn as nn
import numpy as np
import torch
my_softmax = nn.Softmax(dim=-1)
mu, sigma = 0, 0.1 # mean and standard deviation
train_dataset = []
image = []
image_x = np.random.normal(mu, sigma, 24).reshape((3 , 4, 2))
train_dataset.append(image_x)
x = torch.tensor(train_dataset).float()
print(x)
print(my_softmax(x))
my_softmax = nn.Softmax(dim=1)
print(my_softmax(x))
prints following :
tensor([[[[-0.1500, 0.0243],
[ 0.0226, 0.0772],
[-0.0180, -0.0278],
[ 0.0782, -0.0853]],
[[-0.0134, -0.1139],
[ 0.0385, -0.1367],
[-0.0447, 0.1493],
[-0.0633, -0.2964]],
[[ 0.0123, 0.0061],
[ 0.1086, -0.0049],
[-0.0918, -0.1308],
[-0.0100, 0.1730]]]])
tensor([[[[ 0.4565, 0.5435],
[ 0.4864, 0.5136],
[ 0.5025, 0.4975],
[ 0.5408, 0.4592]],
[[ 0.5251, 0.4749],
[ 0.5437, 0.4563],
[ 0.4517, 0.5483],
[ 0.5580, 0.4420]],
[[ 0.5016, 0.4984],
[ 0.5284, 0.4716],
[ 0.5098, 0.4902],
[ 0.4544, 0.5456]]]])
tensor([[[[ 0.3010, 0.3505],
[ 0.3220, 0.3665],
[ 0.3445, 0.3230],
[ 0.3592, 0.3221]],
[[ 0.3450, 0.3053],
[ 0.3271, 0.2959],
[ 0.3355, 0.3856],
[ 0.3118, 0.2608]],
[[ 0.3540, 0.3442],
[ 0.3509, 0.3376],
[ 0.3200, 0.2914],
[ 0.3289, 0.4171]]]])
So first tensor is prior to softmax being applied, second tensor is result of softmax applied to tensor with dim=-1 and third tensor is result of softmax applied to tensor with dim=1 .
For result of first softmax can see corresponding elements sum to 1, for example [ 0.4565, 0.5435] -> 0.4565 + 0.5435 == 1.
What is summing to 1 as result of of second softmax ?
Which dim value should I choose ?
Update : The dimension (3 , 4, 2) corresponds to image dimension where 3 is the RGB value , 4 is the number of horizontal pixels (width) , 2 is the number of vertical pixels (height). This is an image classification problem. I'm using cross entropy loss function. Also, I'm using softmax in final layer in order to back-propagate probabilities.
| You have a 1x3x4x2 tensor train_dataset. Your softmax function's dim parameter determines across which dimension to perform Softmax operation. First dimension is your batch dimension, second is depth, third is rows and last one is columns. Please look at picture below (sorry for horrible drawing) to understand how softmax is performed when you specify dim as 1.
In short, sum of each corresponding entry of your 4x2 matrices are equal to 1.
Update: The question which dimension the softmax should be applied depends on what data your tensor store, and what is your goal.
Update: For image classification task, please see the tutorial on official pytorch website. It covers basics of image classification with pytorch on a real dataset and its a very short tutorial. Although that tutorial does not perform Softmax operation, what you need to do is just use torch.nn.functional.log_softmax on output of last fully connected layer. See MNIST classifier with pytorch for a complete example. It does not matter whether your image is RGB or grayscale after flattening it for fully connected layers (also keep in mind that same code for MNIST example might not work for you, depends on which pytorch version you use).
| https://stackoverflow.com/questions/52513802/ |
tensor - box plot from a tensor | I'm trying to create a box between two variables probability (y axis) and flowername ( x- axis) .Probability is a tensor. For the flower name, I have to pick the name from a dictionary (flower_dict) where the key is referenced from another tensor, class Index. How do I create box plot ? ANy help is appreciate
print("Probability:", probs)
Probability: tensor([[ 0.9961, 0.0020, 0.0011, 0.0005, 0.0001]], device='cuda:0')
print("Class Index:", classes)
Class Index: tensor([[ 21, 3, 45, 34, 27]], device='cuda:0')
print(flower_dict)
{'21': 'fire lily', '3': 'canterbury bells', '45': 'bolero deep blue', '1': 'pink primrose', '34': 'mexican aster', '27': 'prince of wales feathers', '7': 'moon orchid', '16': 'globe-flower', '25': 'grape hyacinth', '26': 'corn poppy', '79': 'toad lily', '39': 'siam tulip', '24': 'red ginger'}
| I guess you mean creating a bar plot here (with box-plots you usually depict distributions like for examining features etc.; in the iris flower case for example you might want to examine sepal-length in a box plot). If bar plot is what you want, then you can try the following code:
import numpy as np
import matplotlib.pyplot as plt
y = probs.flatten().numpy()
x = [flower_dict[str(i)] for i in classes.flatten().numpy()]
p1 = plt.bar(x, y, width)
plt.ylabel('Probability')
plt.xticks(ind, x)
plt.show()
Hope this helps!
| https://stackoverflow.com/questions/52516212/ |
How to compensate if I cant do a large batch size in neural network | I am trying to run an action recognition code from GitHub. The original code used a batch size of 128 with 4 GPUS. I only have two gpus so I cannot match their bacth size number. Is there anyway I can compensate this difference in batch. I saw somewhere that iter_size might compensate according to a formula effective_batchsize= batch_size*iter_size*n_gpu. what is iter_size in this formula?
I am using PYthorch not Caffe.
| In pytorch, when you perform the backward step (calling loss.backward() or similar) the gradients are accumulated in-place. This means that if you call loss.backward() multiple times, the previously calculated gradients are not replaced, but in stead the new gradients get added on to the previous ones. That is why, when using pytorch, it is usually necessary to explicitly zero the gradients between minibatches (by calling optimiser.zero_grad() or similar).
If your batch size is limited, you can simulate a larger batch size by breaking a large batch up into smaller pieces, and only calling optimiser.step() to update the model parameters after all the pieces have been processed.
For example, suppose you are only able to do batches of size 64, but you wish to simulate a batch size of 128. If the original training loop looks like:
optimiser.zero_grad()
loss = model(batch_data) # batch_data is a batch of size 128
loss.backward()
optimiser.step()
then you could change this to:
optimiser.zero_grad()
smaller_batches = batch_data[:64], batch_data[64:128]
for batch in smaller_batches:
loss = model(batch) / 2
loss.backward()
optimiser.step()
and the updates to the model parameters would be the same in each case (apart maybe from some small numerical error). Note that you have to rescale the loss to make the update the same.
| https://stackoverflow.com/questions/52518324/ |
PyTorch CUDA vs Numpy for arithmetic operations? Fastest? | I performed element-wise multiplication using Torch with GPU support and Numpy using the functions below and found that Numpy loops faster than Torch which shouldn't be the case, I doubt.
I want to know how to perform general arithmetic operations with Torch using GPU.
Note: I ran these code snippets in Google Colab notebook
Define the default tensor type to enable global GPU flag
torch.set_default_tensor_type(torch.cuda.FloatTensor if
torch.cuda.is_available() else
torch.FloatTensor)
Initialize Torch variables
x = torch.Tensor(200, 100) # Is FloatTensor
y = torch.Tensor(200,100)
Function in question
def mul(d,f):
g = torch.mul(d,f).cuda() # I explicitly called cuda() which is not necessary
return g
When call the function above as
%timeit mul(x,y)
Returns:
The slowest run took 10.22 times longer than the fastest. This could
mean hat an intermediate result is being cached. 10000 loops, best
of 3: 50.1 µs per loop
Now trial with numpy,
Used the same values from torch variables
x_ = x.data.cpu().numpy()
y_ = y.data.cpu().numpy()
def mul_(d,f):
g = d*f
return g
%timeit mul_(x_,y_)
Returns
The slowest run took 12.10 times longer than the fastest. This could
mean that an intermediate result is being cached. 100000 loops, best
of 3: 7.73 µs per loop
Needs some help to understand GPU enabled Torch operations.
| GPU operations have to additionally get memory to/from the GPU
The problem is that your GPU operation always has to put the input on the GPU memory, and
then retrieve the results from there, which is a quite costly operation.
NumPy, on the other hand, directly processes the data from the CPU/main memory, so there is almost no delay here. Additionally, your matrices are extremely small, so even in the best-case scenario, there should only be a minute difference.
This is also partially the reason why you use mini-batches when training on a GPU in neural networks: Instead of having several extremely small operations, you now have "one big bulk" of numbers that you can process in parallel.
Also note that GPU clock speeds are generally way lower than CPU clocks, so the GPU only really shines because it has way more cores. If your matrix does not utilize all of them fully, you are also likely to see a faster result on your CPU.
TL;DR: If your matrix is big enough, you will eventually see a speed-up in CUDA than Numpy, even with the additional cost of the GPU transfer.
| https://stackoverflow.com/questions/52526082/ |
pytorch passing architecture type with argprse | Using Pytorch. When passing architecture type by using the following code:
parser.add_argument('-arch', action='store',
dest='arch',
default= str('vgg16'))
When using the name of the architecture with the following code:
model = models.__dict__['{!r}'.format(results.arch)](pretrained=True)
I get the following error:
model = models.dict'{!r}'.format(results.arch)
KeyError: "'vgg16'"
What am I doing wrong?
| You got KeyError meaning your imported models do not include 'vgg16' as one of the known models.
Check what models you do have by printing
print(models.__dict__.keys())
This should allow you to know what models you import and which are missing, then you can look into your imports and see where 'vgg16' got lost.
| https://stackoverflow.com/questions/52532914/ |
How to remove the last FC layer from a ResNet model in PyTorch? | I am using a ResNet152 model from PyTorch. I'd like to strip off the last FC layer from the model. Here's my code:
from torchvision import datasets, transforms, models
model = models.resnet152(pretrained=True)
print(model)
When I print the model, the last few lines look like this:
(2): Bottleneck(
(conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace)
)
)
(avgpool): AvgPool2d(kernel_size=7, stride=1, padding=0)
(fc): Linear(in_features=2048, out_features=1000, bias=True)
)
I want to remove that last fc layer from the model.
I found an answer here on SO (How to convert pretrained FC layers to CONV layers in Pytorch), where mexmex seems to provide the answer I'm looking for:
list(model.modules()) # to inspect the modules of your model
my_model = nn.Sequential(*list(model.modules())[:-1]) # strips off last linear layer
So I added those lines to my code like this:
model = models.resnet152(pretrained=True)
list(model.modules()) # to inspect the modules of your model
my_model = nn.Sequential(*list(model.modules())[:-1]) # strips off last linear layer
print(my_model)
But this code doesn't work as advertised -- as least not for me. The rest of this post is a detailed explanation of why that answer doesn't work so this question doesn't get closed as a duplicate.
First, the printed model is nearly 5x larger than before. I see the same model as before, but followed by what appears to be a repeat of the model, but perhaps flattened.
(2): Bottleneck(
(conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
(bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(relu): ReLU(inplace)
)
)
(avgpool): AvgPool2d(kernel_size=7, stride=1, padding=0)
(fc): Linear(in_features=2048, out_features=1000, bias=True)
)
(1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
(2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(3): ReLU(inplace)
(4): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)
(5): Sequential(
. . . this goes on for ~1600 more lines . . .
(415): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(416): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
(417): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(418): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)
(419): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(420): ReLU(inplace)
(421): AvgPool2d(kernel_size=7, stride=1, padding=0)
)
Second, the fc layer is still there -- and the Conv2D layer after it looks just like the first layer of ResNet152.
Third, if I try to invoke my_model.forward(), pytorch complains about a size mismatch. It expects size [1, 3, 224, 224], but the input was [1, 1000]. So it looks like a copy of the entire model (minus the fc layer) is getting appended to the original model.
Bottom line, the only answer I found on SO doesn't actually work.
| For ResNet model, you can use children attribute to access layers since ResNet model in pytorch consist of nn modules. (Tested on pytorch 0.4.1)
model = models.resnet152(pretrained=True)
newmodel = torch.nn.Sequential(*(list(model.children())[:-1]))
print(newmodel)
Update: Although there is not an universal answer for the question that can work on all pytorch models, it should work on all well structured ones. Existing layers you add to your model (such as torch.nn.Linear, torch.nn.Conv2d, torch.nn.BatchNorm2d...) all based on torch.nn.Module class. And if you implement a custom layer and add that to your network you should inherit it from pytorch's torch.nn.Module class. As written in documentation, children attribute lets you access the modules of your class/model/network.
def children(self):
r"""Returns an iterator over immediate children modules.
Update: It is important to note that children() returns "immediate" modules, which means if last module of your network is a sequential, it will return whole sequential.
| https://stackoverflow.com/questions/52548174/ |
Given 4 points, how to crop a quadrilateral from an image in pytorch/torchvision? | Problem is pretty straightforward -
I want to crop a quadrilateral from an image in pytorch/torchvision. Given, I have four coordinates of the corners of this quadrilateral.
Please note that these four points confine a quadrilateral within themselves which may or may not be a rectangle. So please refrain from suggesting answers involving slicing of the image.
Please comment if I have missed any relevant detail.
| Quoting https://stackoverflow.com/a/30902423/4982729 I could extract the patch using opencv as -
import numpy as np
import cv2
pts = np.array([[542, 107], [562, 102], [582, 110], [598, 142], [600, 192], [601, 225], [592, 261], [572, 263], [551, 245], [526, 220], [520, 188], [518, 152], [525, 127], [524, 107]], dtype=np.int32)
mask = np.zeros((img.shape[0], img.shape[1]))
cv2.fillConvexPoly(mask, pts, 1)
mask = mask.astype(np.bool)
out = np.zeros_like(img)
out[mask] = img[mask]
and then I could convert the numpy array to torch's Variable manually. This seems to raise no errors even when I am forming torch's graph for neural networks.
outputs = model(images)
o = outputs.data.cpu().numpy()
#
# do your opencv stuff here to o
#
o = torch.Tensor(o).to(device)
outputs = Variable(o, requires_grad=True)
| https://stackoverflow.com/questions/52566050/ |
too many arguments in a Pytorch custom nn module forward function | I'm trying to make a neural network in pytorch that has a variable number of layers. My problem is that apparently I am passing some sort of iterable with more than one item to a linear layer which can only take one argument. I just can't see why.
So here is some code. First I created my own module and import it to my notebook later
import torch
class NNet(torch.nn.Module):
def __init__(self, layer_shapes, activation_functions):
super(NNet, self).__init__()
assert len(layer_shapes) == len(activation_functions) + 1
self.layer_shapes = layer_shapes
self.activation_functions = activation_functions
linear_functions = list()
for i in range(len(self.layer_shapes)-1):
linear_functions.append(torch.nn.Linear(
self.layer_shapes[i], self.layer_shapes[i+1]))
self.linear_functions = linear_functions
def parameters(self):
parameters = list()
for function in self.linear_functions:
parameters = parameters+list(function.parameters())
return parameters
def forward(self, x):
assert x.shape[1] == self.layer_shapes[0]
y = x
for i in range(len(self.layer_shapes)-1):
lin = self.linear_functions[i](y)
y = self.activation_functions[i](lin)
return y
In the notebook, the error is in the forward function at y = self.activation_functions[i](self.linear_functions[i](y))
Now I try to use the MNIST dataset supplied by torchvision and use my own module.
batch_size = 100
epochs = 500
learning_rate = 0.001
train_set = torchvision.datasets.MNIST(root =
'../../data',
train=True,
transform=torchvision.transforms.ToTensor(),
download=True)
test_set = torchvision.datasets.MNIST(root =
'../../data',
train=False,
transform=torchvision.transforms.ToTensor(),
download=True)
train_loader = torch.utils.data.DataLoader(dataset=train_set,
batch_size=batch_size,
shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_set,
batch_size=batch_size,
shuffle=False)
model = nnet.NNet([784, 16, 10], [torch.nn.Tanh,
torch.nn.Softmax(dim=1)])
loss_function = torch.nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
loss_items = list()
for t in range(epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.reshape(-1,28*28)
outputs = model(images)
loss = loss_function(outputs, labels)
loss_items.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
This last for loop yields the error:
TypeError Traceback (most recent call last)
<ipython-input-6-4ccb4b105a41> in <module>()
5 images = images.reshape(-1,28*28)
6
----> 7 outputs = model(images)
8 loss = loss_function(outputs, labels)
9 loss_items.append(loss.item())
~/.local/lib/python3.6/site-packages/torch/nn/modules/module.py in
__call__(self, *input, **kwargs)
475 result = self._slow_forward(*input, **kwargs)
476 else:
--> 477 result = self.forward(*input, **kwargs)
478 for hook in self._forward_hooks.values():
479 hook_result = hook(self, input, result)
~/Desktop/Archive/Computing/Projects/Python/ai/neural_network.py in
forward(self, x)
28 for i in range(len(self.layer_shapes)-1):
29 lin = self.linear_functions[i](y)
---> 30 y = self.activation_functions[i](lin)
31 return y
32
TypeError: __init__() takes 1 positional argument but 2 were given
I'm sure someone could tell me why this is happening, but could someone please give me a helpful strategy for debugging here? I'm new to pytorch and I doubt this will be the last trouble that I have. So a strategy for investigating these things would be helpful.
I would appreciate any input.
| In the definition of model I forgot the parentheses on the torch.nn.Tanh class. It should be torch.nn.Tanh()
I keep thinking that these are functions and not classes. I still have some things to fix, but I'm glad I saw that. So frustrating. I found it by basically putting assert and print statements all over my code.
| https://stackoverflow.com/questions/52570007/ |
Combining Neural Networks Pytorch | I have 2 images as input, x1 and x2 and try to use convolution as a similarity measure. The idea is that the learned weights substitute more traditional measure of similarity (cross correlation, NN, ...). Defining my forward function as follows:
def forward(self,x1,x2):
out_conv1a = self.conv1(x1)
out_conv2a = self.conv2(out_conv1a)
out_conv3a = self.conv3(out_conv2a)
out_conv1b = self.conv1(x2)
out_conv2b = self.conv2(out_conv1b)
out_conv3b = self.conv3(out_conv2b)
Now for the similarity measure:
out_cat = torch.cat([out_conv3a, out_conv3b],dim=1)
futher_conv = nn.Conv2d(out_cat)
My question is as follows:
1) Would Depthwise/Separable Convolutions as in the google paper yield any advantage over 2d convolution of the concatenated input. For that matter can convolution be a similarity measure, cross correlation and convolution are very similar.
2) It is my understanding that the groups=2 option in conv2d would provide 2 separate inputs to train weights with, in this case each of the previous networks weights. How are these combined afterwards?
For a basic concept see here.
| Using a nn.Conv2d layer you assume weights are trainable parameters. However, if you want to filter one feature map with another, you can dive deeper and use torch.nn.functional.conv2d to explicitly define both input and filter yourself:
out = torch.nn.functional.conv2d(out_conv3a, out_conv3b)
| https://stackoverflow.com/questions/52616941/ |
pytorch out of GPU memory | I am trying to implement Yolo-v2 in pytorch. However, I seem to be running out of memory just passing data through the network. The model is large and is shown below. However, I feel like I'm doing something stupid here with my network (like not freeing memory somewhere). The network works as expected on cpu.
The test code (where memory runs out) is:
x = torch.rand(32,3,416, 416).cuda()
model = Yolov2().cuda()
y = model(x.float())
Question
Anything that is obviously wrong with my model?
How do I make this more efficient with memory?
Other comments?
The model:
import torch
from torch import nn
import torch.nn.functional as F
class Yolov2(nn.Module):
def __init__(self):
super(Yolov2, self).__init__()
self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm2 = nn.BatchNorm2d(64)
self.conv3 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm3 = nn.BatchNorm2d(128)
self.conv4 = nn.Conv2d(in_channels=128, out_channels=64, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm4 = nn.BatchNorm2d(64)
self.conv5 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm5 = nn.BatchNorm2d(128)
self.conv6 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm6 = nn.BatchNorm2d(256)
self.conv7 = nn.Conv2d(in_channels=256, out_channels=128, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm7 = nn.BatchNorm2d(128)
self.conv8 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm8 = nn.BatchNorm2d(256)
self.conv9 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm9 = nn.BatchNorm2d(512)
self.conv10 = nn.Conv2d(in_channels=512, out_channels=256, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm10 = nn.BatchNorm2d(256)
self.conv11 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm11 = nn.BatchNorm2d(512)
self.conv12 = nn.Conv2d(in_channels=512, out_channels=256, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm12 = nn.BatchNorm2d(256)
self.conv13 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm13 = nn.BatchNorm2d(512)
self.conv14 = nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm14 = nn.BatchNorm2d(1024)
self.conv15 = nn.Conv2d(in_channels=1024, out_channels=512, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm15 = nn.BatchNorm2d(512)
self.conv16 = nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm16 = nn.BatchNorm2d(1024)
self.conv17 = nn.Conv2d(in_channels=1024, out_channels=512, kernel_size=1, stride=1, padding=0, bias=False)
self.batchnorm17 = nn.BatchNorm2d(512)
self.conv18 = nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm18 = nn.BatchNorm2d(1024)
self.conv19 = nn.Conv2d(in_channels=1024, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm19 = nn.BatchNorm2d(1024)
self.conv20 = nn.Conv2d(in_channels=1024, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm20 = nn.BatchNorm2d(1024)
self.conv21 = nn.Conv2d(in_channels=3072, out_channels=1024, kernel_size=3, stride=1, padding=1, bias=False)
self.batchnorm21 = nn.BatchNorm2d(1024)
self.conv22 = nn.Conv2d(in_channels=1024, out_channels=125, kernel_size=1, stride=1, padding=0)
def reorg_layer(self, x):
stride = 2
batch_size, channels, height, width = x.size()
new_ht = int(height/stride)
new_wd = int(width/stride)
new_channels = channels * stride * stride
# from IPython.core.debugger import Tracer; Tracer()()
passthrough = x.permute(0, 2, 3, 1)
passthrough = passthrough.contiguous().view(-1, new_ht, stride, new_wd, stride, channels)
passthrough = passthrough.permute(0, 1, 3, 2, 4, 5)
passthrough = passthrough.contiguous().view(-1, new_ht, new_wd, new_channels)
passthrough = passthrough.permute(0, 3, 1, 2)
return passthrough
def forward(self, x):
out = F.max_pool2d(F.leaky_relu(self.batchnorm1(self.conv1(x)), negative_slope=0.1), 2, stride=2)
out = F.max_pool2d(F.leaky_relu(self.batchnorm2(self.conv2(out)), negative_slope=0.1), 2, stride=2)
out = F.leaky_relu(self.batchnorm3(self.conv3(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm4(self.conv4(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm5(self.conv5(out)), negative_slope=0.1)
out = F.max_pool2d(out, 2, stride=2)
out = F.leaky_relu(self.batchnorm6(self.conv6(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm7(self.conv7(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm8(self.conv8(out)), negative_slope=0.1)
out = F.max_pool2d(out, 2, stride=2)
out = F.leaky_relu(self.batchnorm9(self.conv9(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm10(self.conv10(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm11(self.conv11(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm12(self.conv12(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm13(self.conv13(out)), negative_slope=0.1)
# from IPython.core.debugger import Tracer; Tracer()()
passthrough = self.reorg_layer(out)
out = F.max_pool2d(out, 2, stride=2)
out = F.leaky_relu(self.batchnorm14(self.conv14(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm15(self.conv15(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm16(self.conv16(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm17(self.conv17(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm18(self.conv18(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm19(self.conv19(out)), negative_slope=0.1)
out = F.leaky_relu(self.batchnorm20(self.conv20(out)), negative_slope=0.1)
out = torch.cat([passthrough, out], 1)
out = F.leaky_relu(self.batchnorm21(self.conv21(out)), negative_slope=0.1)
out = self.conv22(out)
return out
Additional Info:
Torch version is '0.4.1.post2'
Running on aws p2.xlarge (limit 12gb GPU memory).
The number of parameters for this model is 67137565. Which would occupy <500MB.
this thread from pytorch might be related.
| I would try to use smaller batch sizes. Start from 1 and then check what is your maximum.
I can also try to reduce your input Tensor dimensions.
Your network is not so small for your GPU
| https://stackoverflow.com/questions/52621570/ |
Is there any way I can download the pre-trained models available in PyTorch to a specific path? | I am referring to the models that can be found here: https://pytorch.org/docs/stable/torchvision/models.html#torchvision-models
| As, @dennlinger mentioned in his answer : torch.utils.model_zoo, is being internally called when you load a pre-trained model.
More specifically, the method: torch.utils.model_zoo.load_url() is being called every time a pre-trained model is loaded. The documentation for the same, mentions:
The default value of model_dir is $TORCH_HOME/models where
$TORCH_HOME defaults to ~/.torch.
The default directory can be overridden with the $TORCH_HOME
environment variable.
This can be done as follows:
import torch
import torchvision
import os
# Suppose you are trying to load pre-trained resnet model in directory- models\resnet
os.environ['TORCH_HOME'] = 'models\\resnet' #setting the environment variable
resnet = torchvision.models.resnet18(pretrained=True)
I came across the above solution by raising an issue in the PyTorch's GitHub repository:
https://github.com/pytorch/vision/issues/616
This led to an improvement in the documentation i.e. the solution mentioned above.
| https://stackoverflow.com/questions/52628270/ |
Find all ReLU layer in a torchvision model | After I fetch a pre-trained model from torchvision.models, I want all the ReLU instance to register_backward_hook(f),which is like this:
for pos, module in self.model.features._modules.items():
for sub_module in module:
if isinstance(module, ReLU):
module.register_backward_hook(f)
The problems for me is how to find all ReLU in a model. For densenet161, the ReLU exists not only in model.features._modules but also in self-defined dense layer, eg. model.features._modules['denseblock1'][0]. For resnet151, the ReLU exists in model._modules and its self-define layer, eg model._modules['layer1'].
Is there any way to find all ReLU inside a model?
| A more elegant way to iterate over all components of a model is using modules()
method:
from torch import nn
for module in self.model.modules():
if isinstance(module, nn.ReLU):
module.register_backward_hook(f)
If you do not want to get all sub-modules, only the immediate ones, you may consider using children() method instead of modules(). You can also get the name of the sub module using named_modules() method.
| https://stackoverflow.com/questions/52637211/ |
Using TPUs with PyTorch | I am trying to use Google Cloud's TPU from Colab. I was able to do it following the tutorial by using Tensorflow.
Does anybody know if it is possible to make use of the TPUs using PyTorch?
If so how can I do it? Do you have any example?
| Check out our repository pytorch/xla where you can start training PyTorch models on TPUs.
Also, you can even use free TPUs on Colab with PyTorch with these Colab notebooks.
| https://stackoverflow.com/questions/52652214/ |
PyTorch - How to get learning rate during training? | While training, I'd like to know the value of learning_rate.
What should I do?
It's my code, like this:
my_optimizer = torch.optim.SGD(my_model.parameters(),
lr=0.001,
momentum=0.99,
weight_decay=2e-3)
Thank you.
| For only one parameter group like in the example you've given, you can use this function and call it during training to get the current learning rate:
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
| https://stackoverflow.com/questions/52660985/ |
CNN weights at input image location | Given a CNN, say AlexNet:
How could one relate kernel locations at the 3rd conv block, i.e 13x13 filter size to the input image. I want to compare the filters at different locations.
I was thinking of just bilinearly upsampling the location, from 13x13 to 224x224,
nn.Upsample(size = (224,224), mode='bilinear')
however it's hard to justify local correspondence.
| Using adaptive pooling, with adaptive pooling, one can reduce any feature map size.
Adaptive max pooling
| https://stackoverflow.com/questions/52665476/ |
Printing all the contents of a tensor | I came across this PyTorch tutorial (in neural_networks_tutorial.py) where they construct a simple neural network and run an inference. I would like to print the contents of the entire input tensor for debugging purposes. What I get when I try to print the tensor is something like this and not the entire tensor:
I saw a similar link for numpy but was not sure about what would work for PyTorch. I can convert it to numpy and may be view it, but would like to avoid the extra overhead. Is there a way for me to print the entire tensor?
| Though I don't suggest to do that, if you want, then
In [18]: torch.set_printoptions(edgeitems=1)
In [19]: a
Out[19]:
tensor([[-0.7698, ..., -0.1949],
...,
[-0.7321, ..., 0.8537]])
In [20]: torch.set_printoptions(edgeitems=3)
In [21]: a
Out[21]:
tensor([[-0.7698, 1.3383, 0.5649, ..., 1.3567, 0.6896, -0.1949],
[-0.5761, -0.9789, -0.2058, ..., -0.5843, 2.6311, -0.0008],
[ 1.3152, 1.8851, -0.9761, ..., 0.8639, -0.6237, 0.5646],
...,
[ 0.2851, 0.5504, -0.9471, ..., 0.0688, -0.7777, 0.1661],
[ 2.9616, -0.8685, -1.5467, ..., -1.4646, 1.1098, -1.0873],
[-0.7321, 0.7610, 0.3182, ..., 2.5859, -0.9709, 0.8537]])
| https://stackoverflow.com/questions/52673610/ |
How to extend a Loss Function Pytorch | I would like to create my own custom Loss function as a weighted combination of 3 Loss Function, something similar to:
criterion = torch.nn.CrossEntropyLoss(out1, lbl1) + \
torch.nn.CrossEntropyLoss(out2, lbl2) + \
torch.nn.CrossEntropyLoss(out3, lbl3)
I am doing it to address a multi-class multi-label classification problem.
Does it make sense? How to implement correctly such Loss Function in Pytorch?
Thanks
| Your way of approaching the problem seems correct but there's a typo in your code. Here's a fix for that:
loss1 = torch.nn.CrossEntropyLoss()(out1, lbl1)
loss2 = torch.nn.CrossEntropyLoss()(out2, lbl2)
loss3 = torch.nn.CrossEntropyLoss()(out3, lbl3)
final_loss = loss1 + loss2 + loss3
Then you can call .backward on final_loss which should then compute the gradients and backpropagate them.
Also, it's possible to weight each of the component losses where the weights are itself learned during the training process.
You can refer the discussions of combine-multiple-criterions-to-a-loss-function for more information.
| https://stackoverflow.com/questions/52690881/ |
what does THCudaTensor_data ( and THC in general ) do? | The program I am inspecting uses pytorch to load weights and cuda code to do the computations with the weights. My understanding of THC library is how tensors are implemented in the backend of pytorch ( and torch, maybe? ).
how is THC implemented ( I would really appreiciate some details if possible )?
what does THCudaTensor_data( THC_state, THCudaTensor* ) do? ( from the way it is used in the code, it seems like it is used to convert pytorch's tensor to an array in cuda. if this is the case, then would the function preserve all elements and the length of the array?)
| I am still not exactly sure of the inner-workings of THCudaTensor_data, but the behaviour that was tripping me up was: for n-dimensional tensor, THCudaTensor_data returns a flattened 1D array of the tensor.
Hope this helps
| https://stackoverflow.com/questions/52697871/ |
Minimize angle in pytorch | I'm trying to figure out how to minimize a scalar in pytorch that represents the angle of an axis/angle rotation. My target is a sample set of 3D vectors, my input is the target rotated by a particular axis/angle rotation (plus some gaussian noise). The axis is known and fixed. I want to find the angle using pytorch.
What I have so far is this nn.Module:
class AngleModel(torch.nn.Module):
def __init__(self):
super(AngleModel, self).__init__()
self.angle = nn.Parameter(Variable(torch.Tensor([0.0]), requires_grad=True))
self.qw = torch.cos(self.angle / 2.)
self.qx = 0.0
self.qy = 0.0
self.qz = torch.sin(self.angle / 2.)
def forward(self, input):
matrix_np = transform_from_pq([0, 0, 0, self.qw, self.qx, self.qy, self.qz])
matrix = torch.from_numpy(matrix_np)
input_ext = torch.cat((input, torch.ones(input.size(0)).reshape(-1, 1)), 1)
output = torch.matmul(input_ext.float(), matrix.float())
return output[:, :3]
However using this in an optimizer fails because model.parameters() returns an empty list (i.e. "empty" generator).
I'm completely new to pytorch. What am I doing wrong?
Relevant code
Initialization:
def _init_model(self):
self.model = AngleModel()
self.crit = torch.nn.MSELoss()
l_rate = 0.01
print(list(self.model.parameters()))
self.optim = torch.optim.SGD(self.model.parameters(), lr = l_rate)
self.epochs = 2000
Learning function:
for epoch in range(self.epochs):
inputs = torch.from_numpy(normalize(input))
labels = torch.from_numpy(normalize(target))
_x = Variable(inputs, requires_grad = True) # without it complains about no grad_fn
_y = Variable(labels)
self.optim.zero_grad()
outputs = self.model.forward(_x)
loss = self.crit(outputs, _y)
loss.backward()
self.optim.step()
print("Epoch %6d loss %05.3f; %s" % (epoch, loss.data[0], self.model.angle))
Update 1:
Code of the Module updated
Surrounding code added
This at least does not throw any errors anymore but also does not optimize angle
| Here are the necessary changes to the AngleModel class to make it work:
class AngleModel(nn.Module):
def __init__(self):
super(AngleModel, self).__init__()
self.angle = nn.Parameter(torch.tensor(0.0))
def forward(self, input):
qw = torch.cos(self.angle / 2.)
qx = 0.0
qy = 0.0
qz = torch.sin(self.angle / 2.)
matrix = torch.zeros(3, 3)
matrix[0, 0] = 1. - 2. * qy ** 2 - 2. * qz ** 2
matrix[1, 1] = 1. - 2. * qx ** 2 - 2. * qz ** 2
matrix[2, 2] = 1. - 2. * qx ** 2 - 2. * qy ** 2
matrix[0, 1] = 2. * qx * qy - 2. * qz * qw
matrix[1, 0] = 2. * qx * qy + 2. * qz * qw
matrix[0, 2] = 2. * qx * qz + 2 * qy * qw
matrix[2, 0] = 2. * qx * qz - 2 * qy * qw
matrix[1, 2] = 2. * qy * qz - 2. * qx * qw
matrix[2, 1] = 2. * qy * qz + 2. * qx * qw
output = torch.matmul(input, matrix)
return output
Among others the main reason that it hadn't been working before was that the graph wasn't consistent due to the intermediate use of numpy. Furthermore the quaternion components qw..qz had been calculated only once in the __init__ method. Their calculation had to move to the forward step too.
| https://stackoverflow.com/questions/52698444/ |
Does PyTorch seed affect dropout layers? | I came across the idea of seeding my neural network for reproducible results, and was wondering if pytorch seeding affects dropout layers and what is the proper way to seed my training/testing?
I'm reading the documentation here, and wondering if just placing these lines will be enough?
torch.manual_seed(1)
torch.cuda.manual_seed(1)
| You can easily answer your question with some lines of code:
import torch
from torch import nn
dropout = nn.Dropout(0.5)
torch.manual_seed(9999)
a = dropout(torch.ones(1000))
torch.manual_seed(9999)
b = dropout(torch.ones(1000))
print(sum(abs(a - b)))
# > tensor(0.)
Yes, using manual_seed is enough.
| https://stackoverflow.com/questions/52730405/ |
XOR neural network does not learn | I am trying to solve the very simple non-linear problem. It is XOR gate.
I my school knowledge. XOR can be solve by using 2 input nodes, 2 hidden layer nodes. And 1 output. It is binary classification problem.
I generate the 1000 of random integer number it is 0 or 1 and then do backpropagation. But for some unknown reason my network has not learned anything. The training accuracy is constant at 50.
# coding: utf-8
import matplotlib
import torch
import torch.nn as nn
from torch.autograd import Variable
matplotlib.use('TkAgg') # My buggy OSX 10.13.6 requires this
import matplotlib.pyplot as plt
from torch.utils.data import Dataset
from tqdm import tqdm
import random
N = 1000
batch_size = 10
epochs = 40
hidden_size = 2
output_size = 1
lr = 0.1
def return_xor(N):
tmp_x = []
tmp_y = []
for i in range(N):
a = (random.randint(0, 1) == 1)
b = (random.randint(0, 1) == 1)
if (a and not b) or (not a and b):
q = True
else:
q = False
input_features = (a, b)
output_class = q
tmp_x.append(input_features)
tmp_y.append(output_class)
return tmp_x, tmp_y
# In[495]:
# Training set
x, y = return_xor(N)
x = torch.tensor(x, dtype=torch.float, requires_grad=True)
y = torch.tensor(y, dtype=torch.float, requires_grad=True)
# Test dataset
x_test, y_test = return_xor(100)
x_test = torch.tensor(x_test)
y_test = torch.tensor(y_test)
class MyDataset(Dataset):
"""Define my own `Dataset` in order to use `Variable` with `autograd`"""
def __init__(self, x, y):
self.x = x
self.y = y
def __getitem__(self, index):
return self.x[index], self.y[index]
def __len__(self):
return len(self.x)
dataset = MyDataset(x, y)
test_dataset = MyDataset(x_test, y_test)
print(dataset.x.shape)
print(dataset.y.shape)
# Make data iterable by loading to a loader. Shuffle, batch_size kwargs put them here in order to remind I myself
train_loader = torch.utils.data.DataLoader(dataset=dataset, batch_size=batch_size, shuffle=True)
test_loader = torch.utils.data.DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=False)
print(f"They are {len(train_loader)} batches in the dataset")
shown = 0
for (x, y) in train_loader:
if shown == 1:
break
print(f"{x.shape} {x.dtype}")
print(f"{y.shape} {y.dtype}")
shown += 1
class MyModel(nn.Module):
"""
Binary classification
2 input nodes
2 hidden nodes
1 output node
"""
def __init__(self, input_size, hidden_size, output_size):
super().__init__()
self.fc1 = torch.nn.Linear(input_size, hidden_size)
self.fc2 = torch.nn.Linear(hidden_size, output_size)
self.sigmoid = torch.nn.Sigmoid()
def forward(self, out):
out = self.fc1(out)
out = self.fc2(out)
out = self.sigmoid(out)
return out
# Create my network
net = MyModel(dataset.x.shape[1], hidden_size, output_size)
CUDA = torch.cuda.is_available()
if CUDA:
net = net.cuda()
criterion = torch.nn.BCELoss(reduction='elementwise_mean')
optimizer = torch.optim.SGD(net.parameters(), lr=lr)
# Train the network
correct_train = 0
total_train = 0
for epoch in range(epochs):
for i, (batches, labels) in enumerate(train_loader):
batcesh = Variable(batches.float())
labels = Variable(labels.float())
output = net(batches) # Forward pass
optimizer.zero_grad()
loss = criterion(output, labels.view(10, 1))
loss.backward()
optimizer.step()
total_train += labels.size(0)
correct_train += (predicted == labels.long()).sum()
if (i + 1) % 10 == 0:
print(f"""
Epoch {epoch+1}/{epochs},
Iteration {i+1}/{len(dataset)//batch_size},
Training Loss: {loss.item()},
Training Accuracy: {100*correct_train/total_train}
""")
Solution:
I did initialized weight, Adaptive learning rate
https://github.com/elcolie/nnbootcamp/blob/master/Study-XOR.ipynb
| I am not sure what results you are getting, as the code you have posted in the question doesn't work (It gives errors with pytorch 0.4.1 like predicted not defined etc). But syntax issues apart, there are other problems.
Your model is not actually two layer as it does not use non-linearity after the first output. Effectively this is one layer network and to fix that you can modify your model's forward as follows:
def forward(self, out):
out = torch.nn.functional.relu(self.fc1(out))
out = self.fc2(out)
out = self.sigmoid(out)
return out
You can try sigmoid or tanh non-linearity as well... but the non-linearity is a must. This should fix the problem.
I also see that you are using only 2 hidden units. This might be restrictive and you might want to increase that to something like 5 or 10.
| https://stackoverflow.com/questions/52738146/ |
How to save LambdaLR scheduler in pytorch with lambda function? | Running pytorch 0.4.1 with python 3.6 I encountered this problem:
I cannot torch.save my learning rate scheduler because python won't pickle a lambda function:
lambda1 = lambda epoch: epoch // 30
scheduler = LambdaLR(optimizer, lr_lambda=lambda1)
torch.save(scheduler.state_dict(), 'scheduler.pth.tar')
results with an error
PicklingError: Can't pickle <function <lambda> at 0x7f7583fe92f0>:
attribute lookup <lambda> on __main__ failed
How can I save my scheduler?
I know that using a proper function instead of a lambda function for lambda1 can be saved, but I need a lambda function because I want to be able to control this function when it is defined (for instance I want to be able to change the fixed 30 in the denominator).
How can this be done and still allows me to save the scheduler?
| If one wishes to stay with default behavior of torch.save and torch.load, the lambda function can be replaced with a class, for example:
class LRPolicy(object):
def __init__(self, rate=30):
self.rate = rate
def __call__(self, epoch):
return epoch // self.rate
The scheduler is now
scheduler = LambdaLR(optimizer, lr_lambda=LRPolicy(rate=30))
Now the scheduler can be torch.saveed and torch.load without alternating the pickling module.
| https://stackoverflow.com/questions/52758051/ |
PyTorch RuntimeError Invalid argument 2 of size | I am experimenting with a neural network (PyTorch) and I get this error.
RuntimeError: invalid argument 2: size '[32 x 9216]' is invalid for input with 8192 elements at /pytorch/aten/src/TH/THStorage.cpp:84
My task is about image classification with AlexNet and I have backtracked the error to be the size of the images supplied to the neural network. My question is, given the network architecture with its parameters, how does one determine the correct image size required by the network?
As per my code below, I first transform the training images before feeding into the neural network. But I noticed the neural network can only accept the size of 224 and or else it gives the error above. For instance, my instinct was to apply transforms.RandomResizedCrop of size 64 but apparently this is wrong. Is there a formula to determine the size required?
Code
# transformation to be done on images
transform_train = transforms.Compose([
transforms.RandomResizedCrop(64),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
class AlexNet(nn.Module):
def __init__(self, num_classes=1000):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(64, 192, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(192, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * 6 * 6, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, num_classes),
)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), 256 * 6 * 6)
x = self.classifier(x)
return x
| I have figured out the algorithm of getting the right input size.
Out = float(((W−F+2P)/S)+1)
where
Out = Output shape
W = Image volume size (image size)
F = Receptive field (filter size)
P = Padding
S = Stride
Factoring in the given network hyperparameters,
The require Image size I need would be
W = (55 - 1) * 4 - 2(2) + 11
= 223
⩰ 224
| https://stackoverflow.com/questions/52761666/ |