instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
PyTorch: Comparing predicted label and target label to compute accuracy
I'm trying to implement this loop to get the accuracy of my PyTorch CNN (The complete code of it is here) My version of the loop is so far: correct = 0 test_total = 0 for itera, testdata2 in enumerate(test_loader, 0): test_images2, test_labels2 = testdata2 if use_gpu: test_images2 =...
Indexing in pytorch works mostly like indexing in numpy. To index all rows of a certain column j use: tensor[:, j] Alternatively, the select function from pytorch can be used.
https://stackoverflow.com/questions/49304817/
Pytorch model weight type conversion
I'm trying to do inference on FlowNet2-C model loading from file. However, I met some data type problem. How can I resolve it? Source code FlowNet2-C pre-trained model $ python main.py Initializing Datasets [0.000s] Loading checkpoint '/notebooks/data/model/FlowNet2-C_checkpoint.pth.tar' [1.293s] Loaded chec...
Maybe that is because your model and input x to the model has different data types. It seems that the model parameters have been moved to GPU, but your input x is on GPU. You can try to use model.cuda() after line 94, which will put the model on the GPU. Then the error should disappear.
https://stackoverflow.com/questions/49313974/
math operator difference *= or +=
I found a weird thing when I used the operator e.g. *= or += The code: aa = Variable(torch.FloatTensor([[1,2],[3,4]])) bb = aa bb = bb*2 print(bb) print(aa) cc = Variable(torch.FloatTensor([[1,2],[3,4]])) dd = cc dd *= 2 print(cc) print(dd) The results showed as below: Variable containing: 2 4 6 8 [torch.Floa...
When you do dd = cc, both dd and cc are now references to the same object (same for bb = aa). Nothing is being copied! When you do bb = bb * 2, the * operator creates a new object and bb now refers to that object. No existing object is changed. When you do dd *= 2, the object that dd refers to (and which cc also refe...
https://stackoverflow.com/questions/49321725/
How to take shape [1,1,256] from [1,4,256] cuda.FloatTensor?
I have an batch of output hidden vector from GRU. It's shape is [1,4,256] ( 0 ,.,.) = -0.9944 1.0000 0.0000 ... -1.0000 0.0000 -1.0000 -1.0000 1.0000 0.0000 ... -1.0000 0.0000 -1.0000 -1.0000 1.0000 0.0000 ... -1.0000 0.0000 -1.0000 -1.0000 1.0000 0.0000 ... -1.0000 0.0000 -1.0000 [torch.cuda.Floa...
You can unsqueeze() in dimension 1 to achieve this. encoder_hidden = torch.randn(1, 4, 256) print(encoder_hidden.size()) for idx in range(encoder_hidden.size(1)): decoder_hidden = encoder_hidden[:, idx, :].unsqueeze(1) print(decoder_hidden.size()) It prints: torch.Size([1, 4, 256]) torch.Size([1, 1, 256]) ...
https://stackoverflow.com/questions/49334900/
Understanding PyTorch CNN Channels
I'm a bit confused at how CNNs and channels work. Specifically, how come these two implementations are not equal? Isn't the # of output channels just applying however many # of filters? self.conv1 = nn.Conv2d(1, 10, kernel_size=(3, self.embeds_size)) self.conv2 = nn.ModuleList([nn.Conv2d(1, 1, kernel_size=(3, ...
Check the state dicts of the different modules. Unless you're doing something fancy that you didn't tell us about, PyTorch will initialize the weights randomly. Specifically, try this: print(self.conv1.state_dict()["weight"][0]) print(self.conv2[0].state_dict()["weight"][0]) They will be different.
https://stackoverflow.com/questions/49362616/
Non linear mapping to vector of higher dimension
I am learning Keras and need help on the following. I currently have a sequence of floats in lists X and Y. What I need to do is to have a non-linear mapping to map each element to a vector of higher dimension following the below equation. pos(i) = tanh(W.[concat(X[i],Y[i]]) #where W is a learnable weight matrix, conc...
Based on what you have there. This is what I would do in keras. Im going to assume that you just want your to concatenate your inputs before you feed them into the model. So we'll do it with numpy. Note something like : import numpy as np from keras.model import Dense, Model,Input X = np.random.rand(100, 1) Y = np...
https://stackoverflow.com/questions/49375984/
Cross Entropy in PyTorch
Cross entropy formula: But why does the following give loss = 0.7437 instead of loss = 0 (since 1*log(1) = 0)? import torch import torch.nn as nn from torch.autograd import Variable output = Variable(torch.FloatTensor([0,0,0,1])).view(1, -1) target = Variable(torch.LongTensor([3])) criterion = nn.CrossEntropyLoss()...
In your example you are treating output [0, 0, 0, 1] as probabilities as required by the mathematical definition of cross entropy. But PyTorch treats them as outputs, that don’t need to sum to 1, and need to be first converted into probabilities for which it uses the softmax function. So H(p, q) becomes: H(p, softmax(...
https://stackoverflow.com/questions/49390842/
How do I re-use trained fastai models?
How do I load pretrained model using fastai implementation over PyTorch? Like in SkLearn I can use pickle to dump a model in file then load and use later. I've use .load() method after declaring learn instance like bellow to load previously saved weights: arch=resnet34 data = ImageClassifierData.from_paths(PATH, tfms=...
This error occurs whenever a batch of your data contains a single element. Solution 1: Call learn.predict() after learn.load('resnet34_test') Solution 2: Remove 1 data point from your training set. Pytorch issue Fastai forum issue description
https://stackoverflow.com/questions/49398255/
RuntimeError: Expected object of type torch.DoubleTensor but found type torch.FloatTensor for argument #2 'weight'
My input tensor is torch.DoubleTensor type. But I got the RuntimeError below: RuntimeError: Expected object of type torch.DoubleTensor but found type torch.FloatTensor for argument #2 'weight' I didn't specify the type of the weight explicitly(i.e. I did not init my weight by myself. The weight is created by pytorch...
The default type for weights and biases are torch.FloatTensor. So, you'll need to cast either your model to torch.DoubleTensor or cast your inputs to torch.FloatTensor. For casting your inputs you can do X = X.float() or cast your complete model to DoubleTensor as model = model.double() You can also set the defau...
https://stackoverflow.com/questions/49407303/
Replace diagonal elements with vector in PyTorch
I have been searching everywhere for something equivalent of the following to PyTorch, but I cannot find anything. L_1 = np.tril(np.random.normal(scale=1., size=(D, D)), k=0) L_1[np.diag_indices_from(L_1)] = np.exp(np.diagonal(L_1)) I guess there is no way to replace the diagonal elements in such an elegant way usin...
I do not think that such a functionality is implemented as of now. But, you can implement the same functionality using mask as follows. # Assuming v to be the vector and a be the tensor whose diagonal is to be replaced mask = torch.diag(torch.ones_like(v)) out = mask*torch.diag(v) + (1. - mask)*a So, your implementa...
https://stackoverflow.com/questions/49429147/
How do I initialize weights in PyTorch?
How do I initialize weights and biases of a network (via e.g. He or Xavier initialization)?
Single layer To initialize the weights of a single layer, use a function from torch.nn.init. For instance: conv1 = torch.nn.Conv2d(...) torch.nn.init.xavier_uniform(conv1.weight) Alternatively, you can modify the parameters by writing to conv1.weight.data (which is a torch.Tensor). Example: conv1.weight.data.fill_(0.0...
https://stackoverflow.com/questions/49433936/
Understanding the code in pyTorch
I am having problems with understanding the following part of the code from ResNet architecture. The full code is available at https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/02-intermediate/deep_residual_network/main-gpu.py . I am not very familiar with Python. # Residual Block class ResidualBlock(nn...
The ResNet module is designed to be generic, so that it can create networks with arbitrary blocks. So, if you do not pass the block which you want to create you'll have to write the name of the block explicitly like below. # Residual Block class ResidualBlock(nn.Module): def __init__(self, in_channels, out_channel...
https://stackoverflow.com/questions/49445701/
How can I update the parameters of a neural network in PyTorch?
Let's say I wanted to multiply all parameters of a neural network in PyTorch (an instance of a class inheriting from torch.nn.Module) by 0.9. How would I do that?
Let net be an instance of a neural network nn.Module. Then, to multiply all parameters by 0.9: state_dict = net.state_dict() for name, param in state_dict.items(): # Transform the parameter as required. transformed_param = param * 0.9 # Update the parameter. param.copy_(transformed_param) If you wan...
https://stackoverflow.com/questions/49446785/
PyTorch forward pass using weights trained by Theano
I've trained a small size CNN binary classifier in Theano. To have a simpler code, I wanted to port the trained weights to PyTorch or numpy forward pass for predictions. The predictions by original Theano program are satisfying but the PyTorch forward pass predicted all the examples to one class. Here is how I save t...
Theano uses convolutions (by default, filter_flip=True) while PyTorch uses cross-correlation. So, for every convolutional layer, you need to flip the weights before using them in PyTorch. You can use convert_kernel function from Keras to achieve this result.
https://stackoverflow.com/questions/49447270/
How to correctly give inputs to Embedding, LSTM and Linear layers in PyTorch?
I need some clarity on how to correctly prepare inputs for batch-training using different components of the torch.nn module. Specifically, I'm looking to create an encoder-decoder network for a seq2seq model. Suppose I have a module with these three layers, in order: nn.Embedding nn.LSTM nn.Linear nn.Embedding In...
Your understanding of most of the concepts is accurate, but, there are some missing points here and there. Interfacing embedding to LSTM (Or any other recurrent unit) You have embedding output in the shape of (batch_size, seq_len, embedding_size). Now, there are various ways through which you can pass this to the LST...
https://stackoverflow.com/questions/49466894/
How do you use next_functions[0][0] on grad_fn correctly in pytorch?
I was given this nn structure in the offical pytorch tutorial: input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d -> view -> linear -> relu -> linear -> relu -> linear -> MSELoss -> loss then an example of how to follow the grad backwards using built-in .grad_fn from Varia...
In the PyTorch CNN tutorial after running the following from the tutorial: output = net(input) target = torch.randn(10) # a dummy target, for example target = target.view(1, -1) # make it the same shape as output criterion = nn.MSELoss() loss = criterion(output, target) print(loss) The following code snippet will...
https://stackoverflow.com/questions/49478784/
Pytorch save embeddings as part of encoder class or not
So I'm using pytorch for the first time. I'm trying to save weights to a file. I'm using a Encoder class that has a GRU and a embedding component. I want to make sure when I save the Encoder values that I will get the embedding values. Initially my code uses state_dict() to copy values to a dictionary of my own which I...
No, you do not need to save the embedding values explicitly. Saving a model’s state_dict will save all the variables pertaining to that model, including the embedding weights. You can look for what a state dict contains by looping over it as - for var_name in model.state_dict(): print(var_name)
https://stackoverflow.com/questions/49500089/
Masking diagonal to a specific value with PyTorch tensors
How do I fill the diagonal with a value in torch? In numpy you can do: a = np.zeros((3, 3), int) np.fill_diagonal(a, 5) array([[5, 0, 0], [0, 5, 0], [0, 0, 5]]) I know that torch.diag() returns the diagonal, but how to use this as a mask to assign new values is beyond me. I haven't been able to find the...
You can do this in PyTorch using fill_diagonal_: >>> a = torch.zeros(3, 3) >>> a.fill_diagonal_(5) tensor([[5, 0, 0], [0, 5, 0], [0, 0, 5]])
https://stackoverflow.com/questions/49512313/
Exploding loss in pyTorch
I am trying to train a latent space model in pytorch. The model is relatively simple and just requires me to minimize my loss function but I am getting an odd error. After running for a short while the loss suddenly explodes upwards. import numpy as np import scipy.sparse.csgraph as csg import torch from torch.autogra...
The issue was that I defined my loss l = loss(tY) outside of the loop that ran and updated my gradients, I am not entirely sure why it had the effect that it did, but moving the loss function definition inside of the loop solved the problem, resulting in this loss:
https://stackoverflow.com/questions/49518666/
Force GPU memory limit in PyTorch
Is there a way to force a maximum value for the amount of GPU memory that I want to be available for a particular Pytorch instance? For example, my GPU may have 12Gb available, but I'd like to assign 4Gb max to a particular process.
Update (04-MAR-2021): it is now available in the stable 1.8.0 version of PyTorch. Also, in the docs Original answer follows. This feature request has been merged into PyTorch master branch. Yet, not introduced in the stable release. Introduced as set_per_process_memory_fraction Set memory fraction for a process. The ...
https://stackoverflow.com/questions/49529372/
Pytorch errors when given numpy integer types only in python 3 (not in python 2)
For example, the torch.randn function, among others, gets mad when given a numpy.int64 type: Python 3.5.5 |Anaconda custom (64-bit)| (default, Mar 12 2018, 23:12:44) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import torch >>> import numpy >>...
On Python 2, on an OS where a C long is 64-bit, numpy.int64 is a subclass of int, so most things that want ints will accept numpy.int64 even if they're not written to handle int-like types. On Python 3, that doesn't happen any more. If you need to use a library that wants real ints, call int: torch.randn(int(some_num...
https://stackoverflow.com/questions/49545988/
PyTorch: Variable data has to be a tensor -- data is already as tenors
I am trying to load data using pytorch's Dataset and DataLoader classes. I use torch.from_numpyto convert each array to a tensor in the torch Dataset and from looking into the data, each X and y is indeed a tensor # At this point dataset is {'X': numpy array of arrays, 'y': numpy array of arrays } class TorchDatase...
There is error in your use of enumerate which caused the error because the first return value of enumerate is the batch index, not the actual data. There are two ways you can make your script work. First way Since your X and y is do not need special process. You can just return a sample of X and y. Change your __get...
https://stackoverflow.com/questions/49583041/
How does PyTorch module do the back prop
While following the instructions on extending PyTorch - adding a module, I noticed while extending Module, we don't really have to implement the backward function. The only thing we need is to apply the Function instance in the forward function and PyTorch can automatically call the backward one in the Function instanc...
Not having to implement backward() is the reason PyTorch or any other DL framework is so valuable. In fact, implementing backward() should only be done in very specific cases where you need to mess with the network's gradient (or when you create a custom Function that can't be expressed using PyTorch's built-in functio...
https://stackoverflow.com/questions/49594858/
Find a GPU with enough memory
I want to programmatically find out the available GPUs and their current memory usage and use one of the GPUs based on their memory availability. I want to do this in PyTorch. I have seen the following solution in this post: import torch.cuda as cutorch for i in range(cutorch.device_count()): if cutorch.getM...
In the webpage you give, there exist an answer: #!/usr/bin/env python # encoding: utf-8 import subprocess def get_gpu_memory_map(): """Get the current gpu usage. Returns ------- usage: dict Keys are device ids as integers. Values are memory usage as integers in MB. """ resu...
https://stackoverflow.com/questions/49595663/
How to resolve runtime error due to size mismatch in PyTorch?
I am trying to implement a simple autoencoder using PyTorch. My dataset consists of 256 x 256 x 3 images. I have built a torch.utils.data.dataloader.DataLoader object which has the image stored as tensor. When I run the autoencoder, I get a runtime error: size mismatch, m1: [76800 x 256], m2: [784 x 128] at /User...
If your input is 3 x 256 x 256, then you need to convert it to B x N to pass it through the linear layer: nn.Linear(3*256*256, 128) where B is the batch_size and N is the linear layer input size. If you are giving one image at a time, you can convert your input tensor of shape 3 x 256 x 256 to 1 x (3*256*256) as follow...
https://stackoverflow.com/questions/49606482/
Pytorch, pipenv and numpy support?
I am using pytorch and installed it follow these instructions: pipenv install git+https://github.com/pytorch/pytorch#egg=pytorch pipenv install git+https://github.com/pytorch/vision#egg=torchvision in order to install pytorch with pipenv. This runs some of the examples, but for instance, this MNIST code: from __fut...
I managed to get it. I slightly changed: pipenv install git+https://github.com/pytorch/pytorch#egg=pytorch pipenv install git+https://github.com/pytorch/vision#egg=torchvision To: pipenv install http://download.pytorch.org/whl/cu91/torch-0.3.1-cp36-cp36m-linux_x86_64.whl pipenv install git+https://github.com/pytorc...
https://stackoverflow.com/questions/49619952/
What's the difference between reshape and view in pytorch?
In numpy, we use ndarray.reshape() for reshaping an array. I noticed that in pytorch, people use torch.view(...) for the same purpose, but at the same time, there is also a torch.reshape(...) existing. So I am wondering what the differences are between them and when I should use either of them?
torch.view has existed for a long time. It will return a tensor with the new shape. The returned tensor will share the underling data with the original tensor. See the documentation here. On the other hand, it seems that torch.reshape has been introduced recently in version 0.4. According to the document, this method...
https://stackoverflow.com/questions/49643225/
Downloading pretrained TimeNet RNN?
I've been looking for the pretrained net behind TimeNet - a resnet equivalent for time series analysis via RNNs. There's some articles and several publications of the same paper, but the weights and architecture themselves are not easy to find. Anyone knows how to find it? Is it available to the public?
It looks like someone answered this on the top response to this Quora question. Why are there no pre-trained RNN models It's not available to the public just yet.
https://stackoverflow.com/questions/49661028/
pytorch - net.cuda() seems don't work
I wrote a cnn module to do digit recognition using pytorch, then try to train the network with gpu but got following error. Traceback (most recent call last): File "main.py", line 51, in <module> outputs = cnn(inputs) File "/home/daniel/anaconda3/envs/pytorch/lib/python3.5/site-packages/torch/nn/modules/...
Daniel's answer to his own question seems to be correct. The problem is indeed that modules are not recognized if they are appended to a list. However, Pytorch also provides built-in solutions to this problem: nn.ModuleList and nn.ModuleDict are two container types that keep track of the added content and their paramet...
https://stackoverflow.com/questions/49675499/
Resolved package not found
When I try to execute conda env create -f virtual_platform_windows.yml It shows ResolvePackageNotFound: - pytorch==0.1.12=py35_0.1.12cu80 I tried installing pytorch for windows and error still comes.How to solve this??
Open: virtual_platform_windows.yml in Notepad Delete: - pytorch=0.1.12=py35_0.1.12cu80 Delete: - torch==0.1.12 Save Using Anaconda prompt: Execute the code: conda env create -f virtual_platform_windows.yml Activate virtual environment: source activate virtual_platform Install Pytorch seperately with conda install...
https://stackoverflow.com/questions/49680427/
PyTorch - WSD using LSTM
I'm trying to replicate Google's research paper on WSD with neural models using PyTorch. I'm having some issues traying to overfit the model before training on large datasets. Using this training set: The film was also intended to be the first in a trilogy. this model definition: class WordGuesser(nn.Module)...
Solved it by saving only the model's state_dict() via torch.save() and then loading it back in the evaluation phase using model.load_state_dict(). Furthermore, I wrapped the sentence querying loop in another loop, acting as a warm-up (got it from here) and once it was at its last time looping, I set model.eval() and p...
https://stackoverflow.com/questions/49707613/
PyTorch / Gensim - How do I load pre-trained word embeddings?
I want to load a pre-trained word2vec embedding with gensim into a PyTorch embedding layer. How do I get the embedding weights loaded by gensim into the PyTorch embedding layer?
I just wanted to report my findings about loading a gensim embedding with PyTorch. Solution for PyTorch 0.4.0 and newer: From v0.4.0 there is a new function from_pretrained() which makes loading an embedding very comfortable. Here is an example from the documentation. import torch import torch.nn as nn # FloatT...
https://stackoverflow.com/questions/49710537/
Error Utilizing Pytorch Transforms and Custom Dataset
This question mainly concerns the return value of __getitem__ in a pytorch Dataset which I've seen as both a tuple and a dict in the source code. I have been following this tutorial for creating a dataset class within my code, which is following this tutorial on transfer learning. It has the following definition of a ...
The particular way the tutorial on dataloading uses the custom dataset is with self defined transforms. The transforms must be designed to fit the dataset. As such, the dataset must output a sample compatible with the library transform functions, or transforms must be defined for the particular sample case. Choosing th...
https://stackoverflow.com/questions/49717876/
pytorch doesn't give expected output
Firstly, a bunch of data is classified by the CNN model. Then, I'm trying to make prediction on correctly classified data from first step, which is expected to give an accuracy of 100%. However, I found the result is unstable, sometimes 99+%, but not 100%. Is there anybody know what is the problem with my code? Thank y...
Seems like you did not set the network to evaluation mode which might be causing some problems, specially with the BatchNorm layers. Do cnn = CNN() cnn.eval() and it should work.
https://stackoverflow.com/questions/49723034/
How are PyTorch's tensors implemented?
I am building my own Tensor class in Rust, and I am trying to make it like PyTorch's implementation. What is the most efficient way to store tensors programmatically, but, specifically, in a strongly typed language like Rust? Are there any resources that provide good insights into how this is done? I am currently bu...
Contiguous array The commonly used way to store such data is in a single array that is laid out as a single, contiguous block within memory. More concretely, a 3x3x3 tensor would be stored simply as a single array of 27 values, one after the other. The only place where the dimensions are used is to calculate the map...
https://stackoverflow.com/questions/49724954/
Get all 2D diagonals of a 3D tensor in numpy
I have a 3D tensor A x B x C. For each matrix B x C, I want to extract the leading diagonal. Is there a vectorized way of doing this in numpy or pytorch instead of looping over A?
You can use numpy.diagonal() np.diagonal(a, axis1=1, axis2=2) Example: In [10]: a = np.arange(3*4*5).reshape(3,4,5) In [11]: a Out[11]: array([[[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19]], [[20, 21, 22, 23, 24], [25, 26, 27, 28, 2...
https://stackoverflow.com/questions/49731792/
How to form a sequence of consecutive numbers in Pytorch?
How to convert the Matlab code v = [1: n] to pytorch? Writing a whole loop for that seems inefficient.
You can directly use the arange method from Pytorch. torch_v = torch.arange(1,n) Reference: https://pytorch.org/docs/master/torch.html?highlight=arange#torch.arange
https://stackoverflow.com/questions/49742625/
What is the benefit of random image crop on Convolutional Network?
I`m studying about transfer learning with the pytorch tutorial. I found pytorch tutorial author uses the different approach to train set and validation set. data_transforms = { 'train': transforms.Compose([ transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms....
Couple of ideas behind random cropping: In short: Extending the amount of data for training Making NN more robust More detail: The semantics of the image are preserved but the activation values of the conv net are different. The conv net learns to associate a broader range of spatial activations with a certain cl...
https://stackoverflow.com/questions/49748787/
Pytorch tensor to numpy array
I have a pytorch Tensor of shape [4, 3, 966, 1296]. I want to convert it to numpy array using the following code: imgs = imgs.numpy()[:, ::-1, :, :] How does that code work?
There are 4 dimensions of the tensor you want to convert. [:, ::-1, :, :] : means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension. ::-1 means that for the second axes it reverses the the axes
https://stackoverflow.com/questions/49768306/
Pytorch hidden state LSTM
Why do we need to initialize the hidden state h0 in LSTM in pytorch. As h0 will anyways be calculated and get overwritten ? Isn't it like int a a = 0 a = 4 Even if we do not do a=0, it should be fine..
The point is that you are able to supply the initial state, it is a feature. They could have implemented it as a default but by letting you control the allocation of the tensor you can save some memory (allocating once, zeroing on every invocation). Why would you need to set h? Sequence-to-sequence models require this...
https://stackoverflow.com/questions/49778001/
How is the print and view functions works in pytorch?
This is a convolutional neural network which I found in the web class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Lin...
1) x.view can do more than just flatten: It will keep the same data while reshaping the dimension. So using x.view(batch_size, -1)will be equivalent to Flatten 2) In the __repr__function of nn.Module, the elements that are printed are the modules in self._modules.items() which are its children. F.dropoutand F.max_po...
https://stackoverflow.com/questions/49808467/
How does one manually compute the error of the whole data set in pytorch?
I was trying to track the error of the whole data set and compute the error of the whole data set in pytorch. I wrote the following (reproducible example and fully contained) in cifar10 pytorch 0.3.1: import torch from torch.autograd import Variable import torch.optim as optim import torchvision import torchvision.tr...
If your batch size is too large, with your code the values of (max_indices == labels).sum() (max_indices != labels).sum() do not add up to the batch size. This is due to the fact, that you use a torch.ByteTensor which will overflow for values > 255 when summing. using (max_indices != labels).int().sum() will r...
https://stackoverflow.com/questions/49809032/
what is the default weight initializer for conv in pytorch?
The question How to initialize weights in PyTorch? shows how to initialize the weights in Pytorch. However, what is the default weight initializer for Convand Dense in Pytorch? What distribution does Pytorch use?
Each pytorch layer implements the method reset_parameters which is called at the end of the layer initialization to initialize the weights. You can find the implementation of the layers here. For the dense layer which in pytorch is called linear for example, weights are initialized uniformly stdv = 1. / math.sqrt(sel...
https://stackoverflow.com/questions/49816627/
PyTorch Getting Custom Loss Function Running
I'm trying to use a custom loss function by extending nn.Module, but I can't get past the error element 0 of variables does not require grad and does not have a grad_fn Note: my labels are lists of size: num_samples, but each batch will have the same labels throughout the batch, so we shrink labels for the whole ...
You are subclassing nn.Module to define a function, in your case Loss function. So, when you compute loss.backward(), it tries to store the gradients in the loss itself, instead of the model and there is no variable in the loss for which to store the gradients. Your loss needs to be a function and not a module. See Ext...
https://stackoverflow.com/questions/49821111/
Variable size input for LSTM in Pytorch
I am using features of variable length videos to train one layer LSTM. Video sizes are changing from 10 to 35 frames. I am using batch size of 1. I have the following code: lstm_model = LSTMModel(4096, 4096, 1, 64) for step, (video_features, label) in enumerate(data_loader): bx = Variable(score.view(-1, len(video_...
Yes, you code is correct and will work always for a batch size of 1. But, if you want to use a batch size other than 1, you’ll need to pack your variable size input into a sequence, and then unpack after LSTM. You can find more details in my answer to a similar question. P.S. - You should post such questions to codere...
https://stackoverflow.com/questions/49832739/
What is volatile variable in Pytorch
What is volatile attribute of a Variable in Pytorch? Here's a sample code for defining a variable in PyTorch. datatensor = Variable(data, volatile=True)
Basically, set the input to a network to volatile if you are doing inference only and won't be running backpropagation in order to conserve memory. From the docs: Volatile is recommended for purely inference mode, when you’re sure you won’t be even calling .backward(). It’s more efficient than any other autogr...
https://stackoverflow.com/questions/49837638/
How to convert from a Pytroch Tensor from mathematically a column vector to a column matrix?
I am working with tensors in pytorch. How can I convert a tensor corresponding to a column vector to a tensor corresponding to its transpose? import numpy as np coef = torch.from_numpy(np.arange(1.0, 5.0)).float() print(coef) print(coef.size()) Currently the size of coef is [4] but I want it to be [4, 1] with the sa...
It is easy to achieve in PyTorch. You can use the view() method. coef = coef.view(4, 1) print(coef.size()) # now the shape will be [4, 1]
https://stackoverflow.com/questions/49847984/
Tensorflow : What is actually tf.nn.dropout output_keep_prob?
I am trying to understand concept of output_keep_prob: So if my example is simple RNN : with tf.variable_scope('encoder') as scope: cells = rnn.LSTMCell(num_units=500) cell = rnn.DropoutWrapper(cell=cells, output_keep_prob=0.5) model = tf.nn.bidirectional_dynamic_rnn(cell, cell, inputs=em...
Keep_prop means the probability of any given neuron's output to be preserved (as opposed to dropped, that is zeroed out.) In other words, keep_prob = 1 - drop_prob. The tf.nn.dropout() description states that By default, each element is kept or dropped independently. So if you think about it, if you have a large...
https://stackoverflow.com/questions/49864214/
Running through a dataloader in Pytorch using Google Colab
I am trying to use Pytorch to run classification on a dataset of images of cats and dogs. In my code I am so far downloading the data and going into the folder train which has two folders in it called "cats" and "dogs." I am then trying to load this data into a dataloader and iterate through batches, but it is giving m...
I think the main problem was images being of different size . I may have understood ImageFolder in other way but, i think you don't need labels for images if the directory structure is as specified in pytorch and pytorch will figure out the labels for you. I would also add more things to your transform that automatic...
https://stackoverflow.com/questions/49878836/
Pytorch function name demystification: gels for least squares estimation
What does "gels" stand for in Pytorch? It solves least squares, but what does the name stand for? It is hard to get comfortable with a function without getting its name and it is surprising that these are not explained in the documentation.
gels is actually a function from LAPACK (Linear Algebra Package) and stands for GEneralalized Least Squares meaning that it works on general matrices: General matrix A general real or complex m by n matrix is represented by a real or complex matrix of size (m, n).
https://stackoverflow.com/questions/49882518/
KL Divergence for two probability distributions in PyTorch
I have two probability distributions. How should I find the KL-divergence between them in PyTorch? The regular cross entropy only accepts integer labels.
Yes, PyTorch has a method named kl_div under torch.nn.functional to directly compute KL-devergence between tensors. Suppose you have tensor a and b of same shape. You can use the following code: import torch.nn.functional as F out = F.kl_div(a, b) For more details, see the above method documentation.
https://stackoverflow.com/questions/49886369/
PyTorch replace torch.nn.Conv2d with torch.nn.functional.conv2d
So I have this MNIST example for PyTorch. I wanted to replace conv2d with functional method. But got unexpected error. I replace self.conv1 = nn.Conv2d(1, 32, 5, padding=2) with self.w_conv1 = Variable(torch.randn(1, 32, 5)) In the forward method I replace x = F.max_pool2d(F.relu(self.conv1(x)), 2) with x = F.max_poo...
albanD answerd the question in https://discuss.pytorch.org/t/pytorch-replace-torch-nn-conv2d-with-torch-nn-functional-conv2d/16596 Hi, The error message is not very clear I’m afraid because it comes from deep within the C backend. The problem here is that when you do a convolution on a 2D image with size (...
https://stackoverflow.com/questions/49896987/
Is there analog of theano.tensor.switch in pytorch?
I'd like to force to zero all elements of a vector which are below a certain threshold. And I'd like to do it so that I can still propagate gradient through non-zero ones. For example, in theano I could write: B = theano.tensor.switch(A < .1, 0, A) Is there a solution for that in pytorch?
As of pytorch 0.4+, you can do it easily with torch.where(see doc,Merged PR) It is as easy as in Theano. See yourself with an example: import torch from torch.autograd import Variable x = Variable(torch.arange(0,4), requires_grad=True) # x = [0 1 2 3] zeros = Variable(torch.zeros(*x.shape)) # zeros =...
https://stackoverflow.com/questions/49931756/
How to calculate the distance between a mini batch and a set of filters in PyTorch
I have a mini-batch of size NxDxWxH, where N is the size of the mini-batch, D is the dimension, and W and H are the width and height respectively. Assume that I have a set of filters F, each with dimension Dx1x1. I need to calculate the pairwise distance between the mini-batch and the filters. The size of the output sh...
You can do this by expanding the input and filters for proper automatic shape casting. # Assuming that input.size() is (N, D, W, H) and filters.size() is (F, D, 1, 1) input.unsqueeze_(1) filters.unsqueeze_(0) output = torch.sum((input - filters)**2, dim=2)
https://stackoverflow.com/questions/49934624/
pytorch multiply 4*1 matrix and 1 size variable occur error
import torch from torch.autograd import Variable import numpy as np x = np.transpose(np.array([[1, 2, 3, 4]])) a = Variable(torch.rand(1), requires_grad=True) print(a * x) # error! I want result like x = [[2][4][6][8]] if a = 2 is there any solution?
What you are looking for is the dot scalar product in matrix multiplication. try: x = np.transpose(np.array([[1, 2, 3, 4]])) a = 2 x.dot(a) This outputs a matrix [[2][4][6][8]]
https://stackoverflow.com/questions/49937990/
AttributeError: 'collections.OrderedDict' object has no attribute 'eval'
I have a model file which looks like this OrderedDict([('inp.conv1.conv.weight', (0 ,0 ,0 ,.,.) = -1.5073e-01 6.4760e-02 1.9156e-01 1.2175e-01 3.5886e-02 1.3992e-01 -1.5903e-01 8.2055e-02 1.7820e-01 (0 ,0 ,1 ,.,.) = 1.0604e-01 -1.3653...
It is not a model file, instead, this is a state file. In a model file, the complete model is stored, whereas in a state file only the parameters are stored. So, your OrderedDict are just values for your model. You will need to create the model and then need to load these values into your model. So, the process will be...
https://stackoverflow.com/questions/49941426/
Installing PyTorch via Conda
Objective: Create a conda environment with pytorch and torchvision. Anaconda Navigator 1.8.3, python 3.6, MacOS 10.13.4. What I've tried: In Navigator, created a new environment. Tried to install pytorch and torchvision but could not because the UI search for packages does not find any packages available matching py...
You seem to have installed PyTorch in your base environment, you therefore cannot use it from your other "pytorch" env. Either: directly create a new environment (let's call it pytorch_env) with PyTorch: conda create -n pytorch_env -c pytorch pytorch torchvision switch to the pytorch environment you have already cre...
https://stackoverflow.com/questions/49951846/
Is it possible to use different L1 / L2 regularization parameters for different sets of weights in chainer or pytorch?
(As an example) When implementing a simple linear model for noutput target values as a neural network in pytorch: l1=L.Linear(ninput, noutput) (call) y = self.l1(x) return y Adding this hook will do L2 regularization on all weights, imposing the same alpha=0.01 everywhere: optimizer.add_hook(optimizer.WeightDec...
Since we are working in pytorch it is possible to add other scalars to loss function yourself. So assume loss from you classfier is L ( assume it is a cross entropy loss ) and you have a linear layer defined as: l1 = nn.Linear(in,out) Now if you want to have different regularization on each set of weights then all y...
https://stackoverflow.com/questions/49965727/
PyTorch 3 reshaping error
When training a CNN using PyTorch in Python, I get the following error: RuntimeError: invalid argument 2: size '[-3 x 3136]' is invalid for input with 160000 elements at /opt/conda/conda-bld/pytorch-cpu_1515613813020/work/torch/lib/TH/THStorage.c:41 This is related to the x.view line in the model below: class Net(n...
I will assume your input images are probably of size 200x200px (by size I mean here height x width, not taking the number of channels into account). While your nn.Conv2d layers are defined to output tensors of the same size (with 32 channels for conv1 and 64 channels for con2), the F.max_pool2d are defined in such a w...
https://stackoverflow.com/questions/49980801/
Getting diagonal "stripe" from matrix in NumPy or PyTorch
I need to get the diagonal "stripe" of a matrix. Say I have a matrix of size KxN (K>N): [[ 0 1 2] [ 3 4 5] [ 6 7 8] [ 9 10 11]] From it I need to extract a diagonal stripe, in this case, a matrix MxV size that is created by truncating the original one: [[ 0 x x] [ 3 4 x] [ x 7 8] [ x x ...
stride_tricks do the trick: >>> import numpy as np >>> >>> def stripe(a): ... a = np.asanyarray(a) ... *sh, i, j = a.shape ... assert i >= j ... *st, k, m = a.strides ... return np.lib.stride_tricks.as_strided(a, (*sh, i-j+1, j), (*st, k, k+m)) ... >>> a = np.ara...
https://stackoverflow.com/questions/49982746/
Expected 4D tensor as input, got 2D tensor instead
I'm trying to build a neural network using the pre-trained network VGG16 on Pytorch. I understand that I need to adjust the classifier part of the network, so I have frozen the parameters to prevent backpropagation through them. Code: %matplotlib inline %config InlineBackend.figure_format = 'retina' import matplotl...
There are two problems with your network - You created your own classifier whose first layer accepts input of size (3*224*224), but this is not the output size of the features part of vgg16. Features output a tensor of size (25088) You are resizing your input to be a tensor of shape (3*224*224) (for each batch) ...
https://stackoverflow.com/questions/49993776/
What are transforms in PyTorch used for?
I am new with Pytorch and not very expert in CNN. I have done a successful classifier with the tutorial that they provide Tutorial Pytorch, but I don't really understand what I am doing when loading the data. They do some data augmentation and normalisation for training, but when I try to modify the parameters, the co...
transforms.Compose just clubs all the transforms provided to it. So, all the transforms in the transforms.Compose are applied to the input one by one. Train transforms transforms.RandomResizedCrop(224): This will extract a patch of size (224, 224) from your input image randomly. So, it might pick this path from to...
https://stackoverflow.com/questions/50002543/
Quickly find indices that have values larger than a threshold in Numpy/PyTorch
Task Given a numpy or pytorch matrix, find the indices of cells that have values that are larger than a given threshold. My implementation #abs_cosine is the matrix #sim_vec is the wanted sim_vec = [] for m in range(abs_cosine.shape[0]): for n in range(abs_cosine.shape[1]): # exclude diagonal cells ...
The following is for PyTorch (fully on GPU) # abs_cosine should be a Tensor of shape (m, m) mask = torch.ones(abs_cosine.size()[0]) mask = 1 - mask.diag() sim_vec = torch.nonzero((abs_cosine >= threshold)*mask) # sim_vec is a tensor of shape (?, 2) where the first column is the row index and second is the column i...
https://stackoverflow.com/questions/50045202/
How do you load MNIST images into Pytorch DataLoader?
The pytorch tutorial for data loading and processing is quite specific to one example, could someone help me with what the function should look like for a more generic simple loading of images? Tutorial: http://pytorch.org/tutorials/beginner/data_loading_tutorial.html My Data: I have the MINST dataset as jpg's in th...
Here's what I did for pytorch 0.4.1 (should still work in 1.3) def load_dataset(): data_path = 'data/train/' train_dataset = torchvision.datasets.ImageFolder( root=data_path, transform=torchvision.transforms.ToTensor() ) train_loader = torch.utils.data.DataLoader( train_dataset...
https://stackoverflow.com/questions/50052295/
Lack of Sparse Solution with L1 Regularization in Pytorch
I am trying to implement L1 regularization onto the first layer of a simple neural network (1 hidden layer). I looked into some other posts on StackOverflow that apply l1 regularization using Pytorch to figure out how it should be done (references: Adding L1/L2 regularization in PyTorch?, In Pytorch, how to add L1 regu...
Your usage of layer.weight.data removes the parameter (which is a PyTorch variable) from its automatic differentiation context, making it a constant when the optimiser takes the gradients. This results in zero gradients and that the L1 loss is not computed. If you remove the .data, the norm is computed of the PyTorch ...
https://stackoverflow.com/questions/50054049/
Load a single layer weights from a pretrained model
I want to specifically add the pretrained model parameters of some layers to my new network . For Linear Layer i just did : model_enc.linear_3d.weight = model_trained.linear_3d.weight model_enc.linear_3d.bias = model_trained.linear_3d.bias Will this suffice or are there any other parameters that I need to load or is...
Your solution should work and seems easy enough to me. From the source code on https://pytorch.org/docs/master/_modules/torch/nn/modules/linear.html#Linear you can see that the nn.Linear module has the attributes in_features, out_features, weight1 and bias: def __init__(self, in_features, out_features, bias=True): ...
https://stackoverflow.com/questions/50059592/
Load a single image in a pretrained pytorch net
Total newbie here, I'm using this pytorch SegNet implementation with a '.pth' file containing weights from a 50 epochs training. How can I load a single test image and see the net prediction? I know this may sound like a stupid question but I'm stuck. What I've got is: from segnet import SegNet import torch model = S...
output = model(image) . Note that the image should be a Variable object and that the output will be as well. If your image is, for example, a Numpy array, you can convert it like so: var_image = Variable(torch.Tensor(image))
https://stackoverflow.com/questions/50063514/
AttributeError: 'torch.FloatTensor' object has no attribute 'item'
Here are the codes: from __future__ import print_function from itertools import count import torch import torch.autograd import torch.nn.functional as F POLY_DEGREE = 4 W_target = torch.randn(POLY_DEGREE, 1) * 5 b_target = torch.randn(1) * 5 def make_features(x): x = x....
The function item() is new from PyTorch 0.4.0. When using earlier versions of PyTorch you will get this error. So you can upgrade your PyTorch version your to solve this. Edit: I got through your example again. What do you want archive with item()? In your case item() should just give you the (python) float value i...
https://stackoverflow.com/questions/50086577/
How can I make a FloatTensor with requires_grad=True from a numpy array using PyTorch 0.4.0?
Pytorch 0.4.0 introduced the merging on the Tensor and Variable classes. Before this version, when I wanted to create a Variable with autograd from a numpy array I would do the following (where x is a numpy array): x = Variable(torch.from_numpy(x).float(), requires_grad=True) With PyTorch version 0.4.0, the migrat...
How can I make a FloatTensor with requires_grad=True from a numpy array using PyTorch 0.4.0, preferably in a single line? If x is your numpy array this line should do the trick: torch.tensor(x, requires_grad=True) Here is a full example tested with PyTorch 0.4.0: import numpy as np import torch x = np.array([1.3,...
https://stackoverflow.com/questions/50087252/
How to apply a custom function to specific columns in a matrix in PyTorch
I have a tensor of size [150, 182, 91], the first part is just the batch size while the matrix I am interested in is the 182x91 one. I need to run a function on the 182x91 matrix for each of the 50 dimensions separately. I need to get a diagonal matrix stripe of the 182x91 matrix, and the function I am using is the ...
You can map the stripe function over the first dimension of your tensor using torch.unbind as In [1]: import torch In [2]: def strip(a): ...: i, j = a.size() ...: assert(i >= j) ...: out = torch.zeros((i - j + 1, j)) ...: for diag in range(0, i - j + 1): ...: out[diag] = torc...
https://stackoverflow.com/questions/50090821/
training a RNN in Pytorch
I want to have an RNN model and teach it to learn generating "ihello" from "hihell". I am new in Pytorch and following the instruction in a video to write the code. I have written two python files named train.py and model.py. this is model.py: #----------------- model for teach rnn hihell to ihello #----------------- ...
The scope of the variables defined in train.py (num_classes, input_size, ...) is the train.py itself. They are only visible in this file. The model.py is oblivious to these. I suggest including these arguments in the constructor: class Model(nn.Module): def __init__(self, hidden_size, input_size): # same and t...
https://stackoverflow.com/questions/50149049/
How does GPU utilization work in the context of neural network training?
I am using an AWS p3.2xlarge instance with the Deep Learning AMI (DLAMI). This instance has a single Tesla V100 (640 Tensor Cores and 5,120 CUDA Cores). When I run the PyTorch Seq2Seq Jupyter Notebook, I noticed that only 25% of the GPU is used. I monitor the GPU usage with the following command watch -n 1 nvidia-smi. ...
The power of GPUs over CPUs is to run many operations at the same time. However archiving this high level of parallelization is not always easy. Frameworks like Tensorflow or PyTorch do its best to optimise everything for GPU and parallelisation, but this is not possible for every case. Computations in LSTMs and RNNs...
https://stackoverflow.com/questions/50164417/
Does a clean and extendable LSTM implementation exists in PyTorch?
I would like to create an LSTM class by myself, however, I don't want to rewrite the classic LSTM functions from scratch again. Digging in the code of PyTorch, I only find a dirty implementation involving at least 3-4 classes with inheritance: https://github.com/pytorch/pytorch/blob/98c24fae6b6400a7d1e13610b20aa05...
The best implementation I found is here https://github.com/pytorch/benchmark/blob/master/rnns/benchmarks/lstm_variants/lstm.py It even implements four different variants of recurrent dropout, which is very useful! If you take the dropout parts away you get import math import torch as th import torch.nn as nn class L...
https://stackoverflow.com/questions/50168224/
Adapting pytorch softmax function
I am currently looking into the softmax function and I would like to adapt the orignally implemented for ome small tests. I have been to the docs but there wasn't that much of usefull information about the function. This is the pytorch python implementation: def __init__(self, dim=None): super(Softmax, self).__...
Softmax Implementation in PyTorch and Numpy A Softmax function is defined as follows: A direct implementation of the above formula is as follows: def softmax(x): return np.exp(x) / np.exp(x).sum(axis=0) Above implementation can run into arithmetic overflow because of np.exp(x). To avoid the overflow, we can divid...
https://stackoverflow.com/questions/50170011/
Implementing word dropout in pytorch
I want to add word dropout to my network so that I can have sufficient training examples for training the embedding of the "unk" token. As far as I'm aware, this is standard practice. Let's assume the index of the unk token is 0, and the index for padding is 1 (we can switch them if that's more convenient). This is a ...
Actually I would do it outside of your model, before converting your input into a LongTensor. This would look like this: import random def add_unk(input_token_id, p): #random.random() gives you a value between 0 and 1 #to avoid switching your padding to 0 we add 'input_token_id > 1' if random.random()...
https://stackoverflow.com/questions/50174230/
AttributeError: 'module' object has no attribute 'float32'
I am trying to use OpenNMT-py with python 2.7. OpenNMT-py requires torchtext, so I installed it but now when I am running my program, I am getting the following error message. Traceback (most recent call last): File "examples/StackPointerParser.py", line 23, in <module> from neuronlp2.io import get_logger,...
This is more a guess, as you have not given information about your version. But it seems to me that your torchtext version is not compatible with your PyTorch version. Probably when you installed torchtext you got the newer version already made for PyTorch 0.4.0. But your PyTorch version installed is still older than...
https://stackoverflow.com/questions/50186348/
What is the state of the art way of doing regression with probability in pytorch
All regression examples I find are examples where you predict a real number and unlike with classification you dont the the confidence the model had when predicting that number. I have done in reinforcement learning another way the output is instead the mean and std and then you sample from that distribution. Then you ...
The key point is that you do not need to sample from the NN-produced distribution. All you need is to optimize the likelihood of the target value under the NN distribution. There is an example in the official PyTorch example on VAE (https://github.com/pytorch/examples/tree/master/vae), though for multidimensional Bern...
https://stackoverflow.com/questions/50196212/
torch.nn.embedding has run time error
I want to use torch.nn.Embedding. I have followed the codes in the documentation of embedding command. here is the code: # an Embedding module containing 10 tensors of size 3 embedding = nn.Embedding(10, 3) # a batch of 2 samples of 4 indices each input = torch.LongTensor([[1,2,4,5],[4,3,2,9]]) embedding(input) The ...
if we change this line: input = torch.LongTensor([[1,2,4,5],[4,3,2,9]]) with this: input = autograd.Variable(torch.LongTensor([[1,2,4,5],[4,3,2,9]])) the problem is solved!
https://stackoverflow.com/questions/50196608/
How can I downgrade the version pytorch from 0.4 to 0.31 with anaconda?
I'm using anaconda now and due to some code error I need to downgrade the pytorch from version 0.4 to version 0.31. However, as I use anaconda as my python package management tool, I used the instruction below to downgrade it and encountered the following error: conda install pytorch=0.31 cuda80 -c soumith PackagesNo...
conda install pytorch=0.3.1.0 cuda80 -c soumith
https://stackoverflow.com/questions/50229857/
Loading FITS images with PyTorch
I'm trying to create a CNN using PyTorch but my images need importing from the FITS format rather than conventional .png or .jpeg etc. Is there a way to accomplish this easily using torch.utils.data.DataLoader or is there a place in the source code where I can put in a clause which will handle FITS files while loadin...
From reading some combination of the docs and the code, I don't think you necessarily want to be using ImageFolder since it doesn't know anything about FITS. Instead you should try using the more generic DataSetFolder class (which in fact is the parent class of ImageFolder). You would pass it a list of extensions it ...
https://stackoverflow.com/questions/50231298/
Pytorch Forward Pass Changes Each Time?
I am learning pytorch and running a toy regression problem. I am baffled by the fact that it appears that each time I run a tensor through a model, the prediction changes. Clearly this is cant be the case but what am I missing? Pytorch version: 0.4.0 I am running here without GPU to eliminate that potential issue. C...
Your network has a Dropout layer, which has for purpose to randomly sample (with a probability p=0.5 here) the data it receives during training (net.train() set before inference). See the doc for more information (usage, purpose). This layer can be short-circuited during testing (net.eval() set before inference).
https://stackoverflow.com/questions/50233272/
In pytorch, how to use the weight parameter in F.cross_entropy()?
I'm trying to write some code like below: x = Variable(torch.Tensor([[1.0,2.0,3.0]])) y = Variable(torch.LongTensor([1])) w = torch.Tensor([1.0,1.0,1.0]) F.cross_entropy(x,y,w) w = torch.Tensor([1.0,10.0,1.0]) F.cross_entropy(x,y,w) However, the output of cross entropy loss is always 1.4076 whatever w is. What is be...
The weight parameter is used to compute a weighted result for all inputs based on their target class. If you have only one input or all inputs of the same target class, weight won't impact the loss. See the difference however with 2 inputs of different target classes: import torch import torch.nn.functional as F from...
https://stackoverflow.com/questions/50248029/
How to train a Pytorch net
I'm using this Pytorch implementation of Segnet with pretrained values I found for object segmentation, and it works fine. Now I want to resume the training from the values I have, using a new dataset with similar images. How can I do that? I guess I have to use the "train.py" file found in the repository, but I don't...
If I had to guess he probablly made some Dataloader feeder that extended the Pytorch Dataloader class. See https://pytorch.org/tutorials/beginner/data_loading_tutorial.html Near the bottom of the page you can see an example in which they loop over their data loader for i_batch, sample_batched in enumerate(dataloade...
https://stackoverflow.com/questions/50249658/
How do I convert a Pandas dataframe to a PyTorch tensor?
How do I train a simple neural network with PyTorch on a pandas dataframe df? The column df["Target"] is the target (e.g. labels) of the network. This doesn't work: import pandas as pd import torch.utils.data as data_utils target = pd.DataFrame(df['Target']) train = data_utils.TensorDataset(df, target) train...
I'm referring to the question in the title as you haven't really specified anything else in the text, so just converting the DataFrame into a PyTorch tensor. Without information about your data, I'm just taking float values as example targets here. Convert Pandas dataframe to PyTorch tensor? import pandas as pd imp...
https://stackoverflow.com/questions/50307707/
Change values inside a Pytorch 3D tensor
I have a 224x224 binary image in a tensor (1, 224, 224), with 0-pixels representing background a 1-pixels representing foreground. I want to reshape it in a tensor (2, 224, 224), such as the first "layer" gt[0] has 1-pixels where there were 0-pixels in the original image and viceversa. This way one layer should show 1s...
Found a solution! gt = gt.repeat(2, 1, 1)
https://stackoverflow.com/questions/50327342/
PyTorch LSTM - using word embeddings instead of nn.Embedding()
Is the nn.Embedding() essential for learning for an LSTM? I am using an LSTM in PyTorch to predict NER - example of a similar task is here - https://pytorch.org/tutorials/beginner/nlp/sequence_models_tutorial.html Code wise, I am using code almost identical to the code in the tutorial above. The only detail is - I a...
nn.Embedding provides an embedding layer for you. This means that the layer takes your word token ids and converts these to word vectors. You can learn the weights for your nn.Embedding layer during the training process, or you can alternatively load pre-trained embedding weights. When you want to use a pre-traine...
https://stackoverflow.com/questions/50340016/
How to perform finetuning on a Pytorch net
I'm using this implementation of SegNet in Pytorch, and I want to finetune it. I've read online and I've found this method (basically freezing all layers except the last one in your net). My problem is that SegNet has more than 100 layers and I'm looking for a simpler way to do it, rather than writing 100 lines of code...
This process is called finetuning and setting requires_grad to False is a good way to do this. From the pytorch docs: Every Tensor has a flag: requires_grad that allows for fine grained exclusion of subgraphs from gradient computation and can increase efficiency. ... If there’s a single input to an operation ...
https://stackoverflow.com/questions/50353176/
How to use PyTorch to print out the prediction accuracy of every class?
I am trying to use PyTorch to print out the prediction accuracy of every class based on the official tutorial link But things seem to go wrong. My code intends to do this work is as following: for epoch in range(num_epochs): # Each epoch has a training and validation phase for phase in ['train', 'val']: ...
Finally, I solved this problem. First, I compared two models' parameters and found out they were the same. So I confirmed that the model is the same. And then, I checked out two inputs and surprisedly found out they were different. So I reviewed two models' inputs carefully and the answer was that the arguments passed...
https://stackoverflow.com/questions/50355859/
DLL files error in using pytorch
I add pytorch via pip installation and now I'm trying to use it, but have this dll error: Traceback (most recent call last): File "F:/Python/Projects/1.py", line 2, in <module> import torch File "C:\Users\Saeed\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\__init__.py", line 78, in <m...
You can use Dependency Walker to find out which dependency of that DLL might be missing. Use it to open the Python extension file that's failing to load. The file name should be something like: C:\Users\Saeed\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\_C.pyd Another common cause is a DLL for Pyth...
https://stackoverflow.com/questions/50368390/
Pytorch What's the difference between define layer in __init__() and directly use in forward()?
What is the difference between the method that define layers in __init__() function, call layer in forward later and the method that directly use layer in forward() function ? Should I define every layer in my compute graph in constructed function(eg. __init__) before I write my compute graph? Could I direct define and...
Everything which contains weights which you want to be trained during the training process should be defined in your __init__ method. You don't need do define activation functions like softmax, ReLU or sigmoid in your __init__, you can just call them in forward. Dropout layers for example also don't need to be defin...
https://stackoverflow.com/questions/50376463/
Reshaping Pytorch tensor
I have a tensor of size (24, 2, 224, 224) in Pytorch. 24 = batch size 2 = matrixes representing foreground and background 224 = image height dimension 224 = image width dimension This is the output of a CNN that performs binary segmentation. In each cell of the 2 matrixes is stored the probability for that pixel t...
Using torch.argmax() (for PyTorch +0.4): prediction = torch.argmax(tensor, dim=1) # with 'dim' the considered dimension prediction = prediction.unsqueeze(1) # to reshape from (24, 224, 224) to (24, 1, 224, 224) If the PyTorch version is below 0.4.0, one can use tensor.max() which returns both the max values and t...
https://stackoverflow.com/questions/50391703/
Pytorch - Stack dimension must be exactly the same?
In pytorch, given the tensors a of shape (1X11) and b of shape (1X11), torch.stack((a,b),0) would give me a tensor of shape (2X11) However, when a is of shape (2X11) and b is of shape (1X11), torch.stack((a,b),0) will raise an error cf. "the two tensor size must exactly be the same". Because the two tensor are the o...
It seems you want to use torch.cat() (concatenate tensors along an existing dimension) and not torch.stack() (concatenate/stack tensors along a new dimension): import torch a = torch.randn(1, 42, 1, 1) b = torch.randn(1, 42, 1, 1) ab = torch.stack((a, b), 0) print(ab.shape) # torch.Size([2, 1, 42, 1, 1]) ab = torch...
https://stackoverflow.com/questions/50394505/
Use torch.eq() only for some value in Pytorch
Is there a way to use torch.eq() or a similar function to compute element-based equality but only for some elements? Let's say I need to know how many 1s are equal in the two tensors but I don't care about other numbers. Any idea how to do this?
Let's say we have 2 tensors A and B filled with random elements and eventually some 1s somewhere. The tensor C is the result of want you aim for: A = torch.rand((2, 3, 3)) B = torch.rand((2, 3, 3)) # fill A and B with some 1s ... C = (A == 1) * (B == 1) Using the following tensors we get: (A) [[[ 0.6151, 1.0000...
https://stackoverflow.com/questions/50405832/
How to compute the cosine_similarity in pytorch for all rows in a matrix with respect to all rows in another matrix
In pytorch, given that I have 2 matrixes how would I compute cosine similarity of all rows in each with all rows in the other. For example Given the input = matrix_1 = [a b] [c d] matrix_2 = [e f] [g h] I would like the output to be output = [cosine_sim([a b] [e f]) cosine_sim([a b] ...
By manually computing the similarity and playing with matrix multiplication + transposition: import torch from scipy import spatial import numpy as np a = torch.randn(2, 2) b = torch.randn(3, 2) # different row number, for the fun # Given that cos_sim(u, v) = dot(u, v) / (norm(u) * norm(v)) # ...
https://stackoverflow.com/questions/50411191/
Reproducable Pytorch Results & Random Seeds
I have a simple toy NN with Pytorch. I am setting all the seeds I can find in the docs as well as numpy random. If I run the code below from top to bottom, the results appear to be reproducible. BUT, if I run block 1 only once and then each time run block 2, the result changes (sometimes dramatically). I am unsure ...
Possible Reason Not knowing what the "sometimes dramatic differences" are, it is hard to answer for sure; but having different results when running [block_1 x1; block_2 x1] xN (read "running block_1 then block_2 once; and repeat both operations N times) and [block_1 x1; block_2 xN] x1 makes sense, given how pseudo-r...
https://stackoverflow.com/questions/50412235/
Concatenating two tensors with different dimensions in Pytorch
Is it possible to concatenate two tensors with different dimensions without using for loop. e.g. Tensor 1 has dimensions (15, 200, 2048) and Tensor 2 has dimensions (1, 200, 2048). Is it possible to concatenate 2nd tensor with 1st tensor along all the 15 indices of 1st dimension in 1st Tensor (Broadcast 2nd tensor alo...
You could do the broadcasting manually (using Tensor.expand()) before the concatenation (using torch.cat()): import torch a = torch.randn(15, 200, 2048) b = torch.randn(1, 200, 2048) repeat_vals = [a.shape[0] // b.shape[0]] + [-1] * (len(b.shape) - 1) # or directly repeat_vals = (15, -1, -1) or (15, 200, 2048) if sha...
https://stackoverflow.com/questions/50424167/
can't import torch mac
I'm trying to import torch and I'm getting the next problem: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/torch/__init__.py", line 66, in <module> import torch._dl as _dl_flags Import...
Try like that: mkdir test_torch cd test_torch python3 -m venv .venv source .venv/bin/activate pip install torch torchvision python3 >>> import torch Works for me. MacOS 10.13.4, Python 3.6.4 Or like that: mkdir test_torch cd test_torch virtualenv .venv source .venv/bin/activate pip install --upgrade pip ...
https://stackoverflow.com/questions/50425739/
Byte Embedding in mLSTM Conceptual Struggle
I am trying to follow the OpenAI "Sentiment Neuron" experiment by reading through the PyTorch code posted on Github for training the model from scratch. One thing I am not understanding is the byte-level embedding used in the code. I understood that the LSTM outputs a probability distribution for the value of the next...
Even though the same symbols are being used for input and output, it's perfectly acceptable to have different representations used at each end. Cross entropy is a function of two probability distributions. In this case, the two distributions are the softmax distribution given by the model, and a point mass on the "corr...
https://stackoverflow.com/questions/50438738/
Pytorch, can't run backward() on even the most simple network without getting an error
I am new to pytorch and I can't run backward() on even the most simple network without generating an error. For example: (Linear(6, 6)(Variable(torch.zeros([10, 6]))) - Variable(torch.zeros([10, 6]))).backward() Throws the following error {RuntimeError}element 0 of variables does not require grad and does not ha...
Try adding a grad_output of matching shape as a parameter to backward: (Linear(6, 6)(Variable(torch.zeros([10, 6]))) - Variable(torch.zeros([10, 6]))).backward(torch.zeros([10, 6])) The following answer has more details: Why should be the function backward be called only on 1 element tensor or with gradients w.r.t to...
https://stackoverflow.com/questions/50446675/
RuntimeError: inconsistent tensor sizes at /pytorch/torch/lib/TH/generic/THTensorMath.c:2864
Im trying to build a dataloader, This is what it looks like `class WhaleData(Dataset): def __init__(self, data_file, root_dir , transform = None): self.csv_file = pd.read_csv(data_file) self.root_dir = root_dir self.transform = transforms.Resize(224) def __len__(self): return len(os.listdir(self.root...
The error appears when PyTorch tries to stack together the images into a single batch tensor (cf. torch.stack([torch.from_numpy(b) for b in batch], 0) from your trace). As you mentioned, since the images have different shape, the stacking fails (i.e. a tensor (B, H, W) can only be created by stacking B tensors if all t...
https://stackoverflow.com/questions/50454645/