instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
"Installing From Source" Within Anaconda Environment
What I would like to do: I am using macOS and Anaconda 2. I would like to install a Python package (specifically PyTorch) from source. I would like to install all the dependencies and the package itself within an Anaconda environment. I don't want this Anaconda environment to be the default/ root Anaconda environm...
I received this answer from the Anaconda Google discussion group and re-post it here in case anyone else is interested. It is the path to my_env. If you created it with -n my_env and you haven't otherwise changed your envs dir, it'll be in <anaconda root>/envs/my_env Yes, this is definitely good practice. The...
https://stackoverflow.com/questions/47799803/
pytorch loss value not change
I wrote a module based on this article: http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/ The idea is pass the input into multiple streams then concat together and connect to a FC layer. I divided my source code into 3 custom modules: TextClassifyCnnNet >> FlatCnnLayer >> FilterLa...
I realised that L2_loss in Adam Optimizer make loss value remain unchanged (I haven't tried in other Optimizer yet). It works when I remove L2_loss: # optimizer = optim.Adam(net.parameters(), lr=0.01, weight_decay=0.1) optimizer = optim.Adam(model.parameters(), lr=0.001) === UPDATE (See above answer for more detail!...
https://stackoverflow.com/questions/47813715/
How Pytorch Tensor get the index of specific value
With python lists, we can do: a = [1, 2, 3] assert a.index(2) == 1 How can a pytorch tensor find the .index() directly?
I think there is no direct translation from list.index() to a pytorch function. However, you can achieve similar results using tensor==number and then the nonzero() function. For example: t = torch.Tensor([1, 2, 3]) print ((t == 2).nonzero(as_tuple=True)[0]) This piece of code returns 1 [torch.LongTensor of size 1x1]...
https://stackoverflow.com/questions/47863001/
Why are Embeddings in PyTorch implemented as Sparse Layers?
Embedding Layers in PyTorch are listed under "Sparse Layers" with the limitation: Keep in mind that only a limited number of optimizers support sparse gradients: currently it’s optim.SGD (cuda and cpu), and optim.Adagrad (cpu) What is the reason for this? For example in Keras I can train an architecture with an E...
Upon closer inspection sparse gradients on Embeddings are optional and can be turned on or off with the sparse parameter: class torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2, scale_grad_by_freq=False, sparse=False) Where: sparse (boolean, optional) – if True, g...
https://stackoverflow.com/questions/47868341/
How to multiply a matrix by a vector in PyTorch
I'm playing around with PyTorch with the aim of learning it, and I have a very dumb question: how can I multiply a matrix by a single vector? Here's what I've tried: >>> import torch >>> a = torch.rand(4,4) >>> a 0.3162 0.4434 0.9318 0.8752 0.0129 0.8609 0.6402 0.2396 0.5720 0.72...
You're looking for torch.mv(a,b) Note that for the future, you may also find torch.matmul() useful. torch.matmul() infers the dimensionality of your arguments and accordingly performs either dot products between vectors, matrix-vector or vector-matrix multiplication, matrix multiplication or batch matrix multiplica...
https://stackoverflow.com/questions/47870003/
Strange behaviour in PyTorch
I started learning pyTorch recently.I moved from Torch community as I like Python. I encountered this strange behaviour in pyTorch.Any insights as why this happened would be appreciated. x=torch.Tensor(10,1).fill_(1) y=torch.Tensor(10).fill_(2) print(x.size()) #output is torch.Size([10, 1]) print(y.size()) #o...
When you're doing the sum between the torch Tensors, broadcasting is happening in the background. It's the same behaviour that you'd also see when you do the addition using NumPy. And, PyTorch simply follows the same broadcasting rules that is followed in NumPy. You can read and understand broadcasting here: NumPy Br...
https://stackoverflow.com/questions/47874207/
PyTorch Slow Batch matrix multiplication on GPU
I am using Batch Matrix Multiplication on 2 3d tensors of sizes (100 , 128 , 128 ) each. import torch a = torch.randn(100,128,128) b = torch.randn(100,128,128) import time t0 = time.time() torch.bmm(a,b) print(time.time() - t0) 0.03233695030212402 Now if i do the same thing on GPU it takes a lot longer a = a...
GPU: 30.57 secs is the total time taken by following steps: CPU launches kernels* on the device (GPU) CPU allocates memory on GPU CPU copies input data to GPU CPU launches kernels on GPU to process the input data CPU copies output results to itself *Kernel is a serial code which is a small part of the original cod...
https://stackoverflow.com/questions/47900761/
pytorch PIP and CONDA error?
Guys I am new to python and deeplearning world I tried to install pytorch using conda I get this Error... (base) C:\WINDOWS\system32>conda install pytorch `Solving environment: failed PackagesNotFoundError: The following packages are not available from current channels: pytorch Current channels: http...
However I found how to use Pytorch on windows here: [https://www.superdatascience.com/pytorch/] conda install -c peterjc123 pytorch Did the trick for me ...
https://stackoverflow.com/questions/47943081/
How to use pytorch DataLoader with a 3-D matrix for LSTM input?
I have a dataset of 3-D(time_stepinputsizetotal_num) matrix which is a .mat file. I want to use DataLoader to get a input dataset for LSTM which batch_size is 5. My code is as following: file_path = "…/database/frameLength100/notOverlap/a.mat" mat_data = s.loadmat(file_path) tensor_data = torch.from_numpy(mat_data[‘a’...
If I understand correctly, you want the batching to happen along the total_num dimension, i. e. dimension 2. You could simply use that the dimension to index your dataset, i.e. change __getitem__ to data = self.tensor_data[:, :, index], and accordingly in __len__, return self.tensor_data.size(2) instead of len(self.te...
https://stackoverflow.com/questions/47943419/
Issues installing pytorch for OS X with conda
I used to have pytorch working for python 3 on OS X but now I can't get it to install automatically for some reason (I don't want to do from source). I did: conda install pytorch torchvision -c pytorch as the website suggested... then I got a mkl error so I installed it but it still complains about it: (FTIR_py3) ...
As suggested in PyTorch forum, I think you should first install MKL. Your error trace also says that MKL is missing in your system. You can install MKL by doing: $ conda install -c anaconda mkl After this, install pytorch and torchvision by $ conda install -c pytorch pytorch torchvision
https://stackoverflow.com/questions/47955463/
Pytorch: CNN don't learn anything after torch.cat()?
I try to concatenate Variable in the network with code like this x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.layer4(x) x = x.view(x.size(0), -1) x= torch.cat((x,angle),1) # from here I concat it. x = self.dropout1(self.relu1(self.bn1(self.fc1(x)))) x = self.dropo...
Probably the error is somewhere outside of the code that you provided. Try to check if there are nan's in your input and check if the loss function is not resulting in nan.
https://stackoverflow.com/questions/47957458/
Why do we need to call zero_grad() in PyTorch?
Why does zero_grad() need to be called during training? | zero_grad(self) | Sets gradients of all model parameters to zero.
In PyTorch, for every mini-batch during the training phase, we typically want to explicitly set the gradients to zero before starting to do backpropragation (i.e., updating the Weights and biases) because PyTorch accumulates the gradients on subsequent backward passes. This accumulating behaviour is convenient while tr...
https://stackoverflow.com/questions/48001598/
pytorch: Does variable.long() guarantee 64-bits?
In pytorch, I have a variable that might be IntTensor or cuda.IntTensor. It needs to be changed to 64-bits retaining cpu/gpu. Does variable.long() guarantee 64-bits on all implementations of pytorch? If not, how can variable be converted to 64-bits retaining cpu/gpu for all implementations?
From PyTorch documentation here, torch.LongTensor or torch.cuda.LongTensor can be used to ensure a 64-bit signed integer. Similarly, for 64-bit floating points, you can use torch.DoubleTensor or torch.cuda.DoubleTensor. You can convert them into variables by using Variable(tensor) method where tensor represents the...
https://stackoverflow.com/questions/48033408/
Computing gradients of intermediate nodes in PyTorch
I'm trying to learn how autograd works in PyTorch. In the simple program below, I don't understand why gradients of loss w.r.t W1 and W2 are None. As far as I understand from the documentation, W1 and W2 are volatile, therefore gradients cannot be computed. Is that it? I mean, how I cannot take derivative of the loss...
When required, intermediate gradients are accumulated in a C++ buffer but in order to save memory they are not retained by default (exposed in python object). Only gradients of leaf Variables set with requires_grad=True will be retained (so Win your example) One way to retain intermediate gradients is to register a ho...
https://stackoverflow.com/questions/48051434/
Unknown Python syntax in PyTorch: a instance can directly receive a parameter
I have a question about Python syntax when I'm learning PyTorch. The following codes are an example from the PyTorch document. m = nn.Linear(20, 30) input = autograd.Variable(torch.randn(128, 20)) output = m(input) print(output.size()) This first line is to create an instance m, but why this instance m can directly ...
In python, any object can define a __call__ method that allows it to be used as a function like in your example. Reference: https://docs.python.org/2/reference/datamodel.html#object.call
https://stackoverflow.com/questions/48055762/
Installing a CPU-based library version on a GPU enabled machine
I want to install a CPU version of PyTorch on a server which is equipped with a nVIDIA Tesla GPU. Will it work or can I only install a GPU version (with CUDA) on this server for PyTorch to function properly?
The version of PyTorch with GPU support also works with CPU (but the cpu training of neural networks is really slow). So you can install the GPU version. Make sure you install PyTorch compiled with the correct cuda version (cuda 7.5, cuda 8.0 or cuda 9.0).
https://stackoverflow.com/questions/48062076/
PyTorch Softmax Dimensions error
I'm attempting to write a simple NN module, with 2 layers, first layer ReLU activation, output softmax with 3 classes (one-hot encoded). It seems theres something wrong with the way I'm using the softmax function, but I'm not sure what's going on. X is 178x13 Y is 178x3 Dataset I'm using is fairly simple, and can be...
This was a problem because for NLLLoss: The target that this loss expects is a class index (0 to N-1, where N = number of classes) And I had been trying to give it the one-hot encoded vector. I solved my issue by doing: loss = loss_fn(y_pred, torch.max(y, 1)[1]) Where torch.max found the maximum values and their ...
https://stackoverflow.com/questions/48070505/
Is it possible to implement a multilayered LSTM with LSTMCells modules in PyTorch?
In PyTorch there is a LSTM module which in addition to input sequence, hidden states, and cell states accepts a num_layers argument which specifies how many layers will our LSTM have. There is however another module LSTMCell which has just input size and number of hidden states as parameters, there is no num_layers s...
LSTMCell is the basic building block of an LSTM network. You should use the LSTM module (which uses LSTMCell internally). If you want to do this yourself, the best way is to read the source code (https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/rnn.py). Basically you want to use one LSTMCell for each la...
https://stackoverflow.com/questions/48080000/
Pytorch: Create an boolean tensor (type: torch.ByteTensor)?
I want to create a tensor only containing boolean values. In Matlab that would be a = false(10,1)
Already found it: a = torch.zeros(10) b = a.type(torch.ByteTensor)
https://stackoverflow.com/questions/48151637/
How do I check if PyTorch is using the GPU?
How do I check if PyTorch is using the GPU? The nvidia-smi command can detect GPU activity, but I want to check it directly from inside a Python script.
These functions should help: >>> import torch >>> torch.cuda.is_available() True >>> torch.cuda.device_count() 1 >>> torch.cuda.current_device() 0 >>> torch.cuda.device(0) <torch.cuda.device at 0x7efce0b03be0> >>> torch.cuda.get_device_name(0) 'GeForce GT...
https://stackoverflow.com/questions/48152674/
Pytorch Operation to detect NaNs
Is there a Pytorch-internal procedure to detect NaNs in Tensors? Tensorflow has the tf.is_nan and the tf.check_numerics operations ... Does Pytorch have something similar, somewhere? I could not find something like this in the docs... I am looking specifically for a Pytorch internal routine, since I would like this ...
You can always leverage the fact that nan != nan: >>> x = torch.tensor([1, 2, np.nan]) tensor([ 1., 2., nan.]) >>> x != x tensor([ 0, 0, 1], dtype=torch.uint8) With pytorch 0.4 there is also torch.isnan: >>> torch.isnan(x) tensor([ 0, 0, 1], dtype=torch.uint8)
https://stackoverflow.com/questions/48158017/
Where can I see the source code for pytorch's MSELoss?
I use the U-NET network to train my data. But I need to modify its loss function to reduce the loss of pixels below 1 to reduce the impact of negative cases on network weights. But I opened the source code in pycharm MSELOSS, see this: class MSELoss(_Loss): r"""Creates a criterion that measures the mean squared er...
There you go: https://github.com/pytorch/pytorch/blob/master/torch/nn/functional.py#L1423 However, it calls the C api def mse_loss(input, target, size_average=True, reduce=True): """ mse_loss(input, target, size_average=True, reduce=True) -> Variable Measures the element-wise mean squared error. See...
https://stackoverflow.com/questions/48219272/
What is the function in TensorFlow that is equivalent to expand() in PyTorch?
Let's say I have a 2 x 3 matrix and I want to create a 6 x 2 x 3 matrix where each element in the first dimension is the original 2 x 3 matrix. In PyTorch, I can do this: import torch from torch.autograd import Variable import numpy as np x = np.array([[1, 2, 3], [4, 5, 6]]) x = Variable(torch.from_numpy(x)) # y is...
Tensorflow automatically broadcasts, so in general you don't need to do any of this. Suppose you have a y' of shape 6x2x3 and your x is of shape 2x3, then you can already do y'*x or y'+x will already behave as if you had expanded it. But if for some other reason you really need to do it, then the command in tensorflow ...
https://stackoverflow.com/questions/48226221/
Pytorch: Intermediate testing during training
How can I test my pytorch model on validation data during training? I know that there is the function myNet.eval() which apparantly switches of any dropout layers, but is it also preventing the gradients from being accumulated? Also how would I undo the myNet.eval() command in order to continue with the training? If...
How can I test my pytorch model on validation data during training? There are plenty examples where there are train and test steps for every epoch during training. An easy one would be the official MNIST example. Since pytorch does not offer any high-level training, validation or scoring framework you have to writ...
https://stackoverflow.com/questions/48232381/
Advantages and Disadvantages of MXNet compared to other Deep Learning APIs
Recently I decided to learn MXNet, as some code I need to use, is written using this API. However, I would like to know which are the advantages and disadvantages of MXNet compared to the other Deep Learning Libraries out there.
Perhaps the biggest reason for considering MXNet is its high-performance imperative API. This is one of the most important advantages of MXNet to other platforms. Imperative API with autograd makes it much easier and more intuitive to compose and debug a network. PyTorch also supports imperative API, but MXNet is the o...
https://stackoverflow.com/questions/48233780/
PyTorch: Relation between Dynamic Computational Graphs - Padding - DataLoader
As far as I understand, the strength of PyTorch is supposed to be that it works with dynamic computational graphs. In the context of NLP, that means that sequences with variable lengths do not necessarily need to be padded to the same length. But, if I want to use PyTorch DataLoader, I need to pad my sequences anyway b...
In the context of NLP, that means that sequences with variable lengths do not necessarily need to be padded to the same length. This means that you don't need to pad sequences unless you are doing data batching which is currently the only way to add parallelism in PyTorch. DyNet has a method called autobatching (w...
https://stackoverflow.com/questions/48244053/
PyTorch's dataloader "too many open files" error when no files should be open
So this is a minimal code which illustrates the issue: This is the Dataset: class IceShipDataset(Dataset): BAND1='band_1' BAND2='band_2' IMAGE='image' @staticmethod def get_band_img(sample,band): pic_size=75 img=np.array(sample[band]) img.resize(pic_size,pic_size) ...
I know how to fix the error, but I don't have a complete explanation for why it happens. First, the solution: you need to make sure that the image data is stored as numpy.arrays, when you call json.loads it loads them as python lists of floats. This causes the torch.utils.data.DataLoader to individually transform each...
https://stackoverflow.com/questions/48250053/
Pytorch: How to compute IoU (Jaccard Index) for semantic segmentation
Can someone provide a toy example of how to compute IoU (intersection over union) for semantic segmentation in pytorch?
I found this somewhere and adapted it for me. I'll post the link if I can find it again. Sorry in case this was a dublicate. The key function here is the function called iou. The wrapping function evaluate_performance is not universal, but it shows that one needs to iterate over all results before computing IoU. impo...
https://stackoverflow.com/questions/48260415/
Pytorch - RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed
I keep running into this error: RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time. I had searched in Pytorch forum, but still can’t find out what I have done wrong in my custom loss function. My...
The problem is from my training loop: it doesn’t detach or repackage the hidden state in between batches? If so, then loss.backward() is trying to back-propagate all the way through to the start of time, which works for the first batch but not for the second because the graph for the first batch has been discarded. th...
https://stackoverflow.com/questions/48274929/
What's the difference between "hidden" and "output" in PyTorch LSTM?
I'm having trouble understanding the documentation for PyTorch's LSTM module (and also RNN and GRU, which are similar). Regarding the outputs, it says: Outputs: output, (h_n, c_n) output (seq_len, batch, hidden_size * num_directions): tensor containing the output features (h_t) from the last layer of the RN...
I made a diagram. The names follow the PyTorch docs, although I renamed num_layers to w. output comprises all the hidden states in the last layer ("last" depth-wise, not time-wise). (h_n, c_n) comprises the hidden states after the last timestep, t = n, so you could potentially feed them into another LSTM. The batch...
https://stackoverflow.com/questions/48302810/
PyTorch: How to change the learning rate of an optimizer at any given moment (no LR schedule)
Is it possible in PyTorch to change the learning rate of the optimizer in the middle of training dynamically (I don't want to define a learning rate schedule beforehand)? So let's say I have an optimizer: optim = torch.optim.SGD(model.parameters(), lr=0.01) Now due to some tests which I perform during training, I r...
So the learning rate is stored in optim.param_groups[i]['lr']. optim.param_groups is a list of the different weight groups which can have different learning rates. Thus, simply doing: for g in optim.param_groups: g['lr'] = 0.001 will do the trick. **Alternatively,** as mentionned in the comments, if your lea...
https://stackoverflow.com/questions/48324152/
Is location-dependent convolution filter possible in PyTorch or TensorFlow?
Let's pretend that in plus of having an image, I also have a gradient from left to right on the X axis of an image, and another gradient from top to bottom on the Y axis. Those two gradients are of the same size of the image, and could both range from -0.5 to 0.5. Now, I'd like to make the convolution kernel (a.k.a. ...
Here is a solution I thought for a simplified version of this problem where a linear combination of weights would be used rather than truly using a nested mini neural network: It may be possible to do 4 different convolutions passes so as to have 4 feature maps, then to multiply those 4 maps with the gradients (2 ver...
https://stackoverflow.com/questions/48331966/
What's the reason of the error ValueError: Expected more than 1 value per channel?
reference fast.ai github repository of fast.ai (as the code elevates the library which is built on top of PyTorch) Please scroll the discussion a bit I am running the following code, and get an error while trying to pass the data to the predict_array function The code is failing when i am trying to use it to pr...
It will fail on batches of size 1 if we use feature-wise batch normalization. As Batch normalization computes: y = (x - mean(x)) / (std(x) + eps) If we have one sample per batch then mean(x) = x, and the output will be entirely zero (ignoring the bias). We can't use that for learning...
https://stackoverflow.com/questions/48343857/
BatchNorm momentum convention PyTorch
Is the batchnorm momentum convention (default=0.1) correct as in other libraries e.g. Tensorflow it seems to usually be 0.9 or 0.99 by default? Or maybe we are just using a different convention?
It seems that the parametrization convention is different in pytorch than in tensorflow, so that 0.1 in pytorch is equivalent to 0.9 in tensorflow. To be more precise: In Tensorflow: running_mean = decay*running_mean + (1-decay)*new_value In PyTorch: running_mean = (1-decay)*running_mean + decay*new_value This ...
https://stackoverflow.com/questions/48345857/
How to model Convolutional recurrent network ( CRNN ) in Keras
I was trying to port CRNN model to Keras. But, I got stuck while connecting output of Conv2D layer to LSTM layer. Output from CNN layer will have a shape of ( batch_size, 512, 1, width_dash) where first one depends on batch_size, and last one depends on input width of input ( this model can accept variable width inpu...
You don't need to permute the batch axis in Keras. In a pytorch model you need to do it because a pytorch LSTM expects an input shape (seq_len, batch, input_size). However in Keras, the LSTM layer expects (batch, seq_len, input_size). So after defining the CNN and squeezing out axis 2, you just need to permute the las...
https://stackoverflow.com/questions/48356464/
Converting state-parameters of Pytorch LSTM to Keras LSTM
I was trying to port an existing trained PyTorch model into Keras. During the porting, I got stuck at LSTM layer. Keras implementation of LSTM network seems to have three state kind of state matrices while Pytorch implementation have four. For eg, for an Bidirectional LSTM with hidden_layers=64, input_size=512 &...
They are really not that different. If you sum up the two bias vectors in PyTorch, the equations will be the same as what's implemented in Keras. This is the LSTM formula on PyTorch documentation: PyTorch uses two separate bias vectors for the input transformation (with a subscript starts with i) and recurrent tran...
https://stackoverflow.com/questions/48361376/
Pytorch: Updating numpy array not updating the corresponding tensor
When I run the following code, import numpy as np a = np.ones(3) b = torch.from_numpy(a) np.add(a, 1, out=a) print(a) print(b) Both a and b are 2s. However, When I run: import numpy as np a = np.ones(3) b = torch.from_numpy(a) a = a+1 print(a) print(b) b remains as 1s while a has been updated to 2s. Is this an ...
Yes, as @hpaulj pointed out in his comment, the operation a = a + 1 creates copy of the original array a and adds 1 using broadcasting. And after addition, since we assign it to a, so a gets updated to the result of addition operation. But, b still shares the memory of the original array a (i.e. the array a that was...
https://stackoverflow.com/questions/48370286/
RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1)
Im using a Pytorch Unet model to which i am feeding in a image as input and along with that i am feeding the label as the input image mask and traning the dataset on it. The Unet model i have picked up from somewhere else, and i am using the cross-entropy loss as a loss function but i get this dimension out of range er...
According to your code: probs_flat = probs.view(-1) targets_flat = targets.view(-1) return self.crossEntropy_loss(probs_flat, targets_flat) You are giving two 1d tensor to nn.CrossEntropyLoss but according to documentation, it expects: Input: (N,C) where C = number of classes Target: (N) where each value is 0 <=...
https://stackoverflow.com/questions/48377214/
pytorch model.cuda() runtime error
I'm building a text classifier using pytorch, and got into some trouble with .cuda() method. I know that .cuda() moves all parameters into gpu so that the training procedure can be faster. However, error occurred in .cuda() method like this: start_time = time.time() for model_type in ('lstm',): hyperparam_comb...
model.cuda() is called inside your training/test loop, which is the problem. As the error message suggests, you repeatedly convert parameters(tensors) in your model to cuda, which is not the right way to convert model into cuda tensor. model object should be created and cuda-ize outside the loop. Only training/test in...
https://stackoverflow.com/questions/48400225/
Given input size: (128x1x1). Calculated output size: (128x0x0). Output size is too small
I am trying to train a U-Net which looks like this `class UNet(nn.Module): def __init__(self, imsize): super(UNet, self).__init__() self.imsize = imsize self.activation = F.relu self.pool1 = nn.MaxPool2d(2) self.pool2 = nn.MaxPool2d(2) self.pool3 = nn.MaxPool2d(2) self.pool4 = nn.MaxPool2...
Your problem is that before the Pool4 your image has already reduced to a 1x1pixel size image. So you need to either feed an much larger image of size at least around double that (~134x134) or remove a pooling layer in your network.
https://stackoverflow.com/questions/48402009/
pytorch lstm tutorial initializing Variable
I am going through the pytorch tutorial for lstm and here's the code they use: lstm = nn.LSTM(3, 3) # Input dim is 3, output dim is 3 inputs = [autograd.Variable(torch.randn((1, 3))) for _ in range(5)] # make a sequence of length 5 # initialize the hidden state. hidden = (autograd.Variable(torch.randn(1, ...
First to quickly answer number 2: They are identical. I don't know why they would do them differently. Next, to answer question 1: hidden is a tuple that contains two Variables that are essentially a 1 x 1 x 3 tensor. Let's focus on what (0 ,.,.). If instead of a 1 x 1 x 3 tensor you had a 2 x 2 tensor, you could s...
https://stackoverflow.com/questions/48412696/
Pytorch transfer learning predictions
I have been following the pytorch transfer learning tutorial,and following the tutorial to my own dataset i have arrived at this model_conv = train_model(model_conv, criterion, optimizer_conv, exp_lr_scheduler, num_epochs=25) Epoch 1/1 ...... ...... ...... Epoch 24/24 train Loss: 0.8674 Acc: 0.5...
Simply feed the new image (in the same format as the images in your training dataset were) to the model: labels = model_conv(new_images)
https://stackoverflow.com/questions/48414717/
How to setup pytorch in google-cloud-ml
I try to throw job with Pytorch code in google-cloud-ml. so I code the "setup.py" file. And add option "install_requires" "setup.py" from setuptools import find_packages from setuptools import setup REQUIRED_PACKAGES = ['http://download.pytorch.org/whl/cpu/torch-0.3.0.post4-cp27-cp27mu-linux_x86_64.whl','torchvisio...
i find solution about setting up PYTORCH in google-cloud-ml first you have to get a .whl file about pytorch and store it to google storage bucket. and you will get the link for bucket link. gs://bucketname/directory/torch-0.3.0.post4-cp27-cp27mu-linux_x86_64.whl the .whl file is depend on your python version or cu...
https://stackoverflow.com/questions/48434556/
PyTorch: training with GPU gives worse error than training the same thing with CPU
I have a next step prediction model on times series which is simply a GRU with a fully-connected layer on top of it. When I train it using CPU after 50 epochs I get a loss of 0.10 but when I train it with GPU the loss is 0.15 after 50 epochs. Doing more epochs doesnt really lower the losses in either cases. Why is pe...
After trying many things I think I found the problem. Apparently the CUDNN libraries are sub-optimal in PyTorch. I don't know if it is a bug in PyTorch or a bug in CUDNN but doing torch.backends.cudnn.enabled = False solves the problem. With the above line, training with GPU or CPU gives the same loss at the same e...
https://stackoverflow.com/questions/48445942/
unknown resampling filter error when trying to create my own dataset with pytorch
I am trying to create a CNN implemented with data augmentation in pytorch to classify dogs and cats. The issue that I am having is that when I try to input my dataset and enumerate through it I keep getting this error: Traceback (most recent call last): File "<ipython-input-55-6337e0536bae>", line 75, in &l...
Try to set the desired size in transforms.Resize as a tuple: transforms.Resize((64, 64)) PIL is using the second argument (in your case 64) as the interpolation method.
https://stackoverflow.com/questions/48446898/
Problems with PyTorch MLP when training the MNIST dataset retrieved from Keras
I have finished a PyTorch MLP model for the MNIST dataset, but got two different results: 0.90+ accuracy when using MNIST dataset from PyTorch, but ~0.10 accuracy when using MNIST dataset from Keras. Below is my code with dependency: PyTorch 0.3.0.post4, keras 2.1.3, tensorflow backend 1.4.1 gpu version. from __futu...
The MNIST data coming from Keras are not normalized; following the Keras MNIST MLP example, you should do it manually, i.e. you should include the following in your load_data() function: x /= 255 x_test /= 255 Not sure about PyTorch, but it would seem that the MNIST data from their own utility functions come already...
https://stackoverflow.com/questions/48477198/
How to find the index of a tensor in a list?
I want to find the index of the smallest tensor (by some key function) in a list li. So I did min and afterwards li.index(min_el). My MWE suggests that somehow tensors don't work with index. import torch li=[torch.ones(1,1), torch.zeros(2,2)] li.index(li[0]) 0 li.index(li[1]) Traceback (most recent call last): File ...
You could directly find the index by using enumerate and a key function that operates on the second element of each tuple. For instance, if your key function compares the first element of the each tensor, you could use ix, _ = min(enumerate(li), key=lambda x: x[1][0, 0]) I think the reason why index succeeds for the...
https://stackoverflow.com/questions/48527722/
Loss is increasing from first epoch itself
I am training my siamese network for nlp. I have used lstm in it. and BCELoss. My loss is increasing from the first epoch. The first 36 epoch loss is error after 0 is 272.4357 [torch.FloatTensor of size 1] error after 1 is 271.8972 [torch.FloatTensor of size 1] error after 2 is 271.5598 [torch.FloatTensor o...
Probably your learning rate is too high. Try decreasing your learning rate. A too large learning rate is the most common reason for loss increasing from the first epoch. Also your loss is very high. It is unusual to have such a high lost. You probably have a sum in your loss function, it might be wiser to replace tha...
https://stackoverflow.com/questions/48527808/
Pytorch Test Loss increases while accuracy increases
I am trying to implement End to End Memory Network using Pytorch and BabI dataset. The network architecture is : MemN2N ( (embedding_A): Embedding(85, 120, padding_idx=0) (embedding_B): Embedding(85, 120, padding_idx=0) (embedding_C): Embedding(85, 120, padding_idx=0) (match): Softmax () ) 85 is the vocabulary si...
When training loss continues to decrease but test loss starts to increase, that is the moment you are starting to overfit, that means that your network weights are fitting the data you are training on better and better, but this extra fitting will not generalize to new unseen data. This means that that is the moment yo...
https://stackoverflow.com/questions/48541336/
How to calculate cost for softmax regression with pytorch
I would to calculate the cost for the softmax regression. The cost function to calculate is given at the bottom of the page. For numpy I can get the cost as follows: """ X.shape = 2,300 # floats y.shape = 300, # integers W.shape = 2,3 b.shape = 3,1 """ import numpy as np np.random.seed(100) # Data and labels X = n...
Your problem is that you cannot use range(N) with pytorch, use the slice 0:N instead: hyp = torch.exp(scores - torch.max(scores)) probs = hyp / torch.sum(hyp) correct_probs = probs[0:N,y] # problem solved logprobs = torch.log(correct_probs) cost_data = -1/N * torch.sum(logprobs) Another point is that your labels y d...
https://stackoverflow.com/questions/48549101/
How to take the average of the weights of two networks?
Suppose in PyTorch I have model1 and model2 which have the same architecture. They were further trained on same data or one model is an earlier version of the othter, but it is not technically relevant for the question. Now I want to set the weights of model to be the average of the weights of model1 and model2. How wo...
beta = 0.5 #The interpolation parameter params1 = model1.named_parameters() params2 = model2.named_parameters() dict_params2 = dict(params2) for name1, param1 in params1: if name1 in dict_params2: dict_params2[name1].data.copy_(beta*param1.data + (1-beta)*dict_params2[name1].data) model.load_state_di...
https://stackoverflow.com/questions/48560227/
ImportError when importing pytorch
When I try importing pytorch inside a jupyter notebook i get the following error: ImportError: dlopen: cannot load any more object with static TLS pytorch import torch No error when i import torch from command line (not jupyter notebook)
For reasons i cannot yet explain, i found out that this is happening only when i install Keras too in the same virtual environment, and it goes away when i uninstall Keras. So the solution was pip uninstall keras
https://stackoverflow.com/questions/48564959/
pytorch variable index lost one dimension
I am going to get every horizontal tensor in a variable but I got one dimension lost. This is my code: import torch from torch.autograd import Variable t = torch.rand((2,2,4)) x = Variable(t) print(x) shape = x.size() for i in range(shape[0]): for j in range(shape[1]): print(x[i,j]) and the output is : Var...
In your case, x is a 2x2x4 tensor. So when you do x[0] you obtain the 2x4 tensor which is in the first row. And if you do x[i,j] you obtain the 4 dimensional vector in position (i,j). If you want to retain one of the dimensions you can either use a slice: x[i,j:j+1] OR reshape the tensor: x[i,j].view(1,4). Thus your co...
https://stackoverflow.com/questions/48577014/
How can I find the equivalent 'batch_size' used in Keras from this Pytorch code?
I am using Pytorch code from github I am trying to port this over to Keras. In particular, Keras uses model.fit for training the Neural net and has a batch_size parameter. I am trying to set this but cannot determine it in the Pytorch script linked above. In the script, there is a function called sliding_window in ...
Below find an example on how to write a Learning Rate scheduler in Keras: from keras.callbacks import Callback from keras import backed as K class LRSchedule(Callback): def __init__(self, schedule): super(LRSchedule, self).__init__() self.schedule = schedule def on_train_begin(self, logs = {}...
https://stackoverflow.com/questions/48586429/
Kaggle Pytorch run length encoding
Im working on the DSB problem in pytorch,I have my predictions but im not sure how to get those into the run length encoding format that is required for the submission,In short this is what it is =================================================================== In order to reduce the submission file size, our metr...
Try if something like that works def rle_encode(image): """ receives a masked image and encodes it to RLE :param mask_image: :return: string corresponding to the rle of the input image """ pixels = image.flatten() # We avoid issues with '1' at the start or end (at the corners of # the o...
https://stackoverflow.com/questions/48599440/
Where is the len function used in PyTorch Dataset?
I am looking to use the code from here . However, I am looking at box 5, where there is the following function; def __len__(self): # Default epoch size is 10 000 samples return 10000 I do not see anywhere throughout this script where this function is being used. Clarification on this would be appreciated. ...
This is a function of the Dataset class. The __len__() function specifies the size of the dataset. In your referenced code, in box 10, a dataset is initialized and passed to a DataLoader object: train_set = ISPRS_dataset(train_ids, cache=CACHE) train_loader = torch.utils.data.DataLoader(train_set,batch_size=BATCH_SIZE...
https://stackoverflow.com/questions/48608585/
Result of slicing in an empty tensor
Can anyone help me to understand why this works: lens = list(range(170,1,-1)) xs = Variable(torch.randn(169, 200, 1)) packed = torch.nn.utils.rnn.pack_padded_sequence(xs, lens, batch_first=True) and this does not: lens = [294, 289, 288, 282, 273, 270, 261, 260, 240, 235, 231, 228, 228, 227, 226, 226, 199, 195, 194,...
Answering my own question. In fact it was answered by SimomW at the Pytorch forum: https://discuss.pytorch.org/t/result-of-slicing-is-an-empty-tensor/13306 It happens because the first len has values all <= 200, but the second has many > 200, which is the maximum seq_len a tensor of shape 169,200,1 can have.
https://stackoverflow.com/questions/48626992/
Simple Pytorch Example - Loss on training doesnt decrease
I am just starting to try and learn pytorch and am finding it frustrating regardless of how it is advertised :) Here I am running a simple regression as an experiment but since the loss doesn't seem to be decreasing with each epoch (on the training) I must be doing something wrong -- either in training or how I am col...
Well I just changed the line: training_samples = utils_data.TensorDataset(torch.from_numpy(x), torch.from_numpy(y)) Adding the torch.from_numpy (otherwise, it was throwing an error, thus nor running) and I get a learning curve that looks something like this:
https://stackoverflow.com/questions/48675563/
Installing Pytorch on Windows 10
I am trying to install Pytorch on Windows 10 anaconda environment with Python 3.6 using the following command: conda install -c peterjc123 pytorch But it gives the following error: UnsatisfiableError: The following specifications were found to be in conflict: - curl -> krb5=1.14 -> *[track_features=vc14] ...
I solved the issue by side loading the pytorch's tar.bz2 file
https://stackoverflow.com/questions/48675722/
reshaping a tensor with padding in pytorch
How do I reshape a tensor with dimensions (30, 35, 49) to (30, 35, 512) by padding it?
While @nemo's solution works fine, there is a pytorch internal routine, torch.nn.functional.pad, that does the same - and which has a couple of properties that a torch.ones(*sizes)*pad_value solution does not (namely other forms of padding, like reflection padding or replicate padding ... it also checks some gradient-...
https://stackoverflow.com/questions/48686945/
How can I download and skip VGG weights that have no counterpart with my CNN in Keras?
I would like to follow the Convolutional Neural Net (CNN) approach here. However, this code in github uses Pytorch, whereas I am using Keras. I want to reproduce boxes 6,7 and 8 where pre-trained weights from VGG-16 on ImageNet is downloaded and is used to make the CNN converge faster. In particular, there is a port...
The technique you are addressing is called "Transfer Learning" - when a pre-trained model on a different dataset is used as part of the model as a starting point for better convergence. The intuition behind it is simple: we assume that after training on such a large and rich dataset as ImageNet, the convolution kernels...
https://stackoverflow.com/questions/48716184/
Error when implementing RBF kernel bandwidth differentiation in Pytorch
I'm implementing an RBF network by using some beginer examples from Pytorch Website. I have a problem when implementing the kernel bandwidth differentiation for the network. Also, Iwould like to know whether my attempt ti implement the idea is fine. This is a code sample to reproduce the issue. Thanks # -*- coding: ut...
Well, you are calling kernel_product(w1, x, s) where w1, x and s are torch Variable while the definition of the function is: kernel_product(x,y, mode = "gaussian", s = 1.). Seems like s should be a string specifying the mode.
https://stackoverflow.com/questions/48729473/
setuptools: installing pytorch from download link: 403 Forbidden
I am trying to include pytorch in the requirements list for setuptools: install_requires=[ 'torch' ], dependency_links=[ 'http://download.pytorch.org/whl/cpu/torch-0.3.0.post4-cp27-cp27mu-linux_x86_64.whl' '@develop#egg=torch' ], But after running python setup.py develop I receive: error: Ca...
First error: if you use direct URL to a wheel file: http://download.pytorch.org/whl/cpu/torch-0.3.0.post4-cp27-cp27mu-linux_x86_64.whl You must not use @develop#egg=torch. That part is for installing from VCS like git. The second URL https://github.com/pytorch/pytorch#from-source is also wrong. It should be htt...
https://stackoverflow.com/questions/48743554/
Mini batch training for inputs of variable sizes
I have a list of LongTensors, and another list of labels. I'm new to PyTorch and RNN's so I'm quite confused as to how to implement minibatch training for the data I have. There is much more to this data, but I want to keep it simple, so I can understand only how to implement the minibatch training part. I'm doing mult...
Yes. The issue with minibatch training on sequences which have different lengths is that you can't stack sequences of different lengths together. Normally one would do. for e in range(epochs): sequences = shuffle(sequences) for mb in range(len(sequences)/mb_size): batch = torch.stack(sequences[mb*mb_s...
https://stackoverflow.com/questions/48796469/
Reading multiple images as custom dataset for PyTorch?
I want to read in multiple images for the main_image set and blur_image set. For example, 5 main images and 5 blurred images. The goal is determine what values for the kernel in the convolutional layer convert the main images to the blurred images. The assumption is that the same kernel is used to blur each of the 5 or...
In your class BlurDataset you only return one image in the __getitem__ method. In your main method you call for batch_idx, (main, blur) in enumerate(train_loader) The torch.utils.data.Dataset class that you inherit from then calls __getitem__ with the index given by enumerate. It will give you one pair of pictures ...
https://stackoverflow.com/questions/48815203/
PyTorch: How do the means and stds get calculated in the Transfer Learning tutorial?
I'm going through the PyTorch Transfer Learning tutorial at: link In the data augmentation stage, there is the following step to normalize images: transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) I can understand why it's doing this but I can't find how the mean and std values get calculated? I tr...
Your numbers don't seem right to me; since the ToTensor transform has output in the range [0.0, 1.0] it shouldn't be possible to get a negative mean. If I calculate the mean with traindata = datasets.ImageFolder(data_dir + '/train', transforms.ToTensor()) image_means = torch.stack([t.mean(1).mean(1) for t, c in train...
https://stackoverflow.com/questions/48818619/
How to use PyTorch multiprocessing?
I'm trying to use python's multiprocessing Pool method in pytorch to process a image. Here's the code: from multiprocessing import Process, Pool from torch.autograd import Variable import numpy as np from scipy.ndimage import zoom def get_pred(args): img = args[0] scale = args[1] scales = args[2] img_scale =...
As stated in pytorch documentation the best practice to handle multiprocessing is to use torch.multiprocessing instead of multiprocessing. Be aware that sharing CUDA tensors between processes is supported only in Python 3, either with spawn or forkserver as start method. Without touching your code, a workaround for ...
https://stackoverflow.com/questions/48822463/
Google Ngram Viewer - English One Million
I'm training a language model in PyTorch and I'd need the most common one million words in English to serve as dictionary. From what I've understood, the Google Ngram English One Million (1-grams) might suit to this task, but after downloading every part (0-9) of this dataset and using tail on them to check if they we...
Try shuf <file> to get a random sorting and you will see the data covers all letters. What you see at the end of the files is not an f but the ligature fl.
https://stackoverflow.com/questions/48830857/
LSTM in Pytorch
I'm new to PyTorch. I came across some this GitHub repository (link to full code example) containing various different examples. There is also an example about LSTMs, this is the Network class: # RNN Model (Many-to-One) class RNN(nn.Module): def __init__(self, input_size, hidden_size, num_layers, num_classes): ...
Obviously I was on the wrong track with this. I was confusing hidden units and hidden/cell state. Only the hidden units in the LSTM are trained during the training step. Cell state and hidden state are resetet at the beginning of every sequence. So it just makes sense that it is programmed this way. Sorry for this..
https://stackoverflow.com/questions/48831585/
ouputs in semantic segmentation task
Im working on the Kaggle semantic segmentation task, In the testing part of my code, model = model.eval() predictions =[] for data in testdataloader: data = t.autograd.Variable(data, volatile=True).cuda() output = model.forward(data) _,preds = t.max(output, 1, keepdim = True) when i do the preds part,th...
Assuming your data is of the form MiniBatch x Dim what you are doing now is looking at which minibatch has the highest value. If you are testing it with a single sample (MB = 1) then you will always get 0 as your answer. Thus, you might want to try: _,preds = t.max(output, 0, keepdim = False)
https://stackoverflow.com/questions/48849715/
Why unintialized tensor in Pytorch have initial values?
The torch command x = torch.Tensor(4, 3) is supposed to create an uninitialized tensor (based on documentations). But when we try to print the content of x, there are values there. >>>from __future__ import print_function >>>print(x) 0.0000e+00 -8.5899e+09 6.1021e-38 8.5920e+09 1.7470e-21...
It means that PyTorch just reserves a certain area within the memory for the tensor, without changing its content. This part of the memory was before occupied by something else (an other tensor or or maybe something completely different like Browser, Code Editor .. if you use CPU memory). The values inside are not cl...
https://stackoverflow.com/questions/48869836/
Package Cuda 8 not found for PyTorch
I am trying to follow the tutorial for chatbots at facebook (https://github.com/facebookresearch/end-to-end-negotiator) and I am stuck here : conda install pytorch torchvision cuda80 -c soumith I managed to get all packages except for cuda80 which is not found. I also tried conda install magma-cuda80 -c soumith conda ...
Open Anaconda Prompt and run - conda install -c peterjc123 pytorch cuda80 OR conda install -c peterjc123 pytorch cuda90
https://stackoverflow.com/questions/48874285/
Install Pytorch on Windows
I am trying to install Pytorch on Windows8.1. I am using Python 3.6.4 and no GPU. I've tried already the Anaconda package provided by peterjc123 by running conda install -c peterjc123 pytorch_legacy cuda80 using a virtual environment. While the installation goes smooth (without errors), after import torch I get the fol...
You are installing the GPU version with the command. Check the link for the github repo. In short, you should run something like conda install -c peterjc123 pytorch. Be sure to install the required dependencies before attempting to install the main framework. For more details, check the link.
https://stackoverflow.com/questions/48895910/
What does .contiguous() do in PyTorch?
What does x.contiguous() do for a tensor x?
There are a few operations on Tensors in PyTorch that do not change the contents of a tensor, but change the way the data is organized. These operations include: narrow(), view(), expand() and transpose() For example: when you call transpose(), PyTorch doesn't generate a new tensor with a new layout, it just modifies...
https://stackoverflow.com/questions/48915810/
PyTorch Sparse Tensors number of dimensions must be nDimI + nDimV
I'm trying to insert the value in gd to coordinate [1,0]. Below are the matrices. When I try this, I get a RuntimeError. >>> import torch >>> cd = [[1, 0]] >>> gd = [0.39613232016563416] >>> i = torch.LongTensor(cd) >>> v = torch.FloatTensor(gd) >>> p = torch.rand(...
Two things. 1) Right now p is a Tensor of rank 1. To insert something in position [1,0] it needs to be a Tensor of rank 2. 2) You don't need to do complicated things with sparse tensors. Simply p[cd[0], cd[1]] = v[0] should work. Where cd = torch.LongTensor([row_idx, col_idx]) So: >>> cd = torch.LongTensor...
https://stackoverflow.com/questions/48941208/
multiprocessing error with pytorch on windows 10
i get the following error when i try to execute my code, which clearly shows its an mulitprocessing error: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. On Linux, the following code runs fine, but Im wondering why i cant get it running on Windows 10....
I found it out myself. I had to put the whole code into if name == 'main': Also i forgot the brakets in the end at the transforms.ToTensor part.
https://stackoverflow.com/questions/49013664/
PyTorch - How to use "toPILImage" correctly
I would like to know, whether I used toPILImage from torchvision correctly. I want to use it, to see how the images look after initial image transformations are applied to the dataset. When I use it like in the code below, the image that comes up has weird colors like this one. The original image is a regular RGB imag...
You can use PIL image but you're not actually loading the data as you would normally. Try something like this instead: import numpy as np import matplotlib.pyplot as plt for img,labels in train_data_loader: # load a batch from train data break # this converts it from GPU to CPU and selects first image img = i...
https://stackoverflow.com/questions/49035156/
Pytorch softmax: What dimension to use?
The function torch.nn.functional.softmax takes two parameters: input and dim. According to its documentation, the softmax operation is applied to all slices of input along the specified dim, and will rescale them so that the elements lie in the range (0, 1) and sum to 1. Let input be: input = torch.randn((3, 4, 5, ...
The easiest way I can think of to make you understand is: say you are given a tensor of shape (s1, s2, s3, s4) and as you mentioned you want to have the sum of all the entries along the last axis to be 1. sum = torch.sum(input, dim = 3) # input is of shape (s1, s2, s3, s4) Then you should call the softmax as: softm...
https://stackoverflow.com/questions/49036993/
Change Tanh activation in LSTM to ReLU
The default non-linear activation function in LSTM class is tanh. I wish to use ReLU for my project. Browsing through the documentation and other resources, I'm unable to find a way to do this in a simple manner. The only way I could find was to define my own custom LSTMCell, but here the author says that custom LSTMCe...
Custom LSTMCells don't support GPU acceleration capabilities - this statement probably means GPU acceleration capabilities become limited if you use LSTMCells. And definitely, you can write your own implementation of LSTM but you need to sacrifice runtime. For example, once I implemented an LSTM (based on linear layer...
https://stackoverflow.com/questions/49040180/
How could I feed a custom image into this model?
I've been following a course online and one of the exercises was to create a simple image detection model (using MNIST data) to detect written numbers. I've been trying to load a custom image I drew in (128x128 jpg) but I can't seem to figure it out. I'm really close, but I think I'm just confused about what parameters...
Simply convert your image to an 128x128 numpy array with values between 0 and 1. Then: image = Variable(torch.from_numpy(image))[None, :, :] classification = model(image) classification is then a pytorch Variable containing probabilities of belonging to each class.
https://stackoverflow.com/questions/49044980/
Implementing RNN and LSTM into DQN Pytorch code
I have some troubles finding some example on the great www to how i implement a recurrent neural network with LSTM layer into my current Deep q-network in Pytorch so it become a DRQN.. Bear with me i am just getting started.. Futhermore, I am NOT working with images processing, thereby CNN so do not worry about this. ...
From my point of view, I think you could add RNN, LSTM layer to the Network#__init__,Network#forward; shape of data should be reshaped into sequences... For more detail, I think you should read these two following articles; after that implementing RNN, LSTM not hard as it seem to be. http://pytorch.org/tutorials/begi...
https://stackoverflow.com/questions/49065222/
An analog of weighted_cross_entropy_with_logits in PyTorch
I'm trying to train a model with PyTorch. Is there any simple way to create a loss like weighted_cross_entropy_with_logits from Tensorflow? There are pos_weight argument in weighted_cross_entropy_with_logits that can help with balancing. But there are only weights for labels in the list of arguments in BCEWithLogitsLo...
You can write your own custom loss function as you want. For example, you can write: def weighted_cross_entropy_with_logits(logits, target, pos_weight): return targets * -logits.sigmoid().log() * pos_weight + (1 - targets) * -(1 - logits.sigmoid()).log() This is a basic implementation. You should...
https://stackoverflow.com/questions/49069502/
PyTorch: Testing with torchvision.datasets.ImageFolder and DataLoader
I'm a newbie trying to make this PyTorch CNN work with the Cats&Dogs dataset from kaggle. As there are no targets for the test images, I manually classified some of the test images and put the class in the filename, to be able to test (maybe should have just used some of the train images). I used the torchvision.d...
Looking at the data from Kaggle and your code, it seems that there are problems in your data loading, both train and test set. First of all, the data should be in a different folder per label for the default PyTorch ImageFolder to load it correctly. In your case, since all the training data is in the same folder, PyTor...
https://stackoverflow.com/questions/49073799/
Image Captioning Example input size of Decoder LSTM Pytorch
I'm new to Pytorch, there is a doubt that am having in the Image Captioning example code . In DcoderRNN class the lstm is defined as , self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True) in the forward function , embeddings = self.embed(captions) embeddings = torch.cat((features.unsqueeze(1...
You can analyze the shape of all input and output tensors and then it will become easier for you to understand what changes you need to make. Let's say: captions = B x S where S = sentence (caption) length. embeddings = self.embed(captions) Now, embeddings = B x S x E where E = embed_size. embeddings = torch.cat(...
https://stackoverflow.com/questions/49085370/
Is a torch.FloatTensor not a Tensor?
Although this example has no training, this is an adapted part of a larger program where training does occur. I simply want the generator network to spew out a random image in this case: import torch from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F from torchvision import trans...
Simply changing the second last line of your main function solves the problem: img_pil = transforms.ToPILImage()(img.squeeze()) img.squeeze() makes the tensor shape (1, 4, 300, 300) to (4, 300, 300).
https://stackoverflow.com/questions/49088670/
where is the definition of _cudnn_convolution_full_forward in pytorch
as the title mentioned, I want to find the definition of _cudnn_convolution_full_forward, but I search through all the project in pytorch and failed. And I cannot find and doc about this function. any one can help me?
All the cudnn convolution functions are defined here: https://github.com/pytorch/pytorch/blob/1848cad10802db9fa0aa066d9de195958120d863/aten/src/ATen/native/cudnn/Conv.cpp This function doesn't exist anymore in the latest versions of pytorch. The closest thing that there is there is cudnn_convolution_forward. In versio...
https://stackoverflow.com/questions/49103096/
Indexing on axis by list in PyTorch
I have Variables lengths_X of size (10L,) and A of size (10L, 16L, 5L). I want to use lengths_X to index along the second axis of A. In other words, I want to get a new tensor predicted_Y of size (10L, 5L) that indexes axis 1 at i for all entries with index i in axis 0. What is the best way to do this in PyTorch?
What you are looking for is actually called batched_index_select and I looked for such functionality before but couldn't find any native function in PyTorch that can do the job. But we can simply use: A = torch.randn(10, 16, 5) index = torch.from_numpy(numpy.random.randint(0, 16, size=10)) B = torch.stack([a[i] for a,...
https://stackoverflow.com/questions/49104307/
Issue training RNN model with pytorch with trivial goal
I'm trying to train a simple RNN model with a trivial goal where the output matches a fixed vector regardless of the input import torch import torch.nn as nn from torch.autograd import Variable import numpy as np class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, s...
Your fixed output is: torch.FloatTensor([[0.0, 1.0, 0.0]]) But you are using the following as the final layer in your RNN: self.softmax = nn.LogSoftmax(dim=1) Does LogSoftmax returns value in [0, 1]? Althouhgh, you can use the Softmax but I would recommend you to use the sign function and transform -1 to 0.
https://stackoverflow.com/questions/49115560/
how to apply gradients manually in pytorch
Starting to learn pytorch and was trying to do something very simple, trying to move a randomly initialized vector of size 5 to a target vector of value [1,2,3,4,5]. But my distance is not decreasing!! And my vector x just goes crazy. No idea what I am missing. import torch import numpy as np from torch.autograd im...
There are two errors in your code that prevents you from getting the desired results. The first error is that you should put the distance calculation in the loop. Because the distance is the loss in this case. So we have to monitor its change in each iteration. The second error is that you should manually zero out t...
https://stackoverflow.com/questions/49154514/
How to get around in place operation error if index leaf variable for gradient update?
I am encountering In place operation error when I am trying to index a leaf variable to update gradients with customized Shrink function. I cannot work around it. Any help is highly appreciated! import torch.nn as nn import torch import numpy as np from torch.autograd import Variable, Function # hyper parameters ba...
I just found: In order to update the variable, it needs to be ht.data[idx] instead of ht[idx]. We can use .data to access the tensor directly.
https://stackoverflow.com/questions/49161652/
Copying a PyTorch Variable to a Numpy array
Suppose I have a PyTorch Variable in GPU: var = Variable(torch.rand((100,100,100))).cuda() What's the best way to copy (not bridge) this variable to a NumPy array? var.clone().data.cpu().numpy() or var.data.cpu().numpy().copy() By running a quick benchmark, .clone() was slightly faster than .copy(). However, ...
This is a very interesting question. According to me, the question is little bit opinion-based and I would like to share my opinion on this. From the above two approaches, I would prefer the first one (use clone()). Since your goal is to copy information, essentially you need to invest extra memory. clone() and copy()...
https://stackoverflow.com/questions/49178967/
Check the total number of parameters in a PyTorch model
How do I count the total number of parameters in a PyTorch model? Something similar to model.count_params() in Keras.
PyTorch doesn't have a function to calculate the total number of parameters as Keras does, but it's possible to sum the number of elements for every parameter group: pytorch_total_params = sum(p.numel() for p in model.parameters()) If you want to calculate only the trainable parameters: pytorch_total_params = sum(p...
https://stackoverflow.com/questions/49201236/
How to use pack_padded_sequence with multiple variable-length input with the same label in pytorch
I have a model which takes three variable-length inputs with the same label. Is there a way I could use pack_padded_sequence somehow? If so, how should I sort my sequences? For example, a = (([0,1,2], [3,4], [5,6,7,8]), 1) # training data is in length 3,2,4; label is 1 b = (([0,1], [2], [6,7,8,9,10]), 1) Both a and...
Let's do it step by step. Input Data Processing a = (([0,1,2], [3,4], [5,6,7,8]), 1) # store length of each element in an array len_a = np.array([len(a) for a in a[0]]) variable_a = np.zeros((len(len_a), np.amax(len_a))) for i, a in enumerate(a[0]): variable_a[i, 0:len(a)] = a vocab_size = len(np.unique(v...
https://stackoverflow.com/questions/49203019/
pytorch error: multi-target not supported in CrossEntropyLoss()
I am on a project using acceleration data to predict some activities. But I have problems on the loss calculation. I am using CrossEntropyLoss for it. Data is used for it like below I use the first 4 data of each rows to predict the index like the last one of each rows. 1 84 84 81 4 81 85 85 80 1 81 82 84 80 1 1 85 ...
Ok. So I reproduced your problem and after some search and reading the API of CrossEntropyLoss(), I have found it's because you have a wrong label dimension. Offical docs of CrossEntropyLoss here. And you can see Input: (N,C) where C = number of classes Target: (N) where each value is 0≤targets[i]≤C−1 While he...
https://stackoverflow.com/questions/49206550/
Is there an efficient way to create a random bit mask in Pytorch?
I want to have a random bit mask that has some specified percent of 0s. The function I devised is: def create_mask(shape, rate): """ The idea is, you take a random permutations of numbers. You then mod then mod it by the [number of entries in the bitmask] / [percent of 0s you want]. The number of zeros...
For anyone running into this, this will create a bitmask with approximately 80% zero's directly on GPU. (PyTorch 0.3) torch.cuda.FloatTensor(10, 10).uniform_() > 0.8
https://stackoverflow.com/questions/49216615/
Difference between 1 LSTM with num_layers = 2 and 2 LSTMs in pytorch
I am new to deep learning and currently working on using LSTMs for language modeling. I was looking at the pytorch documentation and was confused by it. If I create a nn.LSTM(input_size, hidden_size, num_layers) where hidden_size = 4 and num_layers = 2, I think I will have an architecture something like: op0 ...
The multi-layer LSTM is better known as stacked LSTM where multiple layers of LSTM are stacked on top of each other. Your understanding is correct. The following two definitions of stacked LSTM are same. nn.LSTM(input_size, hidden_size, 2) and nn.Sequential(OrderedDict([ ('LSTM1', nn.LSTM(input_size, hidden_si...
https://stackoverflow.com/questions/49224413/
What is the difference between softmax and log-softmax?
The difference between these two functions that has been described in this pytorch post: What is the difference between log_softmax and softmax? is: exp(x_i) / exp(x).sum() and log softmax is: log(exp(x_i) / exp(x).sum()). But for the Pytorch code below why am I getting different output: >>> it = autograd.V...
By default, torch.log provides the natural logarithm of the input, so the output of PyTorch is correct: ln([0.5611,0.4389])=[-0.5778,-0.8236] Your last results are obtained using the logarithm with base 10.
https://stackoverflow.com/questions/49236571/
Pytorch beginner : tensor.new method
everyone, I have a small question. What is the purpose of the method tensor.new(..) in Pytorch, I didn't find anything in the documentation. It looks like it creates a new Tensor (like the name suggests), but why we don't just use torch.Tensor constructors instead of using this new method that requires an existing te...
As the documentation of tensor.new() says: Constructs a new tensor of the same data type as self tensor. Also note: For CUDA tensors, this method will create new tensor on the same device as this tensor.
https://stackoverflow.com/questions/49263588/
How does batching work in a seq2seq model in pytorch?
I am trying to implement a seq2seq model in Pytorch and I am having some problem with the batching. For example I have a batch of data whose dimensions are [batch_size, sequence_lengths, encoding_dimension] where the sequence lengths are different for each example in the batch. Now, I managed to do the encodin...
You are not missing anything. I can help you since I have worked on several sequence-to-sequence application using PyTorch. I am giving you a simple example below. class Seq2Seq(nn.Module): """A Seq2seq network trained on predicting the next query.""" def __init__(self, dictionary, embedding_index, args): ...
https://stackoverflow.com/questions/49283435/
Tying weights in neural machine translation
I want to tie weights of the embedding layer and the next_word prediction layer of the decoder. The embedding dimension is set to 300 and the hidden size of the decoder is set to 600. Vocabulary size of the target language in NMT is 50000, so embedding weight dimension is 50000 x 300 and weight of the linear layer whic...
You could use linear layer to project the 600 dimensional space down to 300 before you apply the shared projection. This way you still get the advantage that the entire embedding (possibly) has a non-zero gradient for each mini-batch but at the risk of increasing the capacity of the network slightly.
https://stackoverflow.com/questions/49299609/