instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
ValueError: expected 2D or 3D input (got 1D input) PyTorch
class VAE(torch.nn.Module): def __init__(self, input_size, hidden_sizes, batch_size): super(VAE, self).__init__() self.input_size = input_size self.hidden_sizes = hidden_sizes self.batch_size = batch_size self.fc = torch.nn.Linear(input_size, hidden_sizes[0]) self.BN = torch.nn.BatchNorm1d(h...
When you build a nn.Module in pytorch for processing 1D signals, pytorch actually expects the input to be 2D: first dimension is the "mini batch" dimension. Thus you need to add a singleton dimesion to your X: x_sample, z_mu, z_var = vae(X[None, ...])
https://stackoverflow.com/questions/53500511/
Pytorch RuntimeError: size mismatch, m1: [1 x 7744], m2: [400 x 120]
In a simple CNN that classifies 5 objects, I get a size mis-match error: "RuntimeError: size mismatch, m1: [1 x 7744], m2: [400 x 120]" in the convolutional layer . my model.py file: import torch.nn as nn import torch.nn.functional as F class FNet(nn.Module): def __init__(self,device): # make your c...
If you have a nn.Linear layer in your net, you cannot decide "on-the-fly" what the input size for this layer would be. In your net you compute num_flat_features for every x and expect your self.fc1 to handle whatever size of x you feed the net. However, self.fc1 has a fixed size weight matrix of size 400x120 (that is e...
https://stackoverflow.com/questions/53500838/
PyTorch - parameters not changing
In an effort to learn how pytorch works, I am trying to do maximum likelihood estimation of some of the parameters in a multivariate normal distribution. However it does not seem to work for any of the covariance related parameters. So my question is: why does this code not work? import torch def make_covariance_ma...
The way you create your covariance matrix is not backprob-able: def make_covariance_matrix(sigma, rho): return torch.tensor([[sigma[0]**2, rho * torch.prod(sigma)], [rho * torch.prod(sigma), sigma[1]**2]]) When creating a new tensor from (multiple) tensors, only the values of your input ...
https://stackoverflow.com/questions/53503234/
Row-wise Element Indexing in PyTorch for C++
I am using the C++ frontend for PyTorch and am struggling with a relatively basic indexing problem. I have an 8 by 6 Tensor such as the one below: [ Variable[CUDAFloatType]{8,6} ] 0 1 2 3 4 5 0 1.7107e-14 4.0448e-17 4.9708e-06 1.1664e-08 9....
It turns out you can do this in a couple different ways. One with gather and one with index. From the PyTorch discussions where I asked the same question: Using torch::gather auto x = torch::randn({8, 6}); int64_t idx_data[8] = { 0, 3, 4, 4, 4, 4, 4, 4 }; auto idx = x.type().toScalarType(torch::kLong).tensorFromBlob(...
https://stackoverflow.com/questions/53507039/
How make customised dataset in Pytorch for images and their masks?
I have two dataset folder of tif images, one is a folder called BMMCdata, and the other one is the mask of BMMCdata images called BMMCmasks(the name of images are corresponds). I am trying to make a customised dataset and also split the data randomly to train and test. at the moment I am getting an error self.filenam...
answer given by @ptrblck in pytorch community. thank you # get all the image and mask path and number of images folder_data = glob.glob("D:\\Neda\\Pytorch\\U-net\\BMMCdata\\data\\*.tif") folder_mask = glob.glob("D:\\Neda\\Pytorch\\U-net\\BMMCmasks\\masks\\*.tif") # split these path using a certain percentage len...
https://stackoverflow.com/questions/53530751/
How do I split the training dataset into training, validation and test datasets?
I have a custom data set of images and its target. I have created a training data set in PyTorch. I want to split it into 3 parts: training, validation and test. How do I do it?
Once you have the "master" dataset you can use data.Subset to split it. Here's an example for random split import torch from torch.utils import data import random master = data.Dataset( ... ) # your "master" dataset n = len(master) # how many total elements you have n_test = int( n * .05 ) # number of test/val ele...
https://stackoverflow.com/questions/53532352/
Save and load checkpoint pytorch
i make a model and save the configuration as: def checkpoint(state, ep, filename='./Risultati/checkpoint.pth'): if ep == (n_epoch-1): print('Saving state...') torch.save(state,filename) checkpoint({'state_dict':rnn.state_dict()},ep) and then i want load this configuration : state_dict= torch....
You need to load rnn.state_dict() stored in the dictionary you loaded: rnn.load_state_dict(state_dict['state_dict']) Look at load_state_dict method for more information.
https://stackoverflow.com/questions/53538138/
What is the backward process of max operation in deep learning?
I know that the backward process of deep learning follows the gradient descent algorithm. However, there is never a gradient concept for max operation. How does deep learning frameworks like tensorflow, pytorch deal with the backward of 'max' operation like maxpooling?
You have to think of what the max operator actually does? That is: It returns or lets better say it propagates the maximum. And that's exactly what it does here - it takes two or more tensors and propagates forward (only) the maximum. It is often helpful to take a look at a short example: t1 = torch.rand(10, re...
https://stackoverflow.com/questions/53539348/
Pytorch: Normalize Image data set
I want to normalize custom dataset of images. For that i need to compute mean and standard deviation by iterating over the dataset. How can I normalize my entire dataset before creating the data set?
Well, let's take this image as an example: The first thing you need to do is decide which library you want to use: Pillow or OpenCV. In this example I'll use Pillow: from PIL import Image import numpy as np img = Image.open("test.jpg") pix = np.asarray(img.convert("RGB")) # Open the image as RGB Rchan = pix[:,:,0...
https://stackoverflow.com/questions/53542974/
How to mask weights in PyTorch weight parameters?
I am attempting to mask (force to zero) specific weight values in PyTorch. The weights I am trying to mask are defined as so in the def __init__ class LSTM_MASK(nn.Module): def __init__(self, options, inp_dim): super(LSTM_MASK, self).__init__() .... self.wfx = nn.Linear(inpu...
The element-wise operation always returns a FloatTensor. It is not possible to assign normal tensors as weight of layers. There are two possible options to deal with it. You can assign it to the data attribute of your weight, there it is possible assign normal tensors. Or alternatively you convert your result to an...
https://stackoverflow.com/questions/53544901/
Plot the derivative of a function with PyTorch?
I have this code: import torch import matplotlib.pyplot as plt x=torch.linspace(-10, 10, 10, requires_grad=True) y = torch.sum(x**2) y.backward() plt.plot(x.detach().numpy(), y.detach().numpy(), label='function') plt.legend() But, I got this error: ValueError: x and y must have same first dimension, but have shap...
I think the main problem is that your dimensions do not match. Why do you wan't to use torch.sum? This should work for you: # %matplotlib inline added this line only for jupiter notebook import torch import matplotlib.pyplot as plt x = torch.linspace(-10, 10, 10, requires_grad=True) y = x**2 # removed the sum...
https://stackoverflow.com/questions/53546141/
Pytorch Loading two Images from Dataloader
I'm trying to make a GAN which takes a lo-res image, and tries to create a hi-res image from it. To do this, I need to user a Dataloader which has both the hi-res and low-res training images stored in it. data_transform = transforms.Compose([transforms.Resize(imageSize), t...
Assuming you have similar names for hi & low resolution images (say img01_hi & img01_low), one option is to create a custom Dataloader that returns both images by overriding __getitem__ method. As both images are returned in one call, you can make sure they match by appending _hi & _low to the filename. Y...
https://stackoverflow.com/questions/53549717/
What transformation do I need to do in order to run dataset through neural network?
I'm new to deep learning and Pytorch, but I hope someone can help me out with this. My dataset contains images from different sizes. I'm trying to create a simple neural network that can classify images. However, I'm getting mismatch errors. Neural network class Net(nn.Module): def __init__(self): super(N...
In your first configuration, you have configured self.fc1 incorrectly. You need the input to be of dimensions 32 * 28 * 28 instead of 32 * 3 * 3 as your images are 32 * 32 and kernel and stride are 3 and 1 respectively. See this video for a simpler explanation. Try adjusting your second configuration yourself now, if y...
https://stackoverflow.com/questions/53559671/
How to convert a pytorch tensor of ints to a tensor of booleans?
I would like to cast a tensor of ints to a tensor of booleans. Specifically I would like to be able to have a function which transforms tensor([0,10,0,16]) to tensor([0,1,0,1]) This is trivial in Tensorflow by just using tf.cast(x,tf.bool). I want the cast to change all ints greater than 0 to a 1 and all ints equal ...
What you're looking for is to generate a boolean mask for the given integer tensor. For this, you can simply check for the condition: "whether the values in the tensor are greater than 0" using simple comparison operator (>) or using torch.gt(), which would then give us the desired result. # input tensor I...
https://stackoverflow.com/questions/53562417/
pytorch, How can i make same size of tensor model(x) and answer(x)?
I'm try to make a simple linear model to predict parameters of formula. y = 3*x1 + x2 - 2*x3 Unfortunately, there are some problem when i try to compute loss. def answer(x): return 3 * x[:,0] + x[:,1] - 2 * x[:,2] def loss_f(x): y = answer(x) y_hat = model(x) loss = ((y - y_hat).pow(2)).sum() / x.size(0) ...
You can use Tensor.view https://pytorch.org/docs/stable/tensors.html#torch.Tensor.view So something like answer(x.data).view(-1, 1) should do the trick.
https://stackoverflow.com/questions/53569050/
Get single random example from PyTorch DataLoader
How do I get a single random example from a PyTorch DataLoader? If my DataLoader gives minbatches of multiple images and labels, how do I get a single random image and label? Note that I don't want a single image and label per minibatch, I want a total of one example.
If you want to choose specific images from your Trainloader/Testloader, you should check out the Subset function from master: Here's an example how to use it: testset = ImageFolderWithPaths(root="path/to/your/Image_Data/Test/", transform=transform) subset_indices = [0] # select your indices here as a list sub...
https://stackoverflow.com/questions/53570732/
pytorch Crossentropy error in simple example of NN
H1, I am try to make NN model that satisfy simple formula. y = X1^2 + X2^2 But when i use CrossEntropyLoss for loss function, i get two different error message. First, when i set code like this x = torch.randn(batch_size, 2) y_hat = model(x) y = answer(x).long() optimizer.zero_grad() loss = loss_func(y_hat, y) los...
You are using the wrong loss function. CrossEntropyLoss is used for classification problems generally wheread your problem is that of regression. So you should use losses which are meant for regression like tasks like Mean Squared Error Loss, L1 Loss etc. Take a look at this, this, this and this.
https://stackoverflow.com/questions/53571621/
Most efficient way to use a large data set for PyTorch?
Perhaps this question has been asked before, but I'm having trouble finding relevant info for my situation. I'm using PyTorch to create a CNN for regression with image data. I don't have a formal, academic programming background, so many of my approaches are ad-hoc and just terribly inefficient. May times I can go bac...
Here is a concrete example to demonstrate what I meant. This assumes that you've already dumped the images into an hdf5 file (train_images.hdf5) using h5py. import h5py hf = h5py.File('train_images.hdf5', 'r') group_key = list(hf.keys())[0] ds = hf[group_key] # load only one example x = ds[0] # load a subset, slice ...
https://stackoverflow.com/questions/53576113/
How to get two scalars on same chart with tensorboardX?
The docs seem to indicate that add_custom_scalars_multilinechart does it but it is not working. Have something like this: from tensorboardX import SummaryWriter writer = SummaryWriter(comment='test') writer.add_custom_scalars_multilinechart(['loss/train', 'loss/test'], title='losses') for blahblah: ... writ...
Plot two scalars on same chart with tensorboardX: from tensorboardX import SummaryWriter Create two summaryWriter for two scalars writer_train = SummaryWriter('runs/train_0') writer_test = SummaryWriter('runs/test_0') Add scalars instances to the summaryWriter respective; they must have same tag, e.g.: "LOSS&quo...
https://stackoverflow.com/questions/53581904/
How to connect the input to the output directly using single fully connected layer in PyTorch?
I am new to deep learning and cnn and trying to get familiar with that field using CIFAR10 tutorial code from PyTorch website. So, in that code I was playing with removing/adding layers to better understand the effect of them and I tried to connect the input(which is the initial data with the batch of 4 images) to the ...
There are two obvious errors in your modified code (from the official ones from PyTorch webpage). First, torch.nn.Linear(in_features, out_features) is the correct syntax. But, you're passing 768 * 4 * 4 as in_features. This is 4 times the actual number of neurons (pixels) in one CIFAR10 image (32*32*3 = 3072). The ...
https://stackoverflow.com/questions/53586245/
Pytorch - TypeError: 'torch.Size' object cannot be interpreted as an integer
Hi I am training a PyTorch model and occurred this error: ----> 5 for i, data in enumerate(trainloader, 0): TypeError: 'torch.Size' object cannot be interpreted as an integer Not sure what this error means. You can find my code here : model.train() for epoch in range(10): running_loss = 0 for i, da...
Your problem is the __len__ function. You cannot use the shape as return value. Here is an example for illustration: import torch class Foo: def __init__(self, data): self.data = data def __len__(self): return self.data.shape myFoo = Foo(data=torch.rand(10, 20)) print(len(myFoo)) Will raise...
https://stackoverflow.com/questions/53588623/
Train SqueezeNet model using MNIST dataset Pytorch
I want to train SqueezeNet 1.1 model using MNIST dataset instead of ImageNet dataset. Can i have the same model as torchvision.models.squeezenet? Thanks!
TorchVision provides only ImageNet data pretrained model for the SqueezeNet architecture. However, you can train your own model using MNIST dataset by taking only the model (but not the pre-trained one) from torchvision.models. In [10]: import torchvision as tv # get the model architecture only; ignore `pretrained` f...
https://stackoverflow.com/questions/53593363/
Distrubuted PyTorch code halts on multiple nodes when using MPI backend
I am trying to run Pytorch code on three nodes using openMPI but the code just halts without any errors or output. Eventually my purpose is to distribute a Pytorch graph on these nodes. Three of my nodes are connected in same LAN and have SSH access to each other without password and have similar specifications: Ubu...
Apologies for replying late to this, but I could solve the issue by adding --mca btl_tcp_if_include eth1 flag to mpirun command. The reason for halt was that openMPI, by default, tries to locate and communicate with other nodes over local loopback network interface e.g. lo. We have to explicitly specify which interfa...
https://stackoverflow.com/questions/53596010/
Size mismatch for fc.bias and fc.weight in PyTorch
I used the transfer learning approach to train a model and saved the best-detected weights. In another script, I tried to use the saved weights for prediction. But I am getting errors as follows. I have used ResNet for finetuning the network and have 4 classes. RuntimeError: Error(s) in loading state_dict for ResNet:...
Cause: You trained a model derived from resnet18 in this way: model_ft = models.resnet18(pretrained=True) num_ftrs = model_ft.fc.in_features model_ft.fc = nn.Linear(num_ftrs, 4) That is, you changed the last nn.Linear layer to output 4 dim prediction instead of the default 1000. When you try and load the model for ...
https://stackoverflow.com/questions/53612835/
Copy GpuMat to CUDA Tensor
I am trying to run model inference in C++. I succesfully traced model in Python with torch.jit.trace. I am able to load model in C++ using torch::jit::load(). I was able to perform inference both on cpu and gpu, however the starting point was always torch::from_blob method which seems to be creating cpu-side tensor. Fo...
Here is an example: //define the deleter ... void deleter(void* arg) {}; //your convert function cuda::GpuMat gImage; //build or load your image here ... std::vector<int64_t> sizes = {1, static_cast<int64_t>(gImage.channels()), static_cast<int64_t>(gImage.rows), ...
https://stackoverflow.com/questions/53615833/
Auto-encoder for vector encodings
Here is an autoencoder I wrote to encode two vectors : [1,2,3] & [1,2,3] The vectors are created in : features = torch.tensor(np.array([ [1,2,3],[1,2,3] ])) This works as per code : %reset -f epochs = 1000 from pylab import plt plt.style.use('seaborn') import torch.utils.data as data_utils import torch impor...
your Dataset (inside DataLoader) returns only image per item without label. When you iterate and expecting each item to be (image, _) you are trying to unpack a feature without a label into image and _ and this is not possible. This is why you get "not enough values to unpack" error
https://stackoverflow.com/questions/53621440/
PyTorch optimizer.step() function doesn't update weights
The code can be seen below. The problem is, that the optimizer.step() part doesn't work. I'm printing model.parameters() before and after the training, and the weights don't change. I'm trying to make a perceptron that can solve the AND-problem. I've been successful in doing this with my own tiny library, where I've i...
Welcome to stackoverflow! The issue here is you are trying to perform back-propagation through a non-differentiable function. Non-differentiable means that no gradients can flow back through them, implying that all trainable weights applied before them will not be updated by your optimizer. Such functions are easy to ...
https://stackoverflow.com/questions/53622076/
How do I display a single image in PyTorch?
How do I display a PyTorch Tensor of shape (3, 224, 224) representing a 224x224 RGB image? Using plt.imshow(image) gives the error: TypeError: Invalid dimensions for image data
Given a Tensor representing the image, use .permute() to put the channels as the last dimension: plt.imshow( tensor_image.permute(1, 2, 0) ) Note: permute does not copy or allocate memory, and from_numpy() doesn't either.
https://stackoverflow.com/questions/53623472/
Updating pre-trained Deep Learning model with respect to new data points
Considering the example of Image classification on ImageNet, How to update the pre-trained model using the new data points. I have loaded the pre-trained model. I have a new data point that is quite different from the distribution of the original data on which the model was previously trained. So, I would like to upda...
If you don't want to change the output of the classifier (i.e. the number of classes), then you can simply continue training the model with new example images, assuming that they are reshaped to the same shape that the pretrained model accepts. On the other hand, if you want to change the number of classes in a pre-t...
https://stackoverflow.com/questions/53624766/
Differences between `torch.Tensor` and `torch.cuda.Tensor`
We can allocate a tensor on GPU using torch.Tensor([1., 2.], device='cuda'). Are there any differences using that way rather than torch.cuda.Tensor([1., 2.]), except we can pass in a specific CUDA device to the former one? Or in other words, in which scenario is torch.cuda.Tensor() necessary?
So generally both torch.Tensor and torch.cuda.Tensor are equivalent. You can do everything you like with them both. The key difference is just that torch.Tensor occupies CPU memory while torch.cuda.Tensor occupies GPU memory. Of course operations on a CPU Tensor are computed with CPU while operations for the GPU / CU...
https://stackoverflow.com/questions/53628940/
Why does this error pop up while working with Deep Q learning?
I have been working with Deep Q Learning on Windows 10 Machine. I have version 0.4.1 of pytorch with NVIDA graphics card. def select_action(self, state): probs = F.softmax(self.model(Variable(state, volatile = True))*7) action = probs.multinomial() return action.data[0,0] From this section of the code, I...
Based on the documentation you didn't specify the num_samples of multinomial function to draw your multinomial distribution. torch.multinomial(input, num_samples, replacement=False, out=None) Returns a tensor where each row contains num_samples indices sampled from the multinomial probability distribu...
https://stackoverflow.com/questions/53639839/
Unexpected increase in validation error in MNIST Pytorch
I'm a bit new to the whole field and thus decided to work on the MNIST dataset. I pretty much adapted the whole code from https://github.com/pytorch/examples/blob/master/mnist/main.py, with only one significant change: Data Loading. I didn't want to use the pre-loaded dataset within Torchvision. So I used MNIST in CSV....
Long story short: you need to change item = self.X[idx] to item = self.X[idx].copy(). Long story long: T.ToTensor() runs torch.from_numpy, which returns a tensor which aliases the memory of your numpy array dataset.X. And T.Normalize() works inplace, so each time the sample is drawn it has mean subtracted and is divid...
https://stackoverflow.com/questions/53652015/
Why was the method of a class called without mentioning the method?
I am currently going through this pytorch tutorial but I think this problem is one regarding Python classes in general: https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html#sphx-glr-beginner-blitz-neural-networks-tutorial-py Specifically, a class called Net was created and we created an object cal...
If you check the source code of nn.Module you will see that it implements __call__, which makes its instances (and instances of its subclasses) callable. def __call__(self, *input, **kwargs): for hook in self._forward_pre_hooks.values(): hook(self, input) if torch.jit._tracing: result = self._...
https://stackoverflow.com/questions/53653532/
VSCode bug with PyTorch DataLoader?
The following code example works in Python, but fails in VSCode in Linux (but not VSCode in Windows). I am wondering if there is something wrong with my code, or if there is something wrong with VSCode under Linux? #Test of PyTorch DataLoader and Visual Studio Code from torch.utils.data import Dataset, DataLoader cl...
Have you tried with num_workers=0? May be VS Code is not able to spawn a new process properly on linux.
https://stackoverflow.com/questions/53660465/
Implementing a many-to-many regression task
Sorry if I present my problem not clearly, English is not my first language Problem Short description: I want to train a model which map input x (with shape of [n_sample, timestamp, feature]) to an output y (with exact same shape). It's like mapping 2 space Longer version: I have 2 float ndarrays of shape [n_sampl...
It seems the network learning nothing from your data, hence the loss fluctuation (since weights depends on random initialization only). There are something you can try: Try to normalize the data (this suggestion is quite broad, but I can't give you more details since I don't have your data, but normalize it to a speci...
https://stackoverflow.com/questions/53667213/
in-place shuffle torch.Tensor in the order of a numpy.ndarray
I want to change the order of elements of a torch.Tensor from default to a numpy.ndarray. In other words, I want to shuffle it so that the order of its elements be specified with a numpy array; the important thing about this problem is that I don't want any third object to be created (because of memory limits) Is there...
Edit: This should be an in-place version: import torch import numpy as np t = torch.rand(10) print('Original Tensor:', t) order = np.array(range(10)) np.random.shuffle(order) print('Order:', order) # in-place changing of values t[np.array(range(10))] = t[order] print('New Tensor:', t) Output: Original Tensor: te...
https://stackoverflow.com/questions/53673575/
Can pytorch's autograd handle torch.cat?
I'm trying to implement a simple neural network that is supposed to learn an grayscale image. The input consist of the 2d indices of a pixel, the output should be the value of that pixel. The net is constructed as follows: Each neuron is connected to the input (i.e. the indices of the pixel) as well as to the output o...
Yes, torch.cat is backprob-able. So you use it without problems for this. What's the problem here is that you define a new optimizer at every iteration. Instead you should define it once after you defined your model. So having this changed the code works fine and loss is decreasing continuously. I also added a print...
https://stackoverflow.com/questions/53683116/
Appending a recurrent layer to PyTorch LSTM model with different hidden size
I'm developing a BI-LSTM model for sequence analysis using PyTorch. For which I am using torch.nn.LSTM. Using that module, you can have several layers with just passing a parameter num_layers to be the number of layers (e.g., num_layers=2). However all of them will have the same hidden_size which is partially fine for ...
If I'm not mistaken this can be done like this: import torch.nn as nn import torch.nn.functional as F class RnnWith2HiddenSizesModel(nn.Module): def __init__(self): super(RnnWith2HiddenSizesModel, self).__init__() self.rnn = nn.LSTM(input_size=10, hidden_size=20, num_layers=2) self.rnn_two...
https://stackoverflow.com/questions/53686052/
can't find the inplace operation: one of the variables needed for gradient computation has been modified by an inplace operation
I am trying to compute a loss on the jacobian of the network (i.e. to perform double backprop), and I get the following error: RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation I can't find the inplace operation in my code, so I don't know which line to fix. ...
grad_output.zero_() is in-place and so is grad_output[:, i-1] = 0. In-place means "modify a tensor instead of returning a new one, which has the modifications applied". An example solution which is not in-place is torch.where. An example use to zero out the 1st column import torch t = torch.randn(3, 3) ixs = torch.ara...
https://stackoverflow.com/questions/53691156/
PyTorch - loading images without sub folders
First of all I wanted to say that I am new to PyTorch, so i apologize in advice if the level of my questions is not that high. I was wondering if you can help me with something (I actually have 2 questions). The story behind them: I am working on image classification. My test data is divided into sub folders based on t...
It depends if you're using operations that depend on other items in the batch. If you're using things like batch normalization it may, but in general if your network processes batch items separately, it doesn't. If you check the documentation of torch.utils.data.Dataset, you will see that a dataset essentially only re...
https://stackoverflow.com/questions/53693431/
torch.utils.data.dataloader outputs TypeError: 'module' object is not callable
So im trying to learn pytorch and i got this code from a tutorial and its just there to import a mnist dataset but it outputs "TypeError: 'module' object is not callable" In the tutorial "dataloader" was written as "Dataloader" but when i run it like that it outputs "AttributeError: module 'torch.utils.data' ha...
It's neither dataloader nor Dataloader but DataLoader :) Side-note: if you're new to PyTorch, consider using the newest version 1.0. torch.autograd.Variable is deprecated as of PyTorch 0.4.1 (I believe) so you're either using an older version of PyTorch or an outdated tutorial.
https://stackoverflow.com/questions/53693999/
Why we need image.to('CUDA') when we have model.to('CUDA')
I'm taking a course on PyTorch. And I'm wondering why we need to separately tell to torch.utils.data.DataLoader output on what device it's running on. If the model is already on CUDA why doesn't it automatically change the inputs accordingly? This pattern seems funny to me: model.to(device) for ii, (inputs, labels) i...
When you call model.to(device) (assuming device is a GPU) your model parameters will be moved to your GPU. Regarding to your comment: they are moved from CPU memory to GPU memory then. By default newly created tensors are created on CPU, if not specified otherwise. So this applies also for your inputs and labels. The...
https://stackoverflow.com/questions/53695105/
Issues importing pytorch with conda
My system is: x86_64 DISTRIB_ID=LinuxMint DISTRIB_RELEASE=17.1 DISTRIB_CODENAME=rebecca DISTRIB_DESCRIPTION="Linux Mint 17.1 Rebecca" NAME="Ubuntu" VERSION="14.04.5 LTS, Trusty Tahr" ID=ubuntu ID_LIKE=debian PRETTY_NAME="Ubuntu 14.04.5 LTS" VERSION_ID="14.04" HOME_URL="http://www.ubuntu.com/" SUPPORT_URL="http://help...
If you would like to use PyTorch, install it in your local environment using conda create -n pytorch_env python=3 source activate pytorch_env conda install pytorch-cpu torchvision -c pytorch Go to python shell and import using the command import torch
https://stackoverflow.com/questions/53697522/
pytorch equivalent tf.gather
I'm having some trouble porting some code over from tensorflow to pytorch. So I have a matrix with dimensions 10x30 representing 10 examples each with 30 features. Then I have another matrix with dimensions 10x5 containing indices of the the 5 closest examples for each examples in the first matrix. I want to 'gather' ...
How about this? matrix1 = torch.randn(10, 30) matrix2 = torch.randint(high=10, size=(10, 5)) gathered = matrix1[matrix2] It uses the trick of indexing with an array of integers.
https://stackoverflow.com/questions/53697596/
How can I compute the tensor in Pytorch efficiently?
I have a tensor x and x.shape=(batch_size,10), now I want to take x[i][0] = x[i][0]*x[i][1]*...*x[i][9] for i in range(batch_size) Here is my code: for i in range(batch_size): for k in range(1, 10): x[i][0] = x[i][0] * x[i][k] But when I implement this in forward() and call loss.backward(), the sp...
It is slow because you use two for loops. You can use .prod See: https://pytorch.org/docs/stable/torch.html#torch.prod In your case, x = torch.prod(x, dim=1) or x = x.prod(dim=1) should work
https://stackoverflow.com/questions/53699675/
How to slice Torch images as numpy images
I am working on a problem in which I have the coordinates to slice the image like X cordinate, Y coordinate, Height, width of the region to crop So if if I have torch image obtained using img = Variable(img.cuda()) how can we slice this image to get that specific area of image [y:y+height, x:x+width] . Thank...
If I understand your question correctly, then you can do it just the same way as in numpy. Here is a short example: import torch t = torch.rand(5, 5) # original matrix print(t) h = 2 w = 2 x = 1 y = 1 # cropped out matrix print(t[x:x+h, y:y+w]) Output: tensor([[ 0.5402, 0.4106, 0.9904, 0.9556, 0.2217], ...
https://stackoverflow.com/questions/53706452/
PyTorch - applying attention efficiently
I have build a RNN language model with attention and I am creating context vector for every element of the input by attending all the previous hidden states (only one direction). The most straight forward solution in my opinion is using a for-loop over the RNN output, such that each context vector is computed one afte...
Ok, for clarity: I assume we only really care about vectorizing the for loop. What is the shape of x? Assuming x is 2-dimensional, I have the following code, where v1 executes your loop and v2 is a vectorized version: import torch import torch.nn.functional as F torch.manual_seed(0) x = torch.randn(3, 6) def v1(): ...
https://stackoverflow.com/questions/53706462/
pytorch vgg model test on one image
I've trained a vgg model, this is how I transformed the test data test_transform_2= transforms.Compose([transforms.RandomResizedCrop(224), transforms.ToTensor()]) test_data = datasets.ImageFolder(test_dir, transform=test_transform_2) the model's finished training now I want to ...
Your image is [h, w, 3] where 3 means the rgb channel, and pytorch expects [b, 3, h, w] where b is batch size. So you can reshape it by calling do that by calling reshaped = img.permute(2, 0, 1).unsqueeze(0). I think there is also a utility function for that somewhere, but I can't find it right now. So in your case t...
https://stackoverflow.com/questions/53710313/
Can I input a Byte Tensor to my RNN/LSTM model?
I am developing an RNN/LSTM model to which I want to encode the sequence in a ByteTensor to save memory as I am limited to a very tight memory. However, when I do so, the model returns the following error: Expected object of scalar type Byte but got scalar type Float for argument #2 'mat2' So, there seems to be s...
It means that inside the model there are float tensors which are being used to operate on your byte tensor (most likely operands in matrix multiplications, additions, etc). I believe you can technically cast them to byte by executing model.type(torch.uint8), but your approach will sooner or later fail anyway - since in...
https://stackoverflow.com/questions/53711360/
Will pytorch performs correctly with python calculate codes in net?
Take the fake codes below as an example: class(): def forward(input): x = some_torch_layers(input) x = some_torch_layers(x) ... x = sum(x) # or numpy or other operations x = some_torch_layers(x) return x Will the pytorch net operates well? Especially, while the sum...
TL;DR No. In order for PyTorch to "perform well" it needs to propagate gradients through the net. PyTorch doesn't (and can't) know how to differentiate an arbtrary numpy code, it can only propagate gradients through PyTorch tensor operations. In your examples the gradients will stop at the numpy sum so only the top-mo...
https://stackoverflow.com/questions/53721444/
PRelue is not supperted with mmdnn?
I converted my caffe model to IR successfully, error happened when I tried convert IR to pytorch: Pytorch Emitter has not supported operator [PRelu] How should I deal with that please?
Yes MMdnn support supports LeakyRelu. Check the link below for pytorch_emitter.py implementation from MMdnn. pytorch_emitter.py If you check the implementation you will find all the supported operations and it doesn't include PRelu.
https://stackoverflow.com/questions/53725125/
torch in-place operations to save memory (softmax)
Some operations in torch are executed in-place. Shorthand operators like += for example. Is it possible to get in-place execution for other operations, such as softmax? I'm currently working with language processing. The model produces a long sequence of probability distributions over a large vocabulary. This final o...
I have created an in-place version of softmax: import numpy as np import torch import torch.nn.functional as F # in-place version t = torch.tensor(np.ones((100,200))) torch.exp(t, out=t) summed = torch.sum(t, dim=1, keepdim=True) t /= summed # original version t2 = torch.tensor(np.ones((100,200))) softmax = F.softma...
https://stackoverflow.com/questions/53732209/
PyTorch - Incorrect labeling using torchvision.datasets.ImageFolder
I have structured my dataset in the following way: dataset/train/0/456.jpg dataset/train/1/456456.jpg dataset/train/2/456.jpg dataset/train/... dataset/val/0/878.jpg dataset/val/1/234.jpg dataset/val/2/34554.jpg dataset/val/... So I used torchvision.datasets.ImageFolder to import my dataset to PyTorch. However, it ...
Someone helped me out with this. ImageFolder creates its own internal labels. By printing image_datasets['train'].class_to_idx you can see what label is paired to what internal label. Using this dictionary, you can trace back the original label.
https://stackoverflow.com/questions/53732300/
Setting dimensions of layers in a convolutional neural network
Say I have 3x100x100 images in batches of 4 as input and I'm trying to make my first convolutional neural networks with pytorch. I'm really not sure if I'm getting convolutional neural networks right because when I train my input through the following arrangement I run into the error: Expected input batch_size (1) to...
Your understanding is correct and very detailed. However, you have used two pooling layers (see relevant code below). So output after the second step will be 16 maps with 44/2=22 dimension. x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) To fix this either not pool or change the dimension...
https://stackoverflow.com/questions/53735130/
How to profiling layer-by-layer in Pytroch?
I have tried to profile layer-by-layer of DenseNet in Pytorch as caffe-time tool. First trial : using autograd.profiler like below ... model = models.__dict__['densenet121'](pretrained=True) model.to(device) with torch.autograd.profiler.profile(use_cuda=True) as prof: model.eval() print(prof) ... But the any ...
To run profiler you have do some operations, you have to input some tensor into your model. Change your code as following. import torch import torchvision.models as models model = models.densenet121(pretrained=True) x = torch.randn((1, 3, 224, 224), requires_grad=True) with torch.autograd.profiler.profile(use_cuda=Tr...
https://stackoverflow.com/questions/53736966/
KeyError: "filename 'storages' not found"
I'm trying to load pre-trained model weights using this line : state_dict = torch.load('models/seq_to_txt_state_7.tar') and I'm getting: KeyError Traceback (most recent call last) <ipython-input-30-3f7b5be8fc72> in <module>() ----> 1 state_dict = torch.load('mo...
@reportgunner is right. The model file was corrupted. End of the message!
https://stackoverflow.com/questions/53743498/
Are there any computational efficiency differences between nn.functional() Vs nn.sequential() in PyTorch
The following is a Feed-forward network using the nn.functional() module in PyTorch import torch.nn as nn import torch.nn.functional as F class newNetwork(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 128) self.fc2 = nn.Linear(128, 64) self.fc3 = nn.L...
There is no difference between the two. The latter is arguably more concise and easier to write and the reason for "objective" versions of pure (ie non-stateful) functions like ReLU and Sigmoid is to allow their use in constructs like nn.Sequential.
https://stackoverflow.com/questions/53745454/
pytorch runs in anaconda prompt but not in python idle
I know this question might be stupid, but I couldn't find any help on the internet. Recently I installed anaconda in my computer, it runs Windows 10 x64. Then I used anaconda prompt to download and install pytorch for 3.6 python: conda install pytorch torchvision cuda100 -c pytorch After the installation I verified ...
It seems like the python used by idle is not the one from anaconda. In python it's very common to have multiple environments, and you always need to be aware of which environment is activated. To see what environment is activated, you can do something in this in anaconda and idle >>> import sys >>> p...
https://stackoverflow.com/questions/53752179/
how to calculate cross entropy in 3d image pytorch?
See the figure here left thing is (2, 480, 640) and it's softmax value right thing is (2, 480, 640) and it's one-hot encoding value how to get cross entropy loss in all element?
Exactly the same way as with any other image. Use binary_cross_entropy(left, right). Note that Both have to be of torch.float32 dtype so you may need to first convert right using right.to(torch.float32). If your left tensor contains logits instead of probabilities it is better to call binary_cross_entropy_with_logits...
https://stackoverflow.com/questions/53759952/
What does it mean if a deeper conv layer converges first?
I am training a 3-layer convnet to classify images - a very standard problem, I know. I first tried 3 convolutional layers with ReLU, and got this: weights from layer 1 with ReLU - looks like edge detection weights from layer 3 with ReLU - looks like feature detection The first layer (16 filters) is learning edges,...
First off, you're confusing terminology. The notion of convergence applies to an optimization algorithm and whether it arrives at some fixed location in the parameter space or not. If not, it may keep going forever, either improving at infinitesimally slow rate and never arriving at an optimum, oscillating around it ...
https://stackoverflow.com/questions/53768085/
inputing numpy array images into pytorch neural net
I have a numpy array representation of an image and I want to turn it into a tensor so I can feed it through my pytorch neural network. I understand that the neural networks take in transformed tensors which are not arranged in [100,100,3] but [3,100,100] and the pixels are rescaled and the images must be in batches....
The problem is that the input you give to your network is of type ByteTensor while only float operations are implemented for conv like operations. Try the following my_img_tensor = my_img_tensor.type('torch.DoubleTensor') # for converting to double tensor Source PyTorch Discussion Forum Thanks to AlbanD
https://stackoverflow.com/questions/53768796/
How do I install PyTorch v1.0.0+ on Google Colab?
PyTorch v1.0.0 stable was released on 8 December 2018 after being announced 7 months earlier. I want get a version optimised for the hardware that my IPython kernel is running on. How do I get this version on Google Colab?
try the following code snippet (it works equally for the runtime with or without gpu) !pip install -q torch==1.0.0 torchvision to check the version import torch print(torch.__version__) here you have the version 1.0.0 UPDATE !pip install torch Works fine now, as the most stable version is 1.0.0
https://stackoverflow.com/questions/53775508/
How are the pytorch dimensions for linear layers calculated?
In the PyTorch tutorial, the constructed network is Net( (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1)) (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1)) (fc1): Linear(in_features=400, out_features=120, bias=True) (fc2): Linear(in_features=120, out_features=84, bias=True) (fc3): Linear(in_f...
The key step is between the last convolution and the first Linear block. Conv2d outputs a tensor of shape [batch_size, n_features_conv, height, width] whereas Linear expects [batch_size, n_features_lin]. To make the two align you need to "stack" the 3 dimensions [n_features_conv, height, width] into one [n_features_lin...
https://stackoverflow.com/questions/53784998/
saving and loading pytorch neural nets
So I created a neural net and I would like to save it and load it whenever I want. Specifically, I want to take pictures and do real time processing. I am using the neural net created here I read that the standard way is to create the net then use torch.save(net,'mynet') to save it and then load it with torch.load('my...
Please refer to the docs on serialization semantics, which first describes the suggested approach and then the one you used as "serialized data is bound to the specific classes and the exact directory structure used, so it can break in various ways when used in other projects, or after some serious refactors." In oth...
https://stackoverflow.com/questions/53794900/
Pytorch PPO implementation is not learning
This PPO implementation has a bug somewhere and I can't figure out what's wrong. The network returns a normal distribution and a value estimate from the critic. The last layer of the actor provides four F.tanhed action values, which are used as mean value for the distribution. nn.Parameter(torch.zeros(action_dim)) is t...
In the Generalized Advantage Estimation loop advantages and returns are added in reversed order. advantage_list.insert(0, advantages.detach()) return_list.insert(0, returns.detach())
https://stackoverflow.com/questions/53802453/
Siamese Neural Network in Pytorch
How can I implement a siamese neural network in PyTorch? What is a siamese neural network? A siamese neural network consists in two identical neural networks, each one taking one input. Identical means that the two neural networks have the exact same architecture and share the same weights.
Implementing siamese neural networks in PyTorch is as simple as calling the network function twice on different inputs. mynet = torch.nn.Sequential( nn.Linear(10, 512), nn.ReLU(), nn.Linear(512, 2)) ... output1 = mynet(input1) output2 = mynet(input2) ... loss.backward() When invoking loss.bac...
https://stackoverflow.com/questions/53803889/
Unexpected result of convolution operation
Here is code I wrote to perform a single convolution and output the shape. Using formula from http://cs231n.github.io/convolutional-networks/ to calculate output size : You can convince yourself that the correct formula for calculating how many neurons “fit” is given by (W−F+2P)/S+1 The formula for computing ...
The problem is that your input image is not a square, so you should apply the formula on the width and the heigth of the input image. And also you should not use the nb_channels in the formula because we are explicitly defining how many channels we want in the output. Then you use your f=kernel_size and not f=kernel_si...
https://stackoverflow.com/questions/53807071/
IndexError when iterating my dataset using Dataloader in PyTorch
I iterated my dataset using Dataloader in PyTorch 0.2 like these: dataloader = torch.utils.data.DataLoader(...) data_iter = iter(dataloader) data = data_iter.next() but IndexError was raised. Traceback (most recent call last): File "main.py", line 193, in <module> data_target = data_target_iter.next() ...
My guess is that your data.Dataset.__len__ was not overloaded properly and in-fact len(dataloader.dataset) returns a number larger than len(self.X_train). Check your implementation of the underlying dataset in '/home/asr4/zhuminxian/adversarial/code/dataset/data_loader.py'.
https://stackoverflow.com/questions/53810497/
vgg probability doesn't add up to 1, pytorch
I've trained a vgg16 model to predict 102 classes of flowers. It works however now that I'm trying to understand one of it's predictions I feel it's not acting normally. model layout # Imports here import os import numpy as np import torch import torchvision from torchvision import datasets, models, transforms impor...
Yes, official network implementations in PyTorch don't apply softmax to the last linear layer. Check the code for VGG. You can use nn.softmax to achieve what you want: m = nn.Softmax() out = vgg16(floatified) out = m(out) You can also use nn.functional.softmax: out = nn.functional.softmax(vgg16(floatified))
https://stackoverflow.com/questions/53813636/
Copying data from one tensor to another using bit masking
import numpy as np import torch a = torch.zeros(5) b = torch.tensor(tuple((0,1,0,1,0)),dtype=torch.uint8) c= torch.tensor([7.,9.]) print(a[b].size()) a[b]=c print(a) torch.Size([2])tensor([0., 7., 0., 9., 0.]) I am struggling to understand how this works. I initially thought the above code was using Fancy indexi...
Indexing with arrays works the same as in numpy and most other vectorized math packages I am aware of. There are two cases: When b is of type uint8 (think boolean, pytorch doesn't distinguish bool from uint8), a[b] is a 1-d array containing the subset of values of a (a[i]) for which the corresponding in b (b[i]) was ...
https://stackoverflow.com/questions/53814772/
How to assign a new value to a pytorch Variable without breaking backpropagation?
I have a pytorch variable that is used as a trainable input for a model. At some point I need to manually reassign all values in this variable. How can I do that without breaking the connections with the loss function? Suppose the current values are [1.2, 3.2, 43.2] and I simply want them to become [1,2,3]. Edit At th...
You can use the data attribute of tensors to modify the values, since modifications on data do not affect the graph. So the graph will still be intact and modifications of the data attribute itself have no influence on the graph. (Operations and changes on data are not tracked by autograd and thus not present in the gr...
https://stackoverflow.com/questions/53819383/
Error when converting PyTorch model to TorchScript
I'm trying to follow the PyTorch guide to load models in C++. The following sample code works: import torch import torchvision # An instance of your model. model = torchvision.models.resnet18() # An example input you would normally provide to your model's forward() method. example = torch.rand(1, 3, 224, 224) # Us...
I just figured out that models loaded from torchvision.models are in train mode by default. AlexNet and SqueezeNet both have Dropout layers, making the inference nondeterministic if in train mode. Simply changing to eval mode fixed the issue: sq = torchvision.models.squeezenet1_0(pretrained=True) sq.eval() traced_scri...
https://stackoverflow.com/questions/53820175/
Pycharm/Pytorch - 'tensor' is not callable
When creating a pytorch (1.0) tensor : import torch W = torch.tensor(([1.0])) Pycharm (2018.3.1) gives me the following warning : 'tensor' is not callable less... (Ctrl+F1) Inspection info: This inspection highlights attempts to call objects which are not callable, like, for example, tuples My code works fine (t...
This has been a known issue to them . The moderator replied with: We will fix this in the next release. It’s being tracked at https://github.com/pytorch/pytorch/issues/7318 However, the reported issue was on PyTorch v0.4.1
https://stackoverflow.com/questions/53826221/
RuntimeError: dimension specified as 0 but tensor has no dimensions
I was trying to Implement simple NN using the MNIST datasets and I keep getting this error import matplotlib.pyplot as plt import torch from torchvision import models from torchvision import datasets, transforms from torch import nn, optim import torch.nn.functional as F import helper transform = transforms.ToTen...
The issue you're hitting directly is that NLL loss expects a labels (you're spelling it lables btw) tensor of at least 1 dimension and it's getting a 0-dimensional tensor (aka a scalar). If you see this kind of messages, it's good to just print(output.shape, labels.shape) for easier inspection. The source of this error...
https://stackoverflow.com/questions/53841576/
Pytorch - inference all images and back-propagate batch by batch
I have a special use case that I have to separate inference and back-propagation: I have to inference all images and slice outputs into batches followed by back-propagating batches by batches. I don't need to update my network's weights. I modified snippets of cifar10_tutorial into the following to simulate my problem:...
Yes you are correct. When you already back-propagated through outputs the first time (first iteration), the buffers will be freed and it will fail the following time (next iteration of your loop), because then necessary data for this computation have already been removed. Yes, the graph grows bigger and bigger, so it ...
https://stackoverflow.com/questions/53843711/
How to load and use a pretained PyTorch InceptionV3 model to classify an image
I have the same problem as How can I load and use a PyTorch (.pth.tar) model which does not have an accepted answer or one I can figure out how to follow the advice given. I'm new to PyTorch. I am trying to load the pretrained PyTorch model referenced here: https://github.com/macaodha/inat_comp_2018 I'm pretty sure ...
Problem Your model isn't actually a model. When it is saved, it contains not only the parameters, but also other information about the model as a form somewhat similar to a dict. Therefore, torch.load("iNat_2018_InceptionV3.pth.tar") simply returns dict, which of course does not have an attribute called predict. mod...
https://stackoverflow.com/questions/53844826/
How do you change the dimension of your input pictures in pytorch?
i made a convolutional nuralnetwork and i want it to take input pictures and output pictures but when i turn the pictures into tensors they have the wrong dimension : RuntimeError: Expected 4-dimensional input for 4-dimensional weight [20, 3, 5, 5], but got 3-dimensional input of size [900, 1440, 3] instead how do ...
In summary, according to the comments you and I posted: The error is due to torch.nn only supports mini-batches. The input should be in the form (batch_size, channels, height, width). You seem to be missing the batch dimension. You can add .unsqueeze(0) to add a fake batch dimension in the first position. In addition...
https://stackoverflow.com/questions/53852355/
Summing contiguous non zero tensor values
I am trying to find the summation of contiguous non zero tensor values as shown below Let’s say, I have a tensor A = [1.3, 0.0, 0.6, 0.7, 0.8]. And I want to 1) sum up the contiguous non-zero values of the tensor to output [1.3, 0.0, 2.1] and then choose the maximum which is 2.1. 2) find the indices as well which w...
My approach is somewhat different from @Anwarvic. I try to do it in one pass. See the function below. It moves through the array and keep a log of max it has seen so far and current sum. Current sum is updated to 0 if we hit a zero or sum up the value to current if non-zero. def find_continguous_max_sum(t): max_,...
https://stackoverflow.com/questions/53875065/
How do I modify this PyTorch convolutional neural network to accept a 64 x 64 image and properly output predictions?
I took this convolutional neural network (CNN) from here. It accepts 32 x 32 images and defaults to 10 classes. However, I have 64 x 64 images with 500 classes. When I pass in 64 x 64 images (batch size held constant at 32), I get the following error. ValueError: Expected input batch_size (128) to match target batch_...
The problem is an incompatible reshape (view) at the end. You're using a sort of "flattening" at the end, which is different from a "global pooling". Both are valid for CNNs, but only the global poolings are compatible with any image size. The flattened net (your case) In your case, with a flatten, ...
https://stackoverflow.com/questions/53875372/
PyTorch - How to deactivate dropout in evaluation mode
This is the model I defined it is a simple lstm with 2 fully connect layers. import copy import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class mylstm(nn.Module): def __init__(self,input_dim, output_dim, hidden_dim,linear_dim): super(mylstm, self).__init__() ...
You have to define your nn.Dropout layer in your __init__ and assign it to your model to be responsive for calling eval(). So changing your model like this should work for you: class mylstm(nn.Module): def __init__(self,input_dim, output_dim, hidden_dim,linear_dim,p): super(mylstm, self).__init__() ...
https://stackoverflow.com/questions/53879727/
Does someone knows the difference between xavier_normal_ and kaiming_normal_?
Like title. Does someone knows the difference between xavier_normal_ and kaiming_normal_? Only Xavier have an argument 'gain' more than kaiming?
Read the documentation: xavier_normal_ Fills the input Tensor with values according to the method described in “Understanding the difficulty of training deep feedforward neural networks” - Glorot, X. & Bengio, Y. (2010), using a normal distribution. kaiming_normal_ Fills the input Tensor with values acco...
https://stackoverflow.com/questions/53881908/
Is there a way to see what's going wrong with a training session in Pytorch?
I'm training a triplet convolution neural network in Jupyter. When I execute the cell I just get the * symbol and nothing happens. I'm not asking for help finding a problem with the code. I would just like to know if there is a troubleshooting possibility that might let me see what is happening. There is probably so...
NameError: name 'set_trace' is not defined You mean: import pdb; pdb.set_trace()
https://stackoverflow.com/questions/53890913/
Traceback (most recent call last) in Colab when looping through dataloader in pytorch
I'm working on a project to classify flower images using a pre-trained model vgg19 using pytorch. I'm relying on the model features only and using a custom classifier. However on starting a for-loop to feed images to the model classifier and calculate accuracy through epochs I get an error. I'm not sure what's the p...
The error is caused because of interference created by the older version of Pillow which is already installed on Colab. You need to upgrade it to the latest version. Use the following code to upgrade to the latest version of Pillow. !pip uninstall -y Pillow !pip install Pillow==5.3.0 import PIL.Image Now, simply res...
https://stackoverflow.com/questions/53894496/
Is my custom loss function correct? (Pytorch)
I want to do word recognition using a CNN + Classifier, where the input is an image and the output a matrice 10x37. 10 is the maximum number of characters in a word and 37 is the number of letters in my example. I wrote a custom loss function for this model but I'm not sure if it's correct since I can't get above 80% ...
The loss function is correct. The problem was in the file containing my training data. It was not correctly created. In fact, I flipped the dimensions in the images (width and height) so the result from my training set was indecipherable for my CNN. Now that I have solved the problem, I have reached 99.8% test accura...
https://stackoverflow.com/questions/53899272/
Pytorch select tensor
I want to know if Pytorch have a slice function (same as tf). In particular, I want to select the orange color rows.
You can use slicing as in numpy. See below import torch A = torch.rand((3,5,500)) first_three_rows = A[:, :3, :] However to get different slices as you asked in the question, you can do import torch A = torch.rand((3,5,500)) indices = [2,4,5] result = torch.cat([A[idx, :index, :] for idx, index in enumerate(indice...
https://stackoverflow.com/questions/53899746/
What are Torch Scripts in PyTorch?
I've just found that PyTorch docs expose something that is called Torch Scripts. However, I do not know: When they should be used? How they should be used? What are their benefits?
Torch Script is one of two modes of using the PyTorch just in time compiler, the other being tracing. The benefits are explained in the linked documentation: Torch Script is a way to create serializable and optimizable models from PyTorch code. Any code written in Torch Script can be saved from your Python process and...
https://stackoverflow.com/questions/53900396/
Convert PyTorch tensor to python list
How do I convert a PyTorch Tensor into a python list? I want to convert a tensor of size [1, 2048, 1, 1] into a list of 2048 elements. My tensor has floating point values. Is there a solution which also works with other data types such as int?
Use Tensor.tolist() e.g: >>> import torch >>> a = torch.randn(2, 2) >>> a.tolist() [[0.012766935862600803, 0.5415473580360413], [-0.08909505605697632, 0.7729271650314331]] >>> a[0,0].tolist() 0.012766935862600803 To remove all dimensions of size 1, use a.squeeze().tolist(). Alter...
https://stackoverflow.com/questions/53903373/
Problems with LSTM model
I try to realise LSTM model in PyTorch and got such problem: loss don't reduce. My task is so: I have sessions with different features. Session length is fixed and equals to 20. My goal is to predict will the last session been skipped or not. I tried to scale input features, I tried to pass target into features(maybe...
My fail, forgot to scale input features, now works fine.
https://stackoverflow.com/questions/53914450/
Pytorch not recognizing directory for dataset
I'm trying to run code for a Deep Convolutional GAN from the official PyTorch site (https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html) on my Mac. When I try loading the data, I keep getting a "FileNotFound" error. Random Seed: 999 ----------------------------------------------------------------------...
The recognizable directory structure starts with /. So I assume, you should be replacing dataroot = "Users/user1/Downloads/DCGANs/celeba/" by dataroot = "/Users/user1/Downloads/DCGANs/celeba/"
https://stackoverflow.com/questions/53916510/
TypeError: object of type 'numpy.int64' has no len()
I am making a DataLoader from DataSet in PyTorch. Start from loading the DataFrame with all dtype as an np.float64 result = pd.read_csv('dummy.csv', header=0, dtype=DTYPE_CLEANED_DF) Here is my dataset classes. from torch.utils.data import Dataset, DataLoader class MyDataset(Dataset): def __init__(self, result...
Reference: https://github.com/pytorch/pytorch/issues/9211 Just add .tolist() to indices line. def random_split(dataset, lengths): """ Randomly split a dataset into non-overlapping new datasets of given lengths. Arguments: dataset (Dataset): Dataset to be split lengths (sequence): lengths o...
https://stackoverflow.com/questions/53916594/
How to stack 1-dimensional vectors in pytorch
I am trying to stack 1-dimensional tensors in pytorch but the stack function seems to be interpreting them as 2-d square matrices. Any ideas how to stack 1-d tensors into a new 1-d tensor? Reproducibility: a = torch.randn([2]) b = torch.randn([3]) c = torch.stack([a, b]) # want a (5,) tensor RuntimeError: invalid ar...
You can try cat (official docs) a = torch.randn([2]) b = torch.randn([3]) c = torch.cat([a, b], dim=0)
https://stackoverflow.com/questions/53918549/
Conv 1x1 configuration for feature reduction
I am using 1x1 convolution in the deep network to reduce a feature x: Bx2CxHxW to BxCxHxW. I have three options: x -> Conv (1x1) -> Batchnorm-->ReLU. Code will be output = ReLU(BN(Conv(x))). Reference resnet x -> BN -> ReLU-> Conv. So the code will be output = Conv(ReLU(BN(x))) . Reference densenet x-> Conv. The cod...
Since you are going to train your net end-to-end, whatever configuration you are using - the weights will be trained to accommodate them. BatchNorm? I guess the first question you need to ask yourself is do you want to use BatchNorm? If your net is deep and you are concerned with covariate shifts then you probably sho...
https://stackoverflow.com/questions/53919836/
What particular change of formula in target changes neural network from gradient descent into gradient ascent?
It was weird when I face it in reinforcement learning. A loss is MSE. Everything should be perfect to be gradient descent and now it is a gradient ascent. I wanna know the magic. I did numpy neural network. Change in a derivative lead to gradient ascent. What particular change in a derivative lead to gradient ascent? I...
If you're doing gradient ascent, it must mean that you are doing a variant of policy gradients reinforcement learning. Doing gradient ascent is extremely simple, long story short, you just apply gradient descent, except you put a minus sign in front of the gradient term! In tensorflow code: gradients = - tf.compute_gra...
https://stackoverflow.com/questions/53923388/
Indexing a batched set of images
Suppose I have two index tensors and an image tensor, how can I sample the (x, y) points from the image? img.shape # -> (batch x H x W x 3) x.shape # -> (batch x H x W) y.shape # -> batch x H x W) (H x W being height x width) Basically I want to perform something like a batch "shuffle" of the image pixel in...
I am assuming you want output[a, b, c, d] == img[a, x[a, b, c], y[a, b, c], d], where a, b, c, d are variables which iterate over batch, H, W and 3, respectively. You can solve that by applying torch.gather twice. As you can see in documentation it performs a similar indexing operation for a single dimension, so we wou...
https://stackoverflow.com/questions/53924868/
pytorch - Where is “conv1d” implemented?
I wanted to see how the conv1d module is implemented https://pytorch.org/docs/stable/_modules/torch/nn/modules/conv.html#Conv1d. So I looked at functional.py but still couldn’t find the looping and cross-correlation computation. Then I searched Github by keyword ‘conv1d’, checked conv.cpp https://github.com/pytorch/py...
It depends on the backend (GPU, CPU, distributed etc) but in the most interesting case of GPU it's pulled from cuDNN which is released in binary format and thus you can't inspect its source code. It's a similar story for CPU MKLDNN. I am not aware of any place where PyTorch would "handroll" it's own convolution kernel...
https://stackoverflow.com/questions/53927358/
how to flatten input in `nn.Sequential` in Pytorch
how to flatten input inside the nn.Sequential Model = nn.Sequential(x.view(x.shape[0],-1), nn.Linear(784,256), nn.ReLU(), nn.Linear(256,128), nn.ReLU(), nn.Linear(128,64), nn.ReLU(), ...
You can create a new module/class as below and use it in the sequential as you are using other modules (call Flatten()). class Flatten(torch.nn.Module): def forward(self, x): batch_size = x.shape[0] return x.view(batch_size, -1) Ref: https://discuss.pytorch.org/t/flatten-layer-of-pytorch-build-b...
https://stackoverflow.com/questions/53953460/
How does Pytorch's "Fold" and "Unfold" work?
I've gone through the official doc. I'm having a hard time understanding what this function is used for and how it works. Can someone explain this in layman's terms?
The unfold and fold are used to facilitate "sliding window" operations (like convolutions). Suppose you want to apply a function foo to every 5x5 window in a feature map/image: from torch.nn import functional as f windows = f.unfold(x, kernel_size=5) Now windows has size of batch-(55x.size(1))-num_windows, y...
https://stackoverflow.com/questions/53972159/
PyTorch Getting Started example not working
I followed this tutorial in the Getting Started section on the PyTorch website: "Deep Learning with PyTorch: A 60 Minute Blitz" and I downloaded the code for "Training a Classifier" on the bottom of the page and I ran it, and it's not working for me. I'm using the CPU version of PyTorch if that makes a difference. I'm ...
The error is likely due to multiprocessing in DataLoader and Windows since the tutorial is using num_workers=2. Python3 documentation shares some guidelines on this: Make sure that the main module can be safely imported by a new Python interpreter without causing unintended side effects (such a starting a new proce...
https://stackoverflow.com/questions/53974351/
Using expand_dims in pytorch
I'm trying to tile a length 18 1 hot vector into a 40x40 grid. Looking at pytorch docs, expand dims seems to be what i need. But I cannot get it to work. Any idea what I'm doing wrong? one_hot = torch.zeros(18).unsqueeze(0) one_hot[0,1] = 1.0 one_hot tensor([[0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., ...
expand works along singleton dimensions of the input tensor. In your example, you are trying to expand a 1-by-18 tensor along its (non-existent) third and fourth dimensions - this is why you are getting an error. The only singleton dimension (=dimension with size==1) you have is the first dimension. fix one_hot = t...
https://stackoverflow.com/questions/53975352/
pytorch - connection between loss.backward() and optimizer.step()
Where is an explicit connection between the optimizer and the loss? How does the optimizer know where to get the gradients of the loss without a call liks this optimizer.step(loss)? -More context- When I minimize the loss, I didn't have to pass the gradients to the optimizer. loss.backward() # Back Propagation opt...
Without delving too deep into the internals of pytorch, I can offer a simplistic answer: Recall that when initializing optimizer you explicitly tell it what parameters (tensors) of the model it should be updating. The gradients are "stored" by the tensors themselves (they have a grad and a requires_grad attri...
https://stackoverflow.com/questions/53975717/