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...
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/folde...
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.mea...
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.bac...
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.Com...
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, requi...
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 ...
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 Normal...
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 ...
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...
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...
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...
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 = ...
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).resh...
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)...
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 pape...
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 dr...
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 c...
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,...
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....
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, ...
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/...
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...
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/pacifina...
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 ...
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 advant...
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...
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, 1...
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...
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( ...
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 bu...
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.parameter...
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 conv...
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() ...
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):...
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: #...
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...
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 s...
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 blo...
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...
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 ...
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 smalle...
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 essentiall...
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.No...
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:...
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 si...
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 give...
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 embed...
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 abov...
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...
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 f...
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 overfitti...
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 lo...
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 take...
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)), ...
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 ther...
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) ...
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) e...
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 ...
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. ...
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_tra...
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.r...
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: imp...
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) (...
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, ...
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...
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] ...
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...
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, ...
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) # padd...
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...
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 ...
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 imp...
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 PyTorc...
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 save...
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 ...
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( ...
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 onl...
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. S...
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 " + ...
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. I...
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 w...
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,...
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 Var...
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 perf...
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 =...
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...
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 ...
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...
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 (3...
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 c...
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 ...
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. Howeve...
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...
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...
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 k...
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 an...
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...
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 ...
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 ...
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 ...
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(...
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 th...
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), ...
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) pri...
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 t...
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 t...
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__() ...
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 re...
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 si...
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.fl...
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 ...
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....
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_d...
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 b...
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 ...
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 ...
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() ## des...
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 ...
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.Co...
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: # C...
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_st...
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(s...
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,...
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 = torc...
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...
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...
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.app...
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 soft...
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("P...
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...
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_b...
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, whe...
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 ...
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 al...
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)](pr...
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...
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 f...
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 sugge...
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=...
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...
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 ...
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...
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 mod...
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 problem...
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(...
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') h...
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 s...
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, ...
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 m...
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...
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 TH...
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. ...
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...
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.cud...
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 r...
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. Eff...
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 a...
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 ...
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 i...
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) ...
https://stackoverflow.com/questions/52761666/