instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Outer sum, etc. in pytorch
Numpy offers optimized outer operations for any RxR -> R function, like np.multiply.outer or np.subtract.outer, with the behaviour: >>> np.subtract.outer([6, 5, 4], [3, 2, 1]) array([[3, 4, 5], [2, 3, 4], [1, 2, 3]]) Pytorch does not seem to offer such a feature (or I have missed it). What...
Per the documenation: Many PyTorch operations support NumPy Broadcasting Semantics. An outer subtraction is a broadcasted subtraction from a 2d array to a 1d array, so essentially you can reshape the first array to (3, 1) and then subtract the second array from it: x = torch.Tensor([6, 5, 4]) y = torch.Tensor([3...
https://stackoverflow.com/questions/52780559/
MemoryError when attempting to create a docker image with Torch/PyTorch
I am following this tutorial to create a Docker image for a flask application. The application depends on Torch/PyTorch. As such, my requirements.txt file looks like the following. flask flask-cors pytorch torchvision pandas My Dockerfile then looks like the following. FROM ubuntu:latest LABEL My Company "info@my...
If anyone is interested, I was able to get PyTorch installed into a docker container as follows. I modified the requirements.txt to look like the following. flask flask-cors pandas I then modified Dockerfile to look like the following. It's quirky and does not follow the conventional way of install Python packages ...
https://stackoverflow.com/questions/52782864/
Odd behaviour of "out" argument in torch.empty()
I have a sample tensor like this: In [137]: x = x.new_ones((5, 3), dtype=torch.double) In [138]: x Out[138]: tensor([[1., 1., 1.], [1., 1., 1.], [1., 1., 1.], [1., 1., 1.], [1., 1., 1.]], dtype=torch.float64) Now, I want to free the memory of this tensor by overwriting the conten...
Here's the C++ implementation of empty with an out param from the source code. Tensor& empty_out(Tensor& result, IntList size) { if (result.is_sparse()) { result.sparse_resize_and_clear_(size, size.size(), 0); } else { result.resize_(size); } return result; } So for dense tensors all it does...
https://stackoverflow.com/questions/52789086/
Setting custom kernel for CNN in pytorch
Is there a way to specify our own custom kernel values for a convolution neural network in pytorch? Something like kernel_initialiser in tensorflow? Eg. I want a 3x3 kernel in nn.Conv2d with initialization so that it acts as a identity kernel - 0 0 0 0 1 0 0 0 0 (this will effectively return the same output as my i...
Thanks to ptrblck I was able to solve it. I can define a new convolution layer as conv and as per the example I can set the identity kernel using - weights = ch.Tensor([[0, 0, 0], [0, 1, 0], [0, 0, 0]]).unsqueeze(0).unsqueeze(0) weights.requires_grad = True conv = nn.Conv2d(1, 1, kernel_size=3, stride=1, padding=1,...
https://stackoverflow.com/questions/52790775/
How to get the output from a specific layer from a PyTorch model?
How to extract the features from a specific layer from a pre-trained PyTorch model (such as ResNet or VGG), without doing a forward pass again?
New answer Edit: there's a new feature in torchvision v0.11.0 that allows extracting features. For example, if you wanna extract features from the layer layer4.2.relu_2, you can do like: import torch from torchvision.models import resnet50 from torchvision.models.feature_extraction import create_feature_extractor x = ...
https://stackoverflow.com/questions/52796121/
How to save and use a trained neural network developed in PyTorch / TensorFlow / Keras?
Are there ways to save a model after training and sharing just the model with others? Like a regular script? Since the network is a collection of float matrices, is it possible to just extract these trained weights and run it on new data to make predictions, instead of requiring the users to install these frameworks to...
PyTorch: As explained in this post, you can save a model's parameters as a dictionary, or load a dictionary to set your model's parameters. You can also save/load a PyTorch model as an object. Both procedures require the user to have at least one tensor computation framework installed, e.g. for efficient matrix multip...
https://stackoverflow.com/questions/52796629/
TypeError: cannot unpack non-iterable int object
Im trying to make my first CNN using pyTorch and am following online help and code already people wrote. i am trying to reproduce their results. I'm using the Kaggle Dogs Breed Dataset for this and below is the error I get. The trainloader does not return my images and labels and any attempt to get them leads in an err...
It seems like you are using torchvision's image transforms. Some of these transforms are expecting as input a PIL.Image object, rather than a tensor or numpy array. You are using io.imread to read ths image file, and I suspect this io is not PIL.Image resulting with a numpy array. Make sure you pass PIL.Image objects t...
https://stackoverflow.com/questions/52815264/
Order of CUDA devices
I saw this solution, but it doesn't quite answer my question; it's also quite old so I'm not sure how relevant it is. I keep getting conflicting outputs for the order of GPU units. There are two of them: Tesla K40 and NVS315 (legacy device that is never used). When I run deviceQuery, I get Device 0: "Tesla K40m" .....
By default, CUDA orders the GPUs by computing power. GPU:0 will be the fastest GPU on your host, in your case the K40m. If you set CUDA_DEVICE_ORDER='PCI_BUS_ID' then CUDA orders your GPU depending on how you set up your machine meaning that GPU:0 will be the GPU on your first PCI-E lane. Both Tensorflow and PyTorch...
https://stackoverflow.com/questions/52815708/
AttributeError: 'Tensor' has no attribute: 'backwards'
I'm posting this question for those who made the same error I did. I got this error when trying to compute my gradients: criterion = torch.nn.CrossEntropyLoss() loss = criterion(y_hat, y_truth) loss.backwards()
It's loss.backward(), not loss.backwards().
https://stackoverflow.com/questions/52817105/
Why pytorch DataLoader behaves differently on numpy array and list?
The only difference is one of the parameter passed to DataLoader is in type "numpy.array" and the other is in type "list", but the DataLoader gives totally different results. You can use the following code to reproduce it: from torch.utils.data import DataLoader,Dataset import numpy as np class my_dataset(Dataset): ...
This is because how batching is handled in torch.utils.data.DataLoader. collate_fn argument decides how samples from samples are merged into a single batch. Default for this argument is undocumented torch.utils.data.default_collate. This function handles batching by assuming numbers/tensors/ndarrays are primitive data...
https://stackoverflow.com/questions/52818145/
Multi label classification in pytorch
I have a multi-label classification problem. I have 11 classes, around 4k examples. Each example can have from 1 to 4-5 label. At the moment, i'm training a classifier separately for each class with log_loss. As you can expect, it is taking quite some time to train 11 classifier, and i would like to try another approac...
You are looking for torch.nn.BCELoss. Here's example code: import torch batch_size = 2 num_classes = 11 loss_fn = torch.nn.BCELoss() outputs_before_sigmoid = torch.randn(batch_size, num_classes) sigmoid_outputs = torch.sigmoid(outputs_before_sigmoid) target_classes = torch.randint(0, 2, (batch_size, num_classes)) #...
https://stackoverflow.com/questions/52855843/
Module not found in pycharm (Windows)
I wanted to install Pytorch via anaconda and it worked but PyCharm can't find the module ( ModuleNotFoundError: No module named 'torch' I also have CUDA installed but when I looked up to add a the package with pycharm it also gives an error. When I added the anaconda interpreter I can't run the code. I use Python...
Ok I solved this problem: First install anaconda and open the prompt then type conda install pytorch -c pytorch and pip3 install torchvision. Then go to PyCharm and create an Project and set the Project Interpreter to the Anaconda one (there is in the path: \Anaconda.x.x\python.exe ). Then you go to the Run settings an...
https://stackoverflow.com/questions/52856441/
Recurrent network (RNN) won't learn a very simple function (plots shown in the question)
So I am trying to train a simple recurrent network to detect a "burst" in an input signal. The following figure shows the input signal (blue) and the desired (classification) output of the RNN, shown in red. So the output of the network should switch from 1 to 0 whenever the burst is detected and stay like with tha...
From the documentation of tourch.nn.RNN, the RNN is actually an Elman network, and have the following properties seen here. The output of an Elman network is only dependent on the hidden state, while the hidden state is dependent on the last input and the previous hidden state. Since we have set “h_state = h_state.dat...
https://stackoverflow.com/questions/52857213/
What does the underscore suffix in PyTorch functions mean?
In PyTorch, many methods of a tensor exist in two versions - one with a underscore suffix, and one without. If I try them out, they seem to do the same thing: In [1]: import torch In [2]: a = torch.tensor([2, 4, 6]) In [3]: a.add(10) Out[3]: tensor([12, 14, 16]) In [4]: a.add_(10) Out[4]: tensor([12, 14, 16]) Wha...
You have already answered your own question that the underscore indicates in-place operations in PyTorch. However I want to point out briefly why in-place operations can be problematic: First of all on the PyTorch sites it is recommended to not use in-place operations in most cases. Unless working under heavy memory ...
https://stackoverflow.com/questions/52920098/
pytorch modify array with list of indices
Suppose I have a list of indices and wish to modify an existing array with this list. Currently the only way I can do this is by using a for loop as follows. Just wondering if there is a faster/ efficient way. torch.manual_seed(0) a = torch.randn(5,3) idx = torch.Tensor([[1,2], [3,2]], dtype=torch.long) for i,j in idx...
It's quite simple a[idx[:,0], idx[:,1]] = 1 You can find a more general solution in this thread.
https://stackoverflow.com/questions/52922401/
RuntimeError: "exp" not implemented for 'torch.LongTensor'
I am following this tutorial: http://nlp.seas.harvard.edu/2018/04/03/attention.html to implement the Transformer model from the "Attention Is All You Need" paper. However I am getting the following error : RuntimeError: "exp" not implemented for 'torch.LongTensor' This is the line, in the PositionalEnconding class,...
I happened to follow this tutorial too. For me I just got the torch.arange to generate float type tensor from position = torch.arange(0, max_len).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2) * -(math.log(10000.0) / d_model)) to position = torch.arange(0., max_len).unsqueeze(1) div_term = torch....
https://stackoverflow.com/questions/52922445/
pytorch how to compute grad after clone a tensor
My simple code: import torch x = torch.randn(4, requires_grad=True).cuda() y = torch.randn(4, requires_grad=True).cuda() z = torch.zeros(4) z = torch.clone(x) z.retain_grad() h = (z + y) * z l = torch.randn(4).cuda() loss = (l - h).pow(2).sum() loss.backward() print('x.grad=', x.grad) print('z.grad=', z.grad) outpu...
You need to call x.retain_grad() after declaring x if you want to keep the grad of tensor x.
https://stackoverflow.com/questions/52926847/
PyTorch: manually setting weight parameters with numpy array for GRU / LSTM
I'm trying to fill up GRU/LSTM with manually defined parameters in pytorch. I have numpy arrays for parameters with shapes as defined in their documentation (https://pytorch.org/docs/stable/nn.html#torch.nn.GRU). It seems to work but I'm not sure whether the returned values are correct. Is this a right way to fill u...
That is a good question, and you already give a decent answer. However, it reinvents the wheel - there is a very elegant Pytorch internal routine that will allow you to do the same without as much effort - and one that is applicable for any network. The core concept here is PyTorch's state_dict. The state dictionary ...
https://stackoverflow.com/questions/52945427/
Pytorch (0.4.1) can not find GPU (Nvidia V100)
I have installed Pytorch(0.4.1) with CUDA 9.0 via anaconda. I also have installed Nvidia driver (390.30). Through nvidia-smi, I can see all GPUs(V100) with their situation. But I always get False when calling torch.cuda.is_avaliable(). I also tried to downgrade the CUDA version from 9.0 to 8.0, but the situation was ju...
It seems that it's a Nvidia container issue. After downgrading the Nvidia container from 18.08 to 18.07, all code runs well.
https://stackoverflow.com/questions/52946435/
Bool value of Tensor with more than one value is ambiguous in Pytorch
I want to create a model in pytorch, but I can't compute the loss. It's always return Bool value of Tensor with more than one value is ambiguous Actually, I run example code, it work. loss = CrossEntropyLoss() input = torch.randn(8, 5) input target = torch.empty(8,dtype=torch.long).random_(5) target output = loss(i...
In your minimal example, you create an object "loss" of the class "CrossEntropyLoss". This object is able to compute your loss as loss(input, target) However, in your actual code, you try to create the object "Loss", while passing Pip and the labels to the "CrossEntropyLoss" cla...
https://stackoverflow.com/questions/52946920/
Pytorch: Getting the correct dimensions for final layer
Pytorch newbie here! I am trying to fine-tune a VGG16 model to predict 3 different classes. Part of my work involves converting FC layers to CONV layers. However, the values of my predictions don't fall between 0 to 2 (the 3 classes). Can someone point me to a good resource on how to compute the correct dimensions fo...
I wrote a function that takes a Pytorch model as input and converts the classification layer to convolution layer. It works for VGG and Alexnet for now, but you can extend it for other models as well. import torch import torch.nn as nn from torchvision.models import alexnet, vgg16 def convolutionize(model, num_classe...
https://stackoverflow.com/questions/52963909/
What are the default values of kernel size and padding in pytorch?
For an instance, take this piece of code : conv = conv2d(in_channels = 3, out_channels = 64) What can I expect the padding and kernel size to be, by default?
class torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True) So to answer your question, by default padding=0, there is no default value for kernel_size. If you leave it empty, you will get an error
https://stackoverflow.com/questions/52964395/
Padding in Pytorch
In PyTorch tensor, I would like to obtain the output from the input as follows: How can I achieve this padding in Pytroch?
One way of doing this is def my_odd_padding(list_of_2d_tensors, pad_value): # get the sizes of the matrices hs = [t_.shape[0] for t_ in list_of_2d_tensors] ws = [t_.shape[1] for t_ in list_of_2d_tensors] # allocate space for output result = torch.zeros(sum(hs), sum(ws)) result.add_(pad_value) fh = 0 fw...
https://stackoverflow.com/questions/52964807/
How to make cuda unavailable in pytorch
i'm running some code with cudas, and I need to test the same code on CPU to compare running time. To decide between regular pytorch tensor and cuda float tensor, the library I use calls torch.cuda.is_available(). Is there an easy method to make this function return false? I tried changing the Cuda visible devices with...
my code Instead of trying to trick it, why not rewrite your code? For example, use_gpu = torch.cuda.is_available() and not os.environ['USE_CPU'] Then you can start your program as python runme.py to run on GPU if available, and USE_CPU=1 python3 runme.py to force CPU execution (or make it semi-permanent by expo...
https://stackoverflow.com/questions/52965474/
usage about rnn.pack_padded_sequence
When I use torch.nn.utils.rnn.pack_padded_sequence(), an error occurred. Here is my code: import torch import numpy as np x = torch.from_numpy(np.array([[1,2,3,4,5,6,0,0],[6,7,8,9,0,0,0,0],[12,83,84,0,0,0,0,0]])) length =[6,4,3] print(torch.nn.utils.rnn.pack_padded_sequence(input=x, lengths=length, batch_first=True)) ...
So the reason for this sounds incredibly stupid, but I think it is due to the way how the wrapper/low-level translator function operates on PyTorch functions: From what I understand about the *args, **kwargs decorators of python (see more here, the problem is that you only have ordered arguments if you pass them witho...
https://stackoverflow.com/questions/52969995/
Comparing Conv2D with padding between Tensorflow and PyTorch
I am trying to import weights saved from a Tensorflow model to PyTorch. So far the results have been very similar. I ran into a snag when the model calls for conv2d with stride=2. To verify the mismatch, I set up a very simple comparison between TF and PyTorch. First, I compare conv2d with stride=1. import tensorflow...
To replicate the behavior, padding sizes are calculated as described in the Tensorflow documentation. Here, I test the padding behavior by setting stride=2 and padding the PyTorch input. import tensorflow as tf import numpy as np import torch import torch.nn.functional as F np.random.seed(0) sess = tf.Session() # C...
https://stackoverflow.com/questions/52975843/
PyTorch: create non-fully-connected layer / concatenate output of hidden layers
In PyTorch, I want to create a hidden layer whose neurons are not fully connected to the output layer. I try to concatenate the output of two linear layers but run into the following error: RuntimeError: size mismatch, m1: [2 x 2], m2: [4 x 4] my current code: class NeuralNet2(nn.Module): def __init__(self):...
It turned out to be a simple comprehension problem with the concatenation function. Changing x = torch.cat((xLeft, xRight)) to x = torch.cat((xLeft, xRight), dim=1) did the trick. Thanks @dennlinger
https://stackoverflow.com/questions/52994435/
Bidirectional LSTM output question in PyTorch
Hi I have a question about how to collect the correct result from a BI-LSTM module’s output. Suppose I have a 10-length sequence feeding into a single-layer LSTM module with 100 hidden units: lstm = nn.LSTM(5, 100, 1, bidirectional=True) output will be of shape: [10 (seq_length), 1 (batch), 200 (num_directions * ...
Yes, when using a BiLSTM the hidden states of the directions are just concatenated (the second part after the middle is the hidden state for feeding in the reversed sequence). So splitting up in the middle works just fine. As reshaping works from the right to the left dimensions you won't have any problems in separat...
https://stackoverflow.com/questions/53010465/
AttributeError: 'tuple' object has no attribute 'dim', when feeding input to Pytorch LSTM network
I am trying to run the following code: import matplotlib.pylab as plt import numpy as np import torch import torch.nn as nn class LSTM(nn.Module): def __init__(self, input_shape, n_actions): super(LSTM, self).__init__() self.lstm = nn.LSTM(input_shape, 12) self.hidden2tag = nn.Linear(12, ...
The pytorch LSTM returns a tuple. So you get this error as your linear layer self.hidden2tag can not handle this tuple. So change: out = self.lstm(x) to out, states = self.lstm(x) This will fix your error, by splitting up the tuple so that out is just your output tensor. out then stores the hidden states, while...
https://stackoverflow.com/questions/53032586/
How to create a torchtext.data.TabularDataset directly from a list or dict
torchtext.data.TabularDataset can be created from a TSV/JSON/CSV file and then it can be used for building the vocabulary from Glove, FastText or any other embeddings. But my requirement is to create a torchtext.data.TabularDataset directly, either from a list or a dict. Current implementation of the code by reading ...
It required me to write an own class inheriting the Dataset class and with few modifications in torchtext.data.TabularDataset class. class TabularDataset_From_List(data.Dataset): def __init__(self, input_list, format, fields, skip_header=False, **kwargs): make_example = { 'json': Example.fromJ...
https://stackoverflow.com/questions/53046583/
Modifying a pytorch tensor and then getting the gradient lets the gradient not work
I am a beginner in pytorch and I face the following issue: When I get the gradient of the below tensor (note that I use some variable x in some way as you can see below), I get the gradient: import torch myTensor = torch.randn(2, 2,requires_grad=True) with torch.enable_grad(): x=myTensor.sum() *10 x.backward() p...
The problem here is that this line represents an in-place operation: myTensor[0,0]*=5 And PyTorch or more precisely autograd is not very good in handling in-place operations, especially on those tensors with the requires_grad flag set to True. You can also take a look here: https://pytorch.org/docs/stable/notes/aut...
https://stackoverflow.com/questions/53051913/
Why does Pytorch expect a DoubleTensor instead of a FloatTensor?
From everything I see online, FloatTensors are Pytorch's default for everything, and when I create a tensor to pass to my generator module it is a FloatTensor, but when I try to run it through a linear layer it complains that it wants a DoubleTensor. class Generator(nn.Module): def __init__(self): super(Generat...
The Problem here is that your numpy input uses double as data type the same data type is also applied on the resulting tensor. The weights of your layer self.fully_connected on the other hand are float. When feeding data trough the layer a matrix multiplication is applied and this multiplication requires both matrice...
https://stackoverflow.com/questions/53055101/
what is the tensorflow equivalent for pytorch probability function: torch.bernoulli?
In Pytorch, you can do following: x = torch.bernoulli(my_data) Any similar functionality in tensorflow? Can the input be 2-D tensor, such as (batch, len)? I tried tensorflow.contrib.distributions.Bernoulli: import numpy as np tmp_x1 = np.random.rand(20,5) new_data_2 = tf.convert_to_tensor(tmp_x1) from tensorflow.cont...
It seems tf.distributions.Bernoulli does what you need. The input can be an N-D tensor, which includes a 2D tensor. EDIT: example use After your comment, I tried the following, which worked for me (using tensorflow 1.11): import numpy as np import tensorflow import tensorflow as tf from tensorflow.distributions imp...
https://stackoverflow.com/questions/53090781/
Pytorch: Modifying VGG16 Architecture
I'm currently trying to modify the VGG16 network architecture so that it's able to accept 400x400 px images. Based on literature that I've read, the way to do it would be to covert the fully connected (FC) layers into convolutional (CONV) layers. This would essentially " allow the network to efficiently “slide” acros...
How to convert VGG to except input size of 400 x 400 ? First Approach The problem with VGG style architecture is we are hardcoding the number of input & output features in our Linear Layers. i.e vgg.classifier[0]: Linear(in_features=25088, out_features=4096, bias=True) It is expecting 25,088 input feature...
https://stackoverflow.com/questions/53114882/
Set higher shared memory to avoid RuntimeError with PyTorch on Google Colab
Using pytorch 1.0 Preview with fastai v1.0 in Colab. I often get RuntimeError: DataLoader worker (pid 13) is killed by signal: Bus error. for more memory intensive tasks (nothing huge). Looks like a shared memory issue: https://github.com/pytorch/pytorch/issues/5040#issue-294274594 Fix looks like it is to change sh...
It's not possible to modify this setting in colab, but the default was raised to fix this issue already so you should not need to change the setting further: https://github.com/googlecolab/colabtools/issues/329
https://stackoverflow.com/questions/53122005/
How to learn the embeddings in Pytorch and retrieve it later
I am building a recommendation system where I predict the best item for each user given their purchase history of items. I have userIDs and itemIDs and how much itemID was purchased by userID. I have Millions of users and thousands of products. Not all products are purchased(there are some products that no one has boug...
model.parameters() returns all the parameters of your model, including the embeddings. So all these parameters of your model are handed over to the optimizer (line below) and will be trained later when calling optimizer.step() - so yes your embeddings are trained along with all other parameters of the network.(you ca...
https://stackoverflow.com/questions/53124809/
Error while running Convolutional Autoencoder RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
I am a noob and am creating a model in PyTorch for the first time. I am trying to create a convolutional autoencoder and am getting the error while running the model. The code I am using is: class MyDataset(Dataset): def __init__(self, image_paths, target_paths, train=True): self.image_paths = image_paths ...
I cannot test your model, but considering the error message it makes sense the cause of your problem lies in the return value of your forward. Currently you are returning x which is your actual input not the output: def forward(self, x): x1 = self.encoder_block1(x) y1 = self.decoder_block1(x1) y0 = self....
https://stackoverflow.com/questions/53128752/
coverting roi pooling in pytorch to nn layer
I have a an mlmodel using ROI pooling for which I am using this (adapted from here) (non NN layer version) def forward(self, features, rois): batch_size, num_channels, data_height, data_width = features.size() num_rois = rois.size()[0] outputs = Variable(torch.zeros(num_rois, num_channels, se...
Found the issue - The rois after multiplication with spatial scale were being rounded down and had to call round function before calling long like so rois = rois.data.float() num_rois = rois.size(0) rois[:,1:].mul_(self.spatial_scale) rois = rois.round().long() ## Check this here !! Hope this helps someone!
https://stackoverflow.com/questions/53157978/
pytorch freeze weights and update param_groups
Freezing weights in pytorch for param_groups setting. So if one wants to freeze weights during training: for param in child.parameters(): param.requires_grad = False the optimizer also has to be updated to not include the non gradient weights: optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, mode...
Actually I think you don't have to update the optimizer. The Parameters handed over to the optimizer are just references. So when you change the requires_grad flag it will immediately be updated. But even if that would for some reason not be the case - as soon as you you set the requires_grad flag to be False you ca...
https://stackoverflow.com/questions/53159427/
PyTorch is installed but not imported
I am trying to build PyTorch. Reference site:https://github.com/hughperkins/pytorch but, When we performed unit test, The following error occur. ImportError while importing test module '/home/usr2/pytorch/test/testByteTensor.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: test/test...
In fact, you should do import torch instead of import PyTorch Here is what's work for me: (I installed it using conda) >>> import torch >>> torch.version >>> <module 'torch.version' from '/home/koke_cacao/miniconda3/envs/ml/lib/python3.6/site-packages/torch/version.py'> >>> ...
https://stackoverflow.com/questions/53165990/
Question about terminology used in LSTM inputs - seq_length vs context_size for sliding window approach
I have time series of a sequence of n vectors that I need to feed to a LSTM with a sliding window approach. In different resources that I read online, seq_length is often referred to as the window length [or the number of LSTM cells] and context_size is defined as the input size to LSTM at a timestep. (for eg. one in...
LSTM by default recurses on data, in that the prediction at time t will depend on all of the past(depending on memory). In this case it seems like you want input at time t to depend on m+1 instances into the past. You do not need a recurrent net if so, you can simple use linear and feed in the sliding window at each in...
https://stackoverflow.com/questions/53179255/
RuntimeError: Attempting to deserialize object on CUDA device 2 but torch.cuda.device_count() is 1
I've got a snippet of python code for training a model. The problem is that after running: loaded_state = torch.load(model_path+seq_to_seq_test_model_fname) to load a pretrained model,I'm getting: Traceback (most recent call last): File "img_to_text.py", line 480, in <module> main() File "img_to_te...
I just figured it out: loaded_state = torch.load(model_path+seq_to_seq_test_model_fname,map_location='cuda:0') is the solution
https://stackoverflow.com/questions/53186736/
Pytorch passing PackSequence argument to LSTM
As per my understanding, pack_sequence and pack_padded_sequence returns a PackedSequence, for which its data attribute should always be 1 dimension. However, the following code gives the error: RuntimeError: input must have 2 dimensions, got 1. import torch import torch.nn.utils.rnn as rnn_utils a = torch.Tensor([1, ...
There are a few things wrong with your code. Input size should be 1 LSTM takes a vector at each time step, you are passing scalars and hence the dimension error. Below code should fix the problem. I made each input a (1,) size array and changed input size to 1. import torch import torch.nn.utils.rnn as rnn_uti...
https://stackoverflow.com/questions/53197659/
Calling cuda() with async results in SyntaxError
I'm trying to run this PyTorch code: for i, (input, target) in enumerate(train_loader): input = input.float().cuda(async=True) target = target.cuda(async=True) input_var = torch.autograd.Variable(input) target_var = torch.autograd.Variable(target) output = model(input_var) But when I try I am g...
Your code does not work because: async is a reserved keyword in python which cannot be used in that way, that is why you get the SyntaxError cuda() no longer has an argument async. The constructor looks like this: cuda(device=None, non_blocking=False) → Tensor Previously there was an argument async but this repl...
https://stackoverflow.com/questions/53201534/
torch.Tensor() with requires_grad parameter
I can't use torch.Tensor() with requires_grad parameter (torch version : 0.4.1) without requires_grad : x = torch.Tensor([[.5, .3, 2.1]]) print(x) > tensor([[0.5000, 0.3000, 2.1000]]) with requires_grad=True or requires_grad=False : x = torch.Tensor([[.5, .3, 2.1]], requires_grad=False) print(x) Traceback (most...
You are creating the tensor x by using the torch.Tensor class constructor which doesn't take the requires_grad flag. Instead, you want to use torch.tensor() (lowercase 't') method x = torch.tensor([[.5, .3, 2.1]], requires_grad=False) Edit: adding a link to docs: torch.Tensor
https://stackoverflow.com/questions/53201921/
is there any difference between matmul and usual multiplication of tensors
I am confused between the multiplication between two tensors using * and matmul. Below is my code import torch torch.manual_seed(7) features = torch.randn((2, 5)) weights = torch.randn_like(features) here, i want to multiply weights and features. so, one way to do it is as follows print(torch.sum(features * weights...
When you use *, the multiplication is elementwise, when you use torch.mm it is matrix multiplication. Example: a = torch.rand(2,5) b = torch.rand(2,5) result = a*b result will be shaped the same as a or b i.e (2,5) whereas considering operation result = torch.mm(a,b) It will give a size mismatch error, as this...
https://stackoverflow.com/questions/53202440/
How to efficiently retrieve the indices of maximum values in a Torch tensor?
Assume to have a torch tensor, for example of the following shape: x = torch.rand(20, 1, 120, 120) What I would like now, is to get the indices of the maximum values of each 120x120 matrix. To simplify the problem I would first x.squeeze() to work with shape [20, 120, 120]. I would then like to get torch tensor whic...
If I get you correctly you don't want the values, but the indices. Unfortunately there is no out of the box solution. There exists an argmax() function, but I cannot see how to get it to do exactly what you want. So here is a small workaround, the efficiency should also be okay since we're just dividing tensors: n = ...
https://stackoverflow.com/questions/53212507/
Pytorch - Getting gradient for intermediate variables / tensors
As an exercice in pytorch framework (0.4.1) , I am trying to display the gradient of X (gX or dSdX) in a simple Linear layer (Z = X.W + B). To simplify my toy example, I backward() from a sum of Z (not a loss). To sum up, I want gX(dSdX) of S=sum(XW+B). The problem is that the gradient of Z (dSdZ) is None. As a resul...
First of all you only calculate gradients for tensors where you enable the gradient by setting the requires_grad to True. So your output is just as one would expect. You get the gradient for X. PyTorch does not save gradients of intermediate results for performance reasons. So you will just get the gradient for those...
https://stackoverflow.com/questions/53219600/
Two-Layer Neural Network in PyTorch does not Converge
Problem I am trying to implement 2-layer neural network using different methods (TensorFlow, PyTorch and from scratch) and then compare their performance based on MNIST dataset. I am not sure what mistakes I have made, but the accuracy in PyTorch is only about 10%, which is basically random guess. I think probably th...
The problem here is that you don't apply your fully connected layers fc1 and fc2. Your forward() currently looks like: def forward(self, x): # x -> (batch_size, 784) x = torch.relu(x) # x -> (batch_size, 10) x = torch.softmax(x, dim=1) return x So if you change it to: def forward(self, x)...
https://stackoverflow.com/questions/53235440/
How to tell PyTorch to not use the GPU?
I want to do some timing comparisons between CPU & GPU as well as some profiling and would like to know if there's a way to tell pytorch to not use the GPU and instead use the CPU only? I realize I could install another CPU-only pytorch, but hoping there's an easier way.
Before running your code, run this shell command to tell torch that there are no GPUs: export CUDA_VISIBLE_DEVICES="" This will tell it to use only one GPU (the one with id 0) and so on: export CUDA_VISIBLE_DEVICES="0"
https://stackoverflow.com/questions/53266350/
Pytorch. Can autograd be used when the final tensor has more than a single value in it?
Can autograd be used when the final tensor has more than a single value in it? I tried the following. x = torch.tensor([4.0, 5.0], requires_grad=True) y = x ** 2 print(y) y.backward() Throws an error RuntimeError: grad can be implicitly created only for scalar outputs The following however works. x = torch.t...
See https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html#gradients y.backward() is same as y.backward(torch.tensor(1.0)) Usually, the output is scalar and hence the scalar is passed to backward as a default choice. However, since your output is two dimensional you should call y.backward(torch.tensor([1...
https://stackoverflow.com/questions/53273662/
PyTorch gradient differs from manually calculated gradient
I'm trying to compute the gradient of 1/x without using Pytorch's autograd. I use the formula grad(1/x, x) = -1/x**2. When I compare my result with this formula to the gradient given by Pytorch's autograd, they're different. Here is my code: a = torch.tensor(np.random.randn(), dtype=dtype, requires_grad=True) loss = ...
So I guess you expect zero as result. When you take a closer look you see that it is quite close. When deviding numbers on a binary system (computer) then you often get round-off errors. Lets take a look at your example with an additional print-statement added: a = torch.tensor(np.random.randn(), requires_grad=True) lo...
https://stackoverflow.com/questions/53274587/
Initialize weights and bias in torch
What is the equivalent command for the below keras code in Pytorch Dense(64, kernel_initializer='he_normal', bias_initializer='zeros', name='uhat_digitcaps')(d5) How to I initialize weights and bias? Thanks!
class Net(nn.Module): def __init__(self, in_channels, out_channels): self.linear = nn.Linear(in_channels, 64) nn.init.kaiming_normal_(self.linear.weight, mode='fan_out') nn.init.constant_(self.linear.bias, 0)
https://stackoverflow.com/questions/53278845/
PyTorch next(iter(training_loader)) extremely slow, simple data, can't num_workers?
Here x_dat and y_dat are just really long 1-dimensional tensors. class FunctionDataset(Dataset): def __init__(self): x_dat, y_dat = data_product() self.length = len(x_dat) self.y_dat = y_dat self.x_dat = x_dat def __getitem__(self, index): sample = self.x_dat[index] ...
When retrieving a batch with x, y = next(iter(training_loader)) you actually create a new instance of dataloader iterator at each call (!) See this thread for more infotrmation. What you should do instead is create the iterator once (per epoch): training_loader_iter = iter(training_loader) and then call next for ...
https://stackoverflow.com/questions/53280967/
Confusion matrix and test accuracy for PyTorch Transfer Learning tutorial
Following the Pytorch Transfer learning tutorial, I am interested in reporting only train and test accuracy as well as confusion matrix (say using sklearn confusionmatrix). How can I do that? The current tutorial only reports train/val accuracy and I am having hard time figuring how to incorporate the sklearn confusion...
Answer given by ptrblck of PyTorch community. Thanks a lot! nb_classes = 9 confusion_matrix = torch.zeros(nb_classes, nb_classes) with torch.no_grad(): for i, (inputs, classes) in enumerate(dataloaders['val']): inputs = inputs.to(device) classes = classes.to(device) outputs = model_ft(in...
https://stackoverflow.com/questions/53290306/
Does it differ to use optimizer.step or model.step in pytorch?
In pytorch, to update the model, should I use optimizer.step() or model.step() ? Here is a example snippet: import torch import torch nn class SomeNeuralNet(nn.Module): def __init__(self,hs,es,dropout): SomeNeuralNet(ClaimRecognizer, self).__init__() # Some initialization here def forward(...
To make the gradient descent step, you normally use just optimizer.step(). Here is also an example taken from the documentation (same link at bottom), what it looks like in general: for input, target in dataset: optimizer.zero_grad() output = model(input) loss = loss_fn(output, target) loss.backward() ...
https://stackoverflow.com/questions/53302713/
Using pre-trained word embeddings - how to create vector for unknown / OOV Token?
I wan't to add pre-trained embeddings to a model. But as it seems there is no out-of-vocabulary (OOV) token resp. no vector for unseen words existent. So what can I do to handle OOV-tokens I come across? I have some ideas, but none of them seem to be very good: I could just create a random vector for this token, bu...
There are multiple ways you can deal with it. I don't think I can cite references about which works better. Non-trainable option: Random vector as embedding You can use an all-zero vector for OOV. You can use the mean of all the embedding vectors, that way you avoid the risk of being away from the actual distribution....
https://stackoverflow.com/questions/53316174/
Pytorch 0.4: Should the requires_grad flag of the network input be set to True during training?
The requires_grad flag of input is default False during my last training. I was wondering if I should set it to True.
So generally: For all tensors / weights that you want to be trained the requires_grad flag has to be True. This would be the case for your parameters resp. weights and biases. So there you want the flag to be True. But this is already default value for predefined modules like nn.Linear, nn.Embedding. nn.Conv2d etc. ...
https://stackoverflow.com/questions/53317618/
Pytorch 0.4.0: There are three ways to create tensors on CUDA device. Is there some difference between them?
I failed in the third way. t3 is still on CPU. No idea why. a = np.random.randn(1, 1, 2, 3) t1 = torch.tensor(a) t1 = t3.to(torch.device('cuda')) t2 = torch.tensor(a) t2 = t2.cuda() t3 = torch.tensor(a, device=torch.device('cuda'))
All three methods worked for me. In 1 and 2, you create a tensor on CPU and then move it to GPU when you use .to(device) or .cuda(). They are the same here. However, when you use .to(device) method you can explicitly tell torch to move to specific GPU by setting device=torch.device("cuda:<id>"). with .cuda() y...
https://stackoverflow.com/questions/53331247/
Accumulating Gradients
I want to accumulate the gradients before I do a backward pass. So wondering what the right way of doing it is. According to this article it's: model.zero_grad() # Reset gradients tensors for i, (inputs, labels) in enumerate(training_set): predictions = model(inputs) ...
So according to the answer here, the first method is memory efficient. The amount of work required is more or less the same in both methods. The second method keeps accumulating the graph, so would require accumulation_steps times more memory. The first method calculates the gradients straight away (and simply adds gr...
https://stackoverflow.com/questions/53331540/
Torchvision 0.2.1 transforms.Normalize does not work as expected
I am trying a new code using Pytorch. In this code, to load the dataset (CIFAR10), I am using torchvision's datasets. I define two transform functions ToTensor() and Normalize(). After normalize I expect the data in the dataset should be between 0 and 1. But the max value is still 255. I also inserted a print statement...
So, in the code you have laid out a plan that how you want to process your data. You have created a data pipeline through which your data will flow and multiple transforms will be applied. However, You forgot to call torch.utils.data.DataLoader. Until this is called, transformations on your data won't be applied. You...
https://stackoverflow.com/questions/53332663/
pytorch save a minibatch of 4D tensor as images
I have set of 8 tensors in 4D tensor of shape (B, C, H, W). More specifically, the shape of my tensor is (8,3,64,64) i.e 8 images with [3x64x64] format. I would like to save these in 1.png, 2.png ..., 8.png etc. When I try torchvision.utils.save_images(my_tensor), this is working fine. However, that is saving the imag...
If you want to save individual images you could use: for i in range(tensor.size(0)): torchvision.utils.save_image(tensor[i, :, :, :], '{}.png'.format(i)) which will save as : 1.png, 2.png ..., 8.png
https://stackoverflow.com/questions/53339224/
How to do a "element by element in-place inverse" with pytorch?
Given is an array a: a = np.arange(1, 11, dtype = 'float32') With numpy, I can do the following: np.divide(1.0, a, out = a) Resulting in: array([1. , 0.5 , 0.33333334, 0.25 , 0.2 , 0.16666667, 0.14285715, 0.125 , 0.11111111, 0.1 ], dtype=float32) Assuming that a i...
Pytorch follows the convention of using _ for in-place operations. for eg add -> add_ # in-place equivalent div -> div_ # in-place equivalent etc Element-by-element inplace inverse. >>> a = torch.arange(1, 11, dtype=torch.float32) >>> a.pow_(-1) >>> a >>> tensor([1.0000...
https://stackoverflow.com/questions/53350677/
Why is this function parameter identical in every invocation, despite passing different value? (Creating closures in a loop)
I'm using PyTorch and trying to register hooks on model parameters. The following code creates lambda functions to add to each model parameter, so I can see in the hook which tensor the gradient belongs to import torch import torchvision # define model and random train batch model = torchvision.models.alexnet() input...
You've run into late binding closures. The variables param and name are looked up at call time, not when the function they're used in is defined. By the time any of these functions are called, name and param are at the last values in the loop. To get around this, you could do this: for name, param in model.named_param...
https://stackoverflow.com/questions/53350810/
Stratified cross validation with Pytorch
My goal is to make binary classification, using neural network. The problem is that dataset is unbalanced, I have 90% of class 1 and 10 of class 0. To deal with it I want to use Stratified cross-validation. The problem that is I am working with Pytorch, I can't find any example and documentation doesn't provide it, a...
The easiest way I've found is to do you stratified splits before passing your data to Pytorch Dataset and DataLoader. That lets you avoid having to port all your code to skorch, which can break compatibility with some cluster computing frameworks.
https://stackoverflow.com/questions/53355326/
Pytorch Index a tensor of [n*n*3] by two tensors of size[n,n]
In numpy, I can index in the following: a = np.random.randn(2,2,3) b = np.eye(2,2).astype(np.uint8) c = np.eye(2,2).astype(np.uint8) print(a) print("diff") print(a[b,c,:]) , in which a[b, c, :] is a tensor of 2*2. [[[-1.01338087 0.70149058 0.55268617] [ 2.56941124 1.12720312 -0.07219555]] [[-0.04084548 0.1...
Indexing in PyTorch is almost similar to numpy. a = torch.randn(2, 2, 3) b = torch.eye(2, 2, dtype=torch.long) c = torch.eye(2, 2, dtype=torch.long) print(a) print(a[b, c, :]) tensor([[[ 1.2471, 1.6571, -2.0504], [-1.7502, 0.5747, -0.3451]], [[-0.4389, 0.4482, 0.7294], [-1.3051, 0....
https://stackoverflow.com/questions/53360596/
F.relu(self.fc1(x)) is causing RuntimeError problem
I have implemented the following CNN for my training and validation data sets that contain 90 and 20 images respectively divided into 3 classes: def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 =...
The size of the in_channels to self.fc1 is dependent on the input image size and not on the kernel-size. In your case, self.fc1 = nn.Linear(16 * 5 * 5, 120) should be nn.Linear(16 * image_size * image_size) where, image_size: is the size of the image in the last convolution layer. Sample Code: import torch import t...
https://stackoverflow.com/questions/53367049/
Pytorch on google-colaboratory GPU - Illegal memory access
I am using pytorch(0.4.0) on google-colaboratory ( NVIDIA-SMI 396.44 Driver Version: 396.44) When running my code outside any function, I am able to send pytorch tensors and model to the GPU : ... model.cuda() data_tensor = data_tensor.cuda() ... And my CNN model is trained successfully with 98% acc...
It now works with Pytorch 1.0 using: !pip3 install https://download.pytorch.org/whl/cu80/torch-1.0.0-cp36-cp36m-linux_x86_64.whl
https://stackoverflow.com/questions/53380068/
Why Skorch show NAN in the every epoch?
I want to create my own dataset class based on Dataset class of Skorch because I want to differentiate categorical columns and continuous columns. These categorical columns will be passed through the embedding layers in the model. The result is weird because it show NAN like this: epoch train_loss valid_loss ...
The problem is not with skorch but your data. You have to scale your inputs and, in this case, especially the targets to avoid huge losses and exploding gradients. As a start I suggest using, for example, sklearn.preprocessing.StandardScaler: from sklearn.preprocessing import StandardScaler class TabularDataset(Datas...
https://stackoverflow.com/questions/53386245/
Is it possible to split the training DataLoader (and dataset) into training and validation datasets?
The torchvision package provides easy access to commonly used datasets. You would use them like this: trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, ...
Meanwhile, I stumbled upon the method random_split. So, you don't split the DataLoader, but you split the Dataset: torch.utils.data.random_split(dataset, lengths)
https://stackoverflow.com/questions/53389417/
PyTorch DataLoader and Parallelism
I have created a class that extends DataSet to load images for a segmentation task, so one input and one output. Every time the method getitem is called, this class performs the necessary operations for data augmentation on both the input and the output, and it works perfectly. However, when I use this class with PyTo...
The solution is to create a local instance of all the Random classes uses, because the DataLoader does not. Doing that, all the random transformations performed are according to random values/states that are not affected by the DataLoader. The common way to do it seems to create a class and put all the transformations ...
https://stackoverflow.com/questions/53401319/
list of fastai models
FastAI uses AWD-LSTM for text processing. They provide pretrained models with get_language_model(). But I can't find proper documentation on what's available. Their github example page is really a moving target. Model names such as lstm_wt103 and WT103_1 are used. In the forums I found wt103RNN. Where can I find an u...
URLs is defined in fastai.datasets, there are constants for two models: WT103, WT103_1. AWS bucket has just the two models.
https://stackoverflow.com/questions/53402928/
How to batch convert sentence lengths to masks in PyTorch?
For example, from lens = [3, 5, 4] we want to get mask = [[1, 1, 1, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 0]] Both of which are torch.LongTensors.
One way that I found is: torch.arange(max_len).expand(len(lens), max_len) < lens.unsqueeze(1) Please share if there are better ways!
https://stackoverflow.com/questions/53403306/
Using nn.ModuleList over Python list dramatically slows down training
I'm training a very simple model that takes the number of hidden layers as a parameter. I originally stored these hidden layers in a vanilla python list [], however when converting this list to a nn.ModuleList, training slows down dramatically by at least one order of magnitude! AdderNet class AdderNet(nn.Module): ...
That's because when using a normal python list, the parameters are not added to the model's parameter list, but when using a ModuleList, they are. So, in the original scenario, you were never actually training the hidden layers, which is why it was faster. (Print out model.parameters() in each case and see what happens...
https://stackoverflow.com/questions/53403812/
How to print the "actual" learning rate in Adadelta in pytorch
In short: I can't draw lr/epoch curve when using adadelta optimizer in pytorch because optimizer.param_groups[0]['lr'] always return the same value. In detail: Adadelta can dynamically adapts over time using only first order information and has minimal computational overhead beyond vanilla stochastic gradient desce...
Check: self.optimizer.state. This is optimized with the lr and used in optimization process. From documentation a lr is just: lr (float, optional): coefficient that scale delta before it is applied to the parameters (default: 1.0) https://pytorch.org/docs/stable/_modules/torch/optim/adadelta...
https://stackoverflow.com/questions/53405934/
RuntimeError: Given groups=1, weight of size [64, 3, 7, 7], expected input[3, 1, 224, 224] to have 3 channels, but got 1 channels instead
In the code below: model_ft.eval() test_data, test_target = image_datasets['train'][idx] test_data = test_data.cuda() #test_target = test_target.cuda() test_target = torch.tensor(test_target) test_target = test_target.cuda() test_data.unsqueeze_(1) test_target.unsqueeze_(0) print(te...
Here's the fix: test_data, test_target = image_datasets['train'][idx] test_data = test_data.cuda() test_target = torch.tensor(test_target) test_target = test_target.cuda() test_data.unsqueeze_(0) test_target.unsqueeze_(0) output = model_ft(test_data) I had to change test_data.unsqueeze_(1) to test_data.unsqueeze_(0)...
https://stackoverflow.com/questions/53416833/
Pytorch: nn.Dropout vs. F.dropout
There are two ways to perform dropout: torch.nn.Dropout torch.nn.functional.Dropout I ask: Is there a difference between them? When should I use one over the other? I don't see any performance difference when I switched them around.
The technical differences have already been shown in the other answer. However the main difference is that nn.Dropout is a torch Module itself which bears some convenience: A short example for illustration of some differences: import torch import torch.nn as nn class Model1(nn.Module): # Model 1 using functiona...
https://stackoverflow.com/questions/53419474/
how to save torchtext Dataset?
I'm working with text and use torchtext.data.Dataset. Creating the dataset takes a considerable amount of time. For just running the program this is still acceptable. But I would like to debug the torch code for the neural network. And if python is started in debug mode, the dataset creation takes roughly 20 minutes (!...
You can use dill instead of pickle. It works for me. You can save a torchtext Field like TEXT = data.Field(sequential=True, tokenize=tokenizer, lower=True,fix_length=200,batch_first=True) with open("model/TEXT.Field","wb")as f: dill.dump(TEXT,f) And load a Field like with open("model/TEXT.Field","rb")as f: ...
https://stackoverflow.com/questions/53421999/
AttributeError: 'Compose' object has no attribute 'Compose' (in Pytorch 0.2.1)
This is the block of code where am getting this error: train_transforms = transforms.Compose([transforms.RandomRotation(30), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transfo...
The problem is that you have a variable called transforms after from torchvision import transforms which has a compose of a certain type. This override the transform you import from the torchvison. Therefore when you run the above code it calls the transforms which is a variable not the one from torchvision module. I...
https://stackoverflow.com/questions/53437666/
how can I insert a Tensor into another Tensor in pytorch
I have pytorch Tensor with shape (batch_size, step, vec_size), for example, a Tensor(32, 64, 128), let's call it A. I have another Tensor(batch_size, vec_size), e.g. Tensor(32, 128), let's call it B. I want to insert B into a certain position at axis 1 of A. The insert positions are given in a Tensor(batch_size), nam...
You can use a mask instead of cloning. See the code below # setup batch, step, vec_size = 64, 10, 128 A = torch.rand((batch, step, vec_size)) B = torch.rand((batch, vec_size)) pos = torch.randint(10, (64,)).long() # computations # create a mask where pos is 0 if it is to be replaced mask = torch.ones( (batch, step)...
https://stackoverflow.com/questions/53438062/
How to vectorize the following python code
I'm trying to obtain a matrix, where each element is calculated as follows: X = torch.ones(batch_size, dim) X_ = torch.ones(batch_size, dim) Y = torch.ones(batch_size, dim) M = torch.zeros(batch_size, batch_size) for i in range(batch_size): for j in range(batch_size): M[i, j] = ((X[i] - X_[i] * Y[j])**2).s...
If you want to sum() over dim, you can "lift" your 2D problem to 3D and sum there: M = ((X[:, None, :] - X_[:, None, :] * Y[None, ...])**2).sum(dim=2) How it works: X[:, None, :] and X_[:, None, :] are 3D of size (batch_size, 1, dim), and Y[None, ...] is of size (1, batch_size, dim). When multiplying X_[:, None,...
https://stackoverflow.com/questions/53442069/
What is the PyTorch alternative for Keras input_shape, output_shape, get_weights, get_config and summary
In Keras, after creating a model, we can see its input and output shapes using model.input_shape, model.output_shape. For weights and config we can use model.get_weights() and model.get_config(), respectively. What are the similar alternatives for PyTorch? Also is there any other functions we need to know for inspect...
There is no "model.summary()" method in pytorch. You need to use built_in methods and fields of the model. For example, I have customized inception_v3 model. To get the information I need to use other many different fields. For instance: IN: print(model) # print network architecture OUT Inception3( (Conv2...
https://stackoverflow.com/questions/53445345/
PyTorch set_grad_enabled(False) vs with no_grad():
Assuming autograd is on (as it is by default), is there any difference (besides indent) between doing: with torch.no_grad(): <code> and torch.set_grad_enabled(False) <code> torch.set_grad_enabled(True)
Actually no, there no difference in the way used in the question. When you take a look at the source code of no_grad. You see that it is actually using torch.set_grad_enabled to archive this behaviour: class no_grad(object): r"""Context-manager that disabled gradient calculation. Disabling gradient calculatio...
https://stackoverflow.com/questions/53447345/
understanding seed of a ByteTensor in PyTorch
I understand that a seed is a number used to initialize pseudo-random number generator. in pytorch, torch.get_rng_state documentation states as follows "Returns the random number generator state as a torch.ByteTensor.". and when i print it i get a 1-d tensor of size 5048 whose values are as shown below tensor([ 80,...
It sounds like you're thinking of the seed and the state as equivalent. For older pseudo-random number generators (PRNGs) that was true, but with more modern PRNGs tend to work as described here. (The answer in the link was written with respect to Mersenne Twister, but the concepts apply equally to other generators.) ...
https://stackoverflow.com/questions/53452049/
Load huge image dataset and some data augmentation using Pytorch
I have a question. I have about 2 million images (place365-standard dataset) and I want to do some data augmentation like transforming, cropping etc. Also, I have to make my own target image (y) based on some color model algorithms (CMYK) for example. So Actually, my preprocessing step includes augmentation and making...
If you look at e.g., torchvision.dataset.ImageFolder you'll see that it works quite similar to your design: the class has transform member that lists all sorts of augmentations (resizing, cropping, flipping etc.) and these are carried out on the images in the __getitem__ method. Regarding parallelism, the Dataset itsel...
https://stackoverflow.com/questions/53453663/
Pytorch LSTM: Target Dimension in Calculating Cross Entropy Loss
I've been trying to get an LSTM (LSTM followed by a linear layer in a custom model), working in Pytorch, but was getting the following error when calculating the loss: Assertion cur_target >= 0 && cur_target < n_classes' failed. I defined the loss function with: criterion = nn.CrossEntropyLoss() and ...
You can use squeeze() on your output tensor, this returns a tensor with all the dimensions of size 1 removed. This short code uses the shapes you mentioned in your question: sequence_length = 75 number_of_classes = 55 # creates random tensor of your output shape output = torch.rand(sequence_length, 1, number_of_cla...
https://stackoverflow.com/questions/53455780/
Pytorch: "Model Weights not Changing"
Can someone help me understand why the weights are not updating? unet = Unet() optimizer = torch.optim.Adam(unet.parameters(), lr=0.001) loss_fn = torch.nn.MSELoss() input = Variable(torch.randn(32, 1, 64, 64, 64 ), requires_grad=True) target = Variable(torch.randn(32, 1, 64, 64, 64), requires_gra...
I identified this problem to be of "The Dying ReLu Problem" Due to the data being Hounsfield units and Pytorch uniform distribution of initial weights meant that many neurons would start out in ReLu's zero region leaving them paralyzed and dependable on other neurons to produce a gradient that could pull them out of th...
https://stackoverflow.com/questions/53461869/
Shape of pytorch model.parameter is inconsistent with how it's defined in the model
I'm attempting to extract the weights and biases from a simple network built in PyTorch. My entire network is composed of nn.Linear layers. When I create a layer by calling nn.Linear(in_dim, out_dim), I expect the parameters that I get from calling model.parameters() for that model to be of shape (in_dim, out_dim) for ...
What you see there is not the (out_dim, in_dim), it is just the shape of the weight matrix. When you call print(model) you can see that input and output features are correct: RNN( (dense1): Linear(in_features=12, out_features=100, bias=True) (dense2): Linear(in_features=100, out_features=100, bias=False) (dense3...
https://stackoverflow.com/questions/53462493/
Sparse tensors to decrease training time
I've learning about PyTorch sparse tensors : https://pytorch.org/docs/stable/sparse.html From the docs (https://pytorch.org/docs/stable/sparse.html) : "Torch supports sparse tensors in COO(rdinate) format, which can efficiently store and process tensors for which the majority of elements are zeros." Is one of the int...
Yes but indirectly. sparse tensors can reduce the complexity of computations and hence training/inference time. Complexity of matrix multiplication depends on number of elements in matrix whereas complexity of sparse matrix multiplication would depend on the number of non-zero elements which are less (due to sparsity...
https://stackoverflow.com/questions/53463156/
Auto updating custom layer parameters while backpropagating in pytorch
I have a pytorch custom layer defined as: class MyCustomLayer(nn.Module): def __init__(self): super(MyCustomLayer, self).__init__() self.my_parameter = torch.rand(1, requires_grad = True) # the following allows the previously defined parameter to be recognized as a network parameter when instantiating ...
What you did i.e. return x*self.my_registered_parameter[0] worked because you use the registered param for calculating the gradient. When you call nn.Parameter it returns a new object and hence self.my_parameter that you use for the operation and the one registered are not same. You can fix this by declaring the my_...
https://stackoverflow.com/questions/53463532/
How does `images, labels = dataiter.next() ` work in PyTorch Tutorial?
From the tutorial cifar10_tutorial, how is images, labels assigned? trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, ...
I think it is crucial to understand the difference between an iterable and an iterator. An iterable is an object that you can iterate over. An Iterator is an object which is used to iterate over an iterable object using the __next__ method, which returns the next item of the object. A simple example is the following. ...
https://stackoverflow.com/questions/53464247/
PyTorch - shape of nn.Linear weights
Yesterday I came across this question and for the first time noticed that the weights of the linear layer nn.Linear need to be transposed before applying matmul. Code for applying the weights: output = input.matmul(weight.t()) What is the reason for this? Why are the weights not in the transposed shape just fro...
I found an answer here: Efficient forward pass in nn.Linear #2159 It seems like there is no real reasoning behind this. However the transpose operation doesn't seem to be slowing down the computation. According to the issue mentioned above, during the forward pass the transpose operation is (almost) free in terms of...
https://stackoverflow.com/questions/53465608/
PyTorch - multiplying tensor with scalar results in zero vector
I have no idea why the result is all 0 with tensor. Anything wrong here? >>> import torch >>> import numpy as np >>> import math >>> torch.__version__ '0.4.1' >>> np.__version__ '1.15.4' >>> torch.arange(0, 10, 2) *-(math.log(10000.0) / 10) tensor([0, 0, 0, 0, 0]...
As written in the comment when using 0.4.0 get the same results as with numpy: tensor([-0.0000, -1.8421, -3.6841, -5.5262, -7.3683]) However with 0.4.1 I'm getting a zero vector too. The reason for this is that torch.arange(0, 10, 2) returns a tensor of type float for 0.4.0 while it returns a tensor of type long f...
https://stackoverflow.com/questions/53467011/
Index pytorch 4d tensor by values in 2d tensor
I have two pytorch tensors: X with shape (A, B, C, D) I with shape (A, B) Values in I are integers in range [0, C). What is the most efficient way to get tensor Y with shape (A, B, D), such that: Y[i][j][k] = X[i][j][ I[i][j] ][k]
You probably want to use torch.gather for the indexing and expand to adjust I to the required size: eI = I[..., None, None].expand(-1, -1, 1, X.size(3)) # make eI the same for the last dimension Y = torch.gather(X, dim=2, index=eI).squeeze() testing the code: A = 3 B = 4 C = 5 D = 7 X = torch.rand(A, B, C, D) ...
https://stackoverflow.com/questions/53471716/
How to convert 3D tensor to 2D tensor in pytorch?
I am new to pytorch. I have 3D tensor (32,10,64) and I want a 2D tensor (32, 64). I tried view() and used after passing to linear layer squeeze() which converted it to (32,10).
Try this t = torch.rand(32, 10, 64).permute(0, 2, 1)[:, :, -1] or, as pointed out by Shai, you could also t = torch.rand(32, 10, 64)[:, -1, :] print(t.size()) # torch.Size([32, 64])
https://stackoverflow.com/questions/53474056/
Understanding the softmax output layer of RNN
Here's a simple LSTM model in Keras: input = Input(shape=(max_len,)) model = Embedding(input_dim=input_dim, output_dim=embed_dim, input_length=max_len)(input) model = Dropout(0.1)(model) model = Bidirectional(LSTM(units=blstm_dim, return_sequences=True, recurrent_dropout=0.1))(model) out =Dense(label_dim, activation="...
Are the two models I've printed above equivalent (let's ignore the recurrent_dropout since I haven't figure out how to do that in PyTorch)? Besides the dropout I can see no difference. So they should be completely equivalent in terms of structure. One note: You don't have to initialize the states if you use it thi...
https://stackoverflow.com/questions/53475803/
AttributeError: 'tuple' object has no attribute 'log_softmax'
while trying to finetune inception_V3 for my own dataset by changing the last fc layer like last_layer =nn.Linear(n_inputs, len(classes)) inception_v3.fc = last_layer after that when I train it got this error on this position # on training loop output = inception_v3(data) # calculate the batch loss ...
This is a well known problem. Try one the following solutions: disable aux_logits when the model is created here by also passing aux_logits=False to the inception_v3 function. edit your train function to accept and unpack the returned tuple to be something like: output, aux = model(input_var) Check the followi...
https://stackoverflow.com/questions/53476305/
Pytorch DataLoader multiple data source
I am trying to use Pytorch dataloader to define my own dataset, but I am not sure how to load multiple data source: My current code: class MultipleSourceDataSet(Dataset): def __init__ (self, json_file, root_dir, transform = None): with open(root_dir + 'block0.json') as f: self.result = torch.T...
For DataLoader you need to have a single Dataset, your problem is that you have multiple 'json' files and you only know how to create a Dataset from each 'json' separately. What you can do in this case is to use ConcatDataset that contains all the single-'json' datasets you create: import os import torch.utils.data as...
https://stackoverflow.com/questions/53477861/
Munging PyTorch's tensor shape from (C, B, H) to (B, C*H)
Given an input tensor of shape (C, B, H) torch.Size([2, 5, 32]) of some neural net layers, where channels = 2 batch_size = 5 hidden_size = 32 The goal is to flatten the channels and manipulate the input tensor to the shape (B, C*H) torch.Size([5, 2 * 32]), where: batch_size = 5 hidden_size = 32 * 2 I've tried t...
Let's look "behind the curtain" and see why one must have both permute/transpose and view in order to go from a C-B-H to B-C*H: Elements of tensors are stored as a long contiguous vector in memory. For instance, if you look at a 2-3-4 tensor it has 24 elements stored at 24 consecutive places in memory. This tensor als...
https://stackoverflow.com/questions/53479315/
Matrix multiplication in pyTorch
I'm writing a simple neural network in pyTorch, where features and weights both are (1, 5) tensors. What are the differences between the two methods that I mention below? y = activation(torch.sum(features*weights) + bias) and yy = activation(torch.mm(features, weights.view(5,1)) + bias)
Consider it step by step: x = torch.tensor([[10, 2], [3,5]]) y = torch.tensor([[1,3], [5,6]]) x * y # tensor([[10, 6], # [15, 30]]) torch.sum(x*y) #tensor(61) x = torch.tensor([[10, 2], [3,5]]) y = torch.tensor([[1,3], [5,6]]) np.matmul(x, y) # array([[20, 42], # [28, 39]]) So there is a differen...
https://stackoverflow.com/questions/53496570/