instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Iterating over Torchtext.data.BucketIterator object throws AttributeError 'Field' object has no attribute 'vocab'
When I try to look into a batch, by printing the next iteration of the BucketIterator object, the AttributeError is thrown. tv_datafields=[("Tweet",TEXT), ("Anger",LABEL), ("Fear",LABEL), ("Joy",LABEL), ("Sadness",LABEL)] train, vld = data.TabularDataset.splits(path="./data/", train="train.csv",validation="test.cs...
I am not sure about the specific error you are getting but, in this case, you can iterate over a batch by using the following code: for i in train_iter: print i.Tweet print i.Anger print i.Fear print i.Joy print i.Sadness i.Tweet (also others) is a tensor of shape (input_data_length, batch_size)....
https://stackoverflow.com/questions/51231852/
torchtext BucketIterator minimum padding
I'm trying to use the BucketIterator.splits function in torchtext to load data from csv files for use in a CNN. Everything works fine unless I have a batch that the longest sentence is shorter than the biggest filter size. In my example I have filters of sizes 3, 4, and 5 so if the longest sentence doesn't have at le...
I looked through the torchtext source code to better understand what the sort_key was doing, and saw why my original idea wouldn't work. I'm not sure if it is the best solution or not, but I have come up with a solution that works. I created a tokenizer function that pads the text if it is shorter than the longest fil...
https://stackoverflow.com/questions/51252221/
Parallel Cholesky decomposition in PyTorch GPU
To get a differentiable term containing the determinant of a D-dimensional positive-definite matrix C (differential entropy of a multivariate Gaussian in my case), I can use: torch.log2(torch.potrf(C).diag()).sum() + D / 2.0 * (np.log2(2 * np.pi * np.e)) potrf(C) performs Cholesky decomposition, whose diagonal element...
Batch Cholesky decomposition is now available in PyTorch. Along with batch inverse(), etc. For older versions of Pytorch You are looking for Batch Cholesky decomposition. It's not implemented in Pytorch at the moment, but there is an open issue and plan to add it in the future. I only know of a Batch LU factori...
https://stackoverflow.com/questions/51257780/
Product of PyTorch tensors along arbitrary axes à la NumPy's `tensordot`
NumPy provides the very useful tensordot function. It allows you to compute the product of two ndarrays along any axes (whose sizes match). I'm having a hard time finding anything similar in PyTorch. mm works only with 2D arrays, and matmul has some undesirable broadcasting properties. Am I missing something? Am I rea...
As mentioned by @McLawrence, this feature is being currently discussed (issue thread). In the meantime, you could consider torch.einsum(), e.g.: import torch import numpy as np a = np.arange(36.).reshape(3,4,3) b = np.arange(24.).reshape(4,3,2) c = np.tensordot(a, b, axes=([1,0],[0,1])) print(c) # [[ 2640. 2838.] [...
https://stackoverflow.com/questions/51266507/
How to get probabilities from Resnet using pytorch?
I am finetuning resnet on my dataset which has multiple labels. I would like to convert the 'scores' of the classification layer to probabilities and use those probabilities to calculate the loss at the training. Could you give an example code for this? Can I use like this: P = net.forward(x) p = to...
So, you are training a model i.e resnet with cross-entropy in pytorch. Your loss calculation would look like this. logit = model(x) loss = torch.nn.functional.cross_entropy(logits=logit, target=y) In this case, you can calculate the probabilities of all classes by doing, logit = model(x) p = torch.nn.functional.sof...
https://stackoverflow.com/questions/51291353/
Equivalent of Keras's binary_crossentropy in PyTorch?
I want to port some code from keras to pytorch, but I cann't find equivalent of Keras's binary_crossentropy in PyTorch. PyTorch's binary_cross_entropy has different behavior with keras's. import torch import torch.nn.functional as F input = torch.tensor([[ 0.6845, 0.2454], [ 0.7186, 0.3710], ...
Keras binary crossentropy takes y_true, y_pred, while Pytorch takes them in the opposite order, therefore you need to change the Keras line to K.eval(K.binary_crossentropy(K.variable(target.detach().numpy()), K.variable(input.detach().numpy()))) In this way you get the correct output: array([[ 1.15359652, 1.404865...
https://stackoverflow.com/questions/51299900/
PyTorch error loading saved nn.Module: object has no attribute 'to'
I am using PyTorch 0.4. I defined a PyTorch MyModel by inheriting from nn.Module, and saved an instance of it by calling torch.save(my_model, my_path) Then, when loading it again with torch.load(my_path), my program crashed with the following error: AttributeError: 'MyModel' object has no attribute 'to' But my p...
I already found it out, and just wanted to quickly post about it since google didn't give an obvious clue. It turned out that, although I saved the model from a computer with 0.4, I was trying to load it from a different computer that still had an older (<0.4) PyTorch version installed. pip install --upgrade torch ...
https://stackoverflow.com/questions/51306585/
How can I generate and display a grid of images in PyTorch with plt.imshow and torchvision.utils.make_grid?
I am trying to understand how torchvision interacts with mathplotlib to produce a grid of images. It's easy to generate images and display them iteratively: import torch import torchvision import matplotlib.pyplot as plt w = torch.randn(10,3,640,640) for i in range (0,10): z = w[i] plt.imshow(z.permute(1,2,0)...
There's a small mistake in your code. torchvision.utils.make_grid() returns a tensor which contains the grid of images. But the channel dimension has to be moved to the end since that's what matplotlib recognizes. Below is the code that works fine: In [107]: import torchvision # sample input (10 RGB images containing ...
https://stackoverflow.com/questions/51329159/
Pytorch Where Does resNet add values?
I am working on ResNet and I have found an implementation that does the skip connections with a plus sign. Like the following Class Net(nn.Module): def __init__(self): super(Net, self).__int_() self.conv = nn.Conv2d(128,128) def forward(self, x): out = self.conv(x) // line 1 ...
As mentioned in comments by @UmangGupta, what you are printing seems to be the shape of your tensors (i.e. the "shape" of a 3x3 matrix is [3, 3]), not their content. In your case, you are dealing with 1x128x32x32 tensors). Example to hopefully clarify the difference between shape and content : import torch out = tor...
https://stackoverflow.com/questions/51332533/
Pytorch DataLoader - Choose Class STL10 Dataset
Is it possible to pull only where class = 0 in the STL10 dataset in PyTorch torchvision? I am able to check them in a loop, but need to receive batches of class 0 images # STL10 dataset train_dataset = torchvision.datasets.STL10(root='./data/', transform=transforms.Compose([ ...
If you only want samples from one class, you can get the indices of samples with the same class from the Dataset instance with something like def get_same_index(target, label): label_indices = [] for i in range(len(target)): if target[i] == label: label_indices.append(i) return label_...
https://stackoverflow.com/questions/51334858/
Why can GPU do matrix multiplication faster than CPU?
I've been using GPU for a while without questioning it but now I'm curious. Why can GPU do matrix multiplication much faster than CPU? Is it because of parallel processing? But I didn't write any parallel processing code. Does it do it automatically by itself? Any intuition / high-level explanation will be apprecia...
How do you parallelize the computations? GPU's are able to do a lot of parallel computations. A Lot more than a CPU could do. Look at this example of vector addition of let's say 1M elements. Using a CPU let's say you have 100 maximum threads you can run : (100 is lot more but let's assume for a while) In a typical ...
https://stackoverflow.com/questions/51344018/
Dimension out of range when applying l2 normalization in Pytorch
I'm getting a runtime error: RuntimeError: Dimension out of range (expected to be in range of [-1, 0], but got 1)` and can't figure out how to fix it. The error appears to refer to the line: i_enc = F.normalize(input =i_batch, p=2, dim=1, eps=1e-12) # (batch, K, feat_dim) I'm trying to encode image feature...
I would suggest to check the shape of i_batch (e.g. print(i_batch.shape)), as I suspect i_batch has only 1 dimension (e.g. of shape [N]). This would explain why PyTorch is complaining you can normalize only over the dimension #0; while you are asking for the operation to be done over a dimension #1 (c.f. dim=1).
https://stackoverflow.com/questions/51348833/
what does colon wrapped class mean in python comment?
What does colon wrapped class (:class:) mean in python comment? For example, class Optimizer(object): r"""Base class for all optimizers. Arguments: params (iterable): an iterable of :class:`torch.Tensor` s or :class:`dict` s. Specifies what Tensors should be optimized. defaults: (d...
It's nothing Python or Torch specific. It's syntax for a documentation tool; most likely Sphinx. The syntax indicates a cross-reference to the documentation for another class. When the documentation tool generates hyperlinked output such as HTML, such references automatically become links to the documentation page fo...
https://stackoverflow.com/questions/51353066/
Pixel RNN Pytorch Implementation
I am trying to implement Pixel RNN in pytorch, but I cannot seem to find any documentation on this. The main parts of Pixel RNN are Row LSTM and BiDiagonal LSTM, so I am looking for some code of these algorithms to better understand what they are doing. Specifically, I am confused as to these algorithms calculate one r...
Summary Here is an in progress partial implementation: https://github.com/carpedm20/pixel-rnn-tensorflow Here is a description of Row LSTM and BiDiagonal LSTM at google deepmind: https://towardsdatascience.com/summary-of-pixelrnn-by-google-deepmind-7-min-read-938d9871d6d9 Row LSTM From the linked deepmind blog:...
https://stackoverflow.com/questions/51364273/
CNN weights getting stuck
This is a slightly theoretical question. Below is a graph the plots the loss as the CNN is being trained. Y axis is MSE and X axis is number of Epochs. Description of CNN: class Net(nn.Module): def __init__ (self): super(Net, self).__init__() self.conv1 = nn.Conv1d(in_channels = 1, out_channels = 5, kernel_...
Is this a multiclass classification problem? If so you could try using cross entropy loss. And a softmax layer before output maybe? I'm not sure because I don't know what's the model's input and output.
https://stackoverflow.com/questions/51364416/
I am trying to classify flowers with a pretrained network, but for some reason it does not train
I am currently trying to classify flowers from this dataset, using Pytorch. First of all I started to transfrom my data for the training, validation and testing set. data_dir = 'flowers' train_dir = data_dir + '/train' valid_dir = data_dir + '/valid' test_dir = data_dir + '/test' train_transforms = transforms.Compos...
Here are some tips- in the order of which I think they will help: Try doing some hyper-parameter optimization. (i.e. try 10 learning rates over a domain like 1e-2 to 1e-6) More info on what that is: (http://cs231n.github.io/neural-networks-3/#hyper) Code and print a accuracy metric (print it with your loss), because ...
https://stackoverflow.com/questions/51366521/
How does pytorch broadcasting work?
torch.add(torch.ones(4,1), torch.randn(4)) produces a Tensor with size: torch.Size([4,4]). Can someone provide a logic behind this?
PyTorch broadcasting is based on numpy broadcasting semantics which can be understood by reading numpy broadcasting rules or PyTorch broadcasting guide. Expounding the concept with an example would be intuitive to understand it better. So, please see the example below: In [27]: t_rand Out[27]: tensor([ 0.23451, 0.3456...
https://stackoverflow.com/questions/51371070/
What exactly is label for image segmentation task in computer vision
I have been working on a some image segmentation tasks lately and would like to apply one from scratch. Segmentation as I have understood is the per pixel prediction to where it belongs - to an object instance(things), to a background segment instance(stuff). As per the COCO dataset on which the latest algorithm ...
The intution of @Aldream was correct but explicitly for the coco dataset they provide binary masks, The documentation is not so great on their website : Interface for manipulating masks stored in RLE format. RLE is a simple yet efficient format for storing binary masks. RLE first divides a vector (or vecto...
https://stackoverflow.com/questions/51371624/
The purpose of introducing nn.Parameter in pytorch
I am new to Pytorch and I am confused about the difference between nn.Parameter and autograd.Variable. I know that the former one is the subclass of Variable and has the gradient. But I really don't understand why we introduce Parameter and when we should use it? SUMMARY: Thanks for the explanation of iacolippo, i...
From the documentation: Parameters are Tensor subclasses, that have a very special property when used with Modules - when they’re assigned as Module attributes they are automatically added to the list of its parameters, and will appear e.g. in parameters() iterator. Assigning a Tensor doesn’t have such effect. This is...
https://stackoverflow.com/questions/51373919/
How to read a ckpt file with python3, while it is saved using python2?
I try to read a checkpoint file with pyTorch checkpoint = torch.load(xxx.ckpt) The file was generated by a program written using python 2.7. I try to read the file using python 3.6 but get the following error UnicodeDecodeError: 'ascii' codec can't decode byte 0x8c in position 16: ordinal not in range(128) Is it ...
Eventually I solve the issue by 1) create a python2 environment using anaconda 2) read the checkpoint file using pytorch, and then save it using pickle checkpoint = torch.load("xxx.ckpt") with open("xxx.pkl", "wb") as outfile: pickle.dump(checkpointfile, outfile) 3) back to the python3 environment, read the fi...
https://stackoverflow.com/questions/51376673/
Understanding PyTorch Bernoulli distribution from the documention
So I was reading the pytorch document trying to learn and understand somethings(because I'm new to the machine learning ), I found the torch.bernoulli() and I understood (I miss understood it) that it approximates the tensors that the have the values between 1 and 0 to 1 or 0 depends on the value (like classic school l...
Well, Bernoulli is a probability distribution. Specifically, torch.distributions.Bernoulli() samples from the distribution and returns a binary value (i.e. either 0 or 1). Here, it returns 1 with probability p and return 0 with probability 1-p. Below example will make the understanding clear: In [141]: m = torch.dis...
https://stackoverflow.com/questions/51392046/
Using torch.nn.DataParallel with a custom CUDA extension
To my understanding, the built-in PyTorch operations all automatically handle batches through implicit vectorization, allowing parallelism across multiple GPUs. However, when writing a custom operation in CUDA as per the Documentation, the LLTM example given performs operations that are batch invariant, for example com...
In order to use torch.nn.DataParallel with a custom CUDA extension, you can follow these steps: Define your custom CUDA extension in a subclass of torch.autograd.Function, and implement the forward() and backward() methods for the forward and backward passes, respectively. In the forward() method, create a new output ...
https://stackoverflow.com/questions/51400618/
Is Seq2Seq the right model for my data?
I'm trying to train a model to predict design patterns from web pages. I'm using coordinates of bounding rects given a bunch of element groupings. Patterns look like this: [[elementId, width, height, x, y]] so my target would be the [[x,y]] given [[elementId, width, height]]. Concretely: [[5, 1.0, 1.0], [4, 1.0,...
Seq2Seq/LSTM are used when input/output are variable lengths. Your input is of size 3 and output is of size 2 (at least for the given examples). So you can use a simple one/two-hidden layer feed-forward model with the L2/L1 loss (for regression). Any opt (SGD/Adam) should be fine, however, Adam works well in practi...
https://stackoverflow.com/questions/51412473/
How do i add ctc beam search decoder in crnn model (pytorch)
I am following the CRNN implementation of https://github.com/meijieru/crnn.pytorch, but seems like it is not using beam search for decoding the words. Can someone tell me how to add beam search decoding in the same model? At the same time in Tensorflow, there is an inbuilt tf.nn.ctc_beam_search_decoder.
i know its not a great idea, but i did it using tensorflow inside pytorch. if(beam): decodes, _ = tf.nn.ctc_beam_search_decoder(inputs=preds_.cpu().detach().numpy(), sequence_length=25*np.ones(1), merge_repeated=False) with tf.Session(config = tf.ConfigProto(device_count = {'GPU':...
https://stackoverflow.com/questions/51422776/
Using Precision and Recall in training of skewed dataset
I have a skewed dataset (5,000,000 positive examples and only 8000 negative [binary classified]) and thus, I know, accuracy is not a useful model evaluation metric. I know how to calculate precision and recall mathematically but I am unsure how to implement them in python code. When I train the model on all the data I...
The implementation of precision, recall and F1 score and other metrics are usually imported from the scikit-learn library in python. link: http://scikit-learn.org/stable/modules/classes.html#module-sklearn.metrics Regarding your classification task, the number of positive training samples simply eclipse the negative...
https://stackoverflow.com/questions/51425436/
What does model.train() do in PyTorch?
Does it call forward() in nn.Module? I thought when we call the model, forward method is being used. Why do we need to specify train()?
model.train() tells your model that you are training the model. This helps inform layers such as Dropout and BatchNorm, which are designed to behave differently during training and evaluation. For instance, in training mode, BatchNorm updates a moving average on each new batch; whereas, for evaluation mode, these updat...
https://stackoverflow.com/questions/51433378/
Rearranging a 3-D array using indices from sorting?
I have a 3-D array of random numbers of size [channels = 3, height = 10, width = 10]. Then I sorted it using sort command from pytorch along the columns and obtained the indices as well. The corresponding index is shown below: Now, I would like to return to the original matrix using these indices. I currently u...
Using Tensor.scatter_() You can directly scatter the sorted tensor back into its original state using the indices provided by sort(): torch.zeros(ch,h,w).scatter_(dim=1, index=indices, src=inp_sort) The intuition is based on the previous answer below. As scatter() is basically the reverse of gather(), inp_reunf = i...
https://stackoverflow.com/questions/51433741/
How can I create a PyCUDA GPUArray from a gpu memory address?
I'm working with PyTorch and want to do some arithmetic on Tensor data with the help of PyCUDA. I can get a memory address of a cuda tensor t via t.data_ptr(). Can I somehow use this address and my knowledge of the size and data type to initialize a GPUArray? I am hoping to avoid copying the data, but that would also b...
It turns out this is possible. We need a pointer do the data, which needs some additional capabilities: class Holder(PointerHolderBase): def __init__(self, tensor): super().__init__() self.tensor = tensor self.gpudata = tensor.data_ptr() def get_pointer(self): return self.tens...
https://stackoverflow.com/questions/51438232/
How to iterate over two dataloaders simultaneously using pytorch?
I am trying to implement a Siamese network that takes in two images. I load these images and create two separate dataloaders. In my loop I want to go through both dataloaders simultaneously so that I can train the network on both images. for i, data in enumerate(zip(dataloaders1, dataloaders2)): # get the inputs...
I see you are struggling to make a right dataloder function. I would do: class Siamese(Dataset): def __init__(self, transform=None): #init data here def __len__(self): return #length of the data def __getitem__(self, idx): #get images and labels here #returned ...
https://stackoverflow.com/questions/51444059/
In Pytorch F.nll_loss() Expected object of type torch.LongTensor but found type torch.FloatTensor for argument #2 'target'
Why does this error occur. I am trying to write a custom loss function, that finally has a negative log likelihood. As per my understanding the NLL is calculated between two probability values? >>> loss = F.nll_loss(sigm, trg_, ignore_index=250, weight=None, size_average=True) Traceback (most recent call...
"As per my understanding, the NLL is calculated between two probability values?" No, NLL is not calculated between two probability values. As per the pytorch docs (See shape section), It is usually used to implement cross entropy loss. It takes input which is expected to be log-probability and is of size (N, C) when ...
https://stackoverflow.com/questions/51448897/
How do I get words from an embedded vector?
How can I convert them into their original words when I generate word vectors in the generator? I used the nn.Embedding module built into pytorch to embed words.
Since you didn't provide any code, I am using below code with comments to answers your query. Feel free to add more information for your particular use case. import torch # declare embeddings embed = torch.nn.Embedding(5,10) # generate embedding for word [4] in vocab word = torch.tensor([4]) # search function for s...
https://stackoverflow.com/questions/51452907/
Pytorch nn.embedding error
I was reading pytorch documentation on Word Embedding. import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim torch.manual_seed(5) word_to_ix = {"hello": 0, "world": 1, "how":2, "are":3, "you":4} embeds = nn.Embedding(2, 5) # 2 words in vocab, 5 dimensional embeddings lookup...
When you declare embeds = nn.Embedding(2, 5) the vocab size is 2 and embedding size is 5. i.e each word will be represented by a vector of size 5 and there are only 2 words in vocab. lookup_tensor = torch.tensor(word_to_ix["how"], dtype=torch.long) embeds will try to look up vector corresponding to the third word in v...
https://stackoverflow.com/questions/51456059/
PyTorch Tensors of Inputs and Labels in LSTM
I am new to PyTorch, and I'm working on a simple project to generate text, in order to get my hands on pytorch. I am using the concept of this code and converting it to PyTorch: https://machinelearningmastery.com/text-generation-lstm-recurrent-neural-networks-python-keras/ I have 10 timesteps and 990 samples. For each ...
In PyTorch, when using the CrossEntropyLoss, you need to give the output labels as integers in [0..n_classes-1] instead of as one-hot vectors. Right now pytorch thinks you are trying to predict multiple outputs.
https://stackoverflow.com/questions/51461970/
Highlighting important words in a sentence using Deep Learning
I am trying to highlight important words in imdb dataset which contributed finally to the sentiment analysis prediction . The dataset is like : X_train - A review as string . Y_train - 0 or 1 Now after using Glove embeddings for embedding the X_train value I can feed it to a neural net . Now my question is , how c...
Here is a version with Attention (not Hierarchical) but you should be able to figure out how to make it work with hierarchy too - if not I can help out too. The trick is to define 2 models and use 1 for the training (model) and the other one to extract attention values (model_with_attention_output): # Tensorflow 1.9; ...
https://stackoverflow.com/questions/51477977/
Initialising weights and bias with PyTorch - how to correct dimensions?
Using this model I'm attempting to initialise my network with my predefined weights and bias : dimensions_input = 10 hidden_layer_nodes = 5 output_dimension = 10 class Model(torch.nn.Module): def __init__(self): super(Model, self).__init__() self.linear = torch.nn.Linear(dimensions_input,hidden_l...
The code provided doesn't run due to the fact that x_data isn't defined, so I can't be sure that this is the issue, but one thing that strikes me is that you should replace self.linear2.weight = torch.nn.Parameter(torch.zeros(dimensions_input,hidden_layer_nodes)) self.linear2.bias = torch.nn.Parameter(torch.ones(hidde...
https://stackoverflow.com/questions/51484793/
Pytorch Torch.save FileNotFoundError
When I try to call "torch.save" to save my model in a "tmp_file", it rises a FileNotFoundError. the trace back is as follow: Traceback (most recent call last): File “C:/Users/Haoran/Documents/GitHub/dose-response/python/simulations/hdr.py”, line 234, in test_hdr_continuous() File “C:/Users/Haoran/Documents/G...
As shmee observed, you are trying to write to /tmp/[...] on a Windows machine. Therefore you get FileNotFoundError. To make your code OS agnostic, you may find python's tempfile package useful, especially NamedTemporaryFile: this function creates a temporary file and returns its name, so you can access/use it in your p...
https://stackoverflow.com/questions/51490965/
How to extract fc7 features from AlexNet in pytorch as numpy array?
I want to extract the 4096-dimensional feature vector from the fc7 layer of my finetuned AlexNet. My goal is to use this layer for clustering later on. This is how I extract it: alexnet = models.alexnet(pretrained=True); fc7 = alexnet.classifier[6]; However, when I print it, fc7 is a Linear object: Linear(in_featur...
This could be done by creating a new model with all the same layers (and associated parameters) as alexnet except for the last layer. new_model = models.alexnet(pretrained=True) new_classifier = nn.Sequential(*list(new_model.classifier.children())[:-1]) new_model.classifier = new_classifier You should now be able to...
https://stackoverflow.com/questions/51501828/
Calculate the accuracy every epoch in PyTorch
I am working on a Neural Network problem, to classify data as 1 or 0. I am using Binary cross entropy loss to do this. The loss is fine, however, the accuracy is very low and isn't improving. I am assuming I did a mistake in the accuracy calculation. After every epoch, I am calculating the correct predictions after thr...
Is x the entire input dataset? If so, you might be dividing by the size of the entire input dataset in correct/x.shape[0] (as opposed to the size of the mini-batch). Try changing this to correct/output.shape[0]
https://stackoverflow.com/questions/51503851/
Accessing reduced dimensionality of trained autoencoder
Here is a autoencoder trained on mnist using PyTorch : import torch import torchvision import torch.nn as nn from torch.autograd import Variable cuda = torch.cuda.is_available() # True if cuda is available, False otherwise FloatTensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor print('Training on %s' % (...
I'm not very familiar with pyTorch, but splitting the autoencoder into an encoder and decoder model seems to work (I changed the size of the hidden layer from 512 to 64, and the dimension of the encoded image from 128 to 4, to make the example run faster): import torch import torchvision import torch.nn as nn from tor...
https://stackoverflow.com/questions/51515819/
Custom Loss in Pytorch where object does not have attribute backward()
I am new to pytorch and I tried creating my own custom loss. This has been really challenging. Below is what I have for my loss. class CustomLoss(nn.Module): def __init__(self, size_average=True, reduce=True): """ Args: size_average (bool, optional): By default, the losses are averag...
Hi! the problem is that you try to call the backward function on the module, but not on the variable (as you probably want to). As you have not implemented a backward function on the module, the interpreter cannot find one. So what you want to do instead is: loss_func = CustomLoss() loss = loss_func.loss_c...
https://stackoverflow.com/questions/51521361/
Why is PyTorch called PyTorch?
I have been looking into deep learning frameworks lately and have been wondering about the origin of the name of PyTorch. With Keras, their home page nicely explains the name's origin, and with something like TensorFlow, the reasoning behind the name seems rather clear. For PyTorch, however, I cannot seem to come acros...
Here a short answer, formed as another question: Torch, SMORCH ??? PyTorch developed from Torch7. A precursor to the original Torch was a library called SVM-Torch, which was developed around 2001. The SVM stands for Support Vector Machines. SVM-Torch is a decomposition algorithm similar to SVM-Light, but adapted to reg...
https://stackoverflow.com/questions/51530778/
Is "input" a keyword that causes errors when used as a parameter name (in PyTorch)?
So I have a line of code: packed_embeddings = pack_padded_sequence(input=embeddings, lengths=lengths, batch_first=True) That throws me this error: File "/Users/kwj/anaconda3/lib/python3.6/site-packages/torch/onnx/__i...
What's happening here is that pack_padded_sequence is decorated to return a partially applied function, and within the decorating code there is a function that accepts arguments as *args, **kwargs. This function passes args to another function, which inspects the first arg. When you pass all the arguments to packed_pa...
https://stackoverflow.com/questions/51531007/
Which part of Pytorch tensor represents channels?
Surprisingly I have not found an answer to this question after looking around the internet. I am specifically interested in a 3d tensor. From doing my own experiments, I have found that when I create a tensor: h=torch.randn(5,12,5) And then put a convolutional layer on it defined as follows: conv=torch.nn.Conv1d(12...
For a conv2D, input should be in (N, C, H, W) format. N is the number of samples/batch_size. C is the channels. H and W are height and width resp. See shape documentation at https://pytorch.org/docs/stable/nn.html#torch.nn.Conv2d For conv1D, input should be (N,C,L) see documentation at https://pytorch.org/docs/stable...
https://stackoverflow.com/questions/51541532/
Implementing a custom dataset with PyTorch
I'm attempting to modify this feedforward network taken from https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/01-basics/feedforward_neural_network/main.py to utilize my own dataset. I define a custom dataset of two 1 dim arrays as input and two scalars the corresponding output : x = torch.tensor([[5...
You need to change input_size to 4 (2*2), and not 2 as your modified code currently shows. If you compare it to the original MNIST example, you'll see that input_size is set to 784 (28*28) and not just to 28.
https://stackoverflow.com/questions/51545026/
How to make a class in pytorch use GPU
So I am running some code and getting the following error in Pytorch: "RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.FloatTensor) should be the same" From what I understand, this means that my model may not be pushed to the GPU, while the input data already is using the GPU. I can share my c...
You have to define the child modules inside the __init__ function so that they can be registered as parameters of the module. If they are not parameters, .cuda() would not be call on them when you call .cuda() for the parent. If you really needed dynamic parameters/modules declaration, take a look here. The key is apa...
https://stackoverflow.com/questions/51549461/
How to progressively grow a neural network in pytorch?
I am trying to make a progressive autoencoder and I have thought a couple ways of growing my network during training. However, I am always stuck on this one part where I don't know if changing the input(encoder) and output(decoder) channel would affect my network. See the example below. X = torch.randn( 8, 1, 4, 4,) #...
By progressive autoencoder I assume you are referring to something like Pioneer Networks: Progressively Growing Generative Autoencoder which referred Progressive Growing of GANs for Improved Quality, Stability, and Variation. First of all, don't use nn.Sequential. It is great for modeling simple and direct network str...
https://stackoverflow.com/questions/51549878/
Issues with using cuda and float tensor
I have some code, and when I run it, I get the following error: Expected object of type torch.cuda.FloatTensor but found type torch.FloatTensor for argument #2 'other' From this error message, I assume there a problem with pushing my models to the GPU. However, I am not sure precisely where the problem lies. I will ...
self.c and self.h were not cuda! I guess you really have to make sure that each tensor is using cuda. I just put .cuda() at the end of self.c and self.h's computation in the compute() method.
https://stackoverflow.com/questions/51562323/
How do I load custom image based datasets into Pytorch for use with a CNN?
I have searched for hours on the internet to find a good solution to my issue. Here is some relevant background information to help you answer my question. This is my first ever deep learning project and I have no idea what I am doing. I know the theory but not the practical elements. The data that I am using can be ...
Looking at the data from Kaggle and your code, there are problems in your data loading. The data should be in a different folder per class label for PyTorch ImageFolder to load it correctly. In your case, since all the training data is in the same folder, PyTorch is loading it as one train set. You can correct this by...
https://stackoverflow.com/questions/51577282/
Data loading with variable batch size?
I am currently working on patch based super-resolution. Most of the papers divide an image into smaller patches and then use the patches as input to the models.I was able to create patches using custom dataloader. The code is given below: import torch.utils.data as data from torchvision.transforms import CenterCrop, T...
The following code snippet works for your purpose. First, we define a ToyDataset which takes in a list of tensors (tensors) of variable length in dimension 0. This is similar to the samples returned by your dataset. import torch from torch.utils.data import Dataset from torch.utils.data.sampler import RandomSampler...
https://stackoverflow.com/questions/51585298/
Linear regression with pytorch
I tried to run linear regression on ForestFires dataset. Dataset is available on Kaggle and gist of my attempt is here: https://gist.github.com/Chandrak1907/747b1a6045bb64898d5f9140f4cf9a37 I am facing two problems: Output from prediction is of shape 32x1 and target data shape is 32. input and target shapes ...
Problem 1 This is reference about MSELoss from Pytorch docs: https://pytorch.org/docs/stable/nn.html#torch.nn.MSELoss Shape: - Input: (N,∗) where * means, any number of additional dimensions - Target: (N,∗), same shape as the input So, you need to expand dims of labels: (32) -> (32,1), by using: torch.unsqueeze(l...
https://stackoverflow.com/questions/51586680/
Why doesn't my simple pytorch network work on GPU device?
I built a simple network from a tutorial and I got this error: RuntimeError: Expected object of type torch.cuda.FloatTensor but found type torch.FloatTensor for argument #4 'mat1' Any help? Thank you! import torch import torchvision device = torch.device("cuda:0") root = '.data/' dataset = torchvision.datase...
TL;DR This is the fix inputs = inputs.to(device) Why?! There is a slight difference between torch.nn.Module.to() and torch.Tensor.to(): while Module.to() is an in-place operator, Tensor.to() is not. Therefore net.to(device) Changes net itself and moves it to device. On the other hand inputs.to(device) does n...
https://stackoverflow.com/questions/51605893/
Understanding PyTorch prediction
For my trained model this code : model(x[0].reshape(1,784).cuda()) returns : tensor([[-1.9903, -4.0458, -4.1143, -4.0074, -3.5510, 7.1074]], device='cuda:0') My network model is defined as : # Hyper-parameters input_size = 784 hidden_size = 50 num_classes = 6 num_epochs = 5000 batch_size = 1 learning_rate =...
Disclaimer: I don't really know pytorch, but i'm guessing based on other libraries and general standard practice as i know it. I believe it's the outputs of the last layer, which would be that fc2 linear transformation. So, the predicted category would be category 5, having the highest value. You could think of it a...
https://stackoverflow.com/questions/51620964/
PyTorch: passing numpy array for weight initialization
I'd like to initialize the parameters of RNN with np arrays. In the following example, I want to pass w to the parameters of rnn. I know pytorch provides many initialization methods like Xavier, uniform, etc., but is there way to initialize the parameters by passing numpy arrays? import numpy as np import torch as nn...
First, let's note that nn.RNN has more than one weight variable, c.f. the documentation: Variables: weight_ih_l[k] – the learnable input-hidden weights of the k-th layer, of shape (hidden_size * input_size) for k = 0. Otherwise, the shape is (hidden_size * hidden_size) weight_hh_l[k] – the learnable...
https://stackoverflow.com/questions/51628607/
Pytorch: NN function approximator, 2 in 1 out
[Please be aware of the Edit History below, as the major problem statement has changed.] We are trying to implement a neural network in pytorch, that approximates a function f(x,y)=z. So there are two real numbers as input and one as ouput, we therefore want 2 nodes in the input layer and one in the output layer. We c...
It should be interesting for you to point out the differences between torch.nn and torch.nn.functional (see here). Essentially, it might be that your backpropagation graph might be executed not 100% correct due to a different specification. As pointed out by previous commenters, I would suggest to define your layers i...
https://stackoverflow.com/questions/51631155/
Model taking long time to train
I have added an LSTM layer after a convolution in the VGG-16 model using PyTorch. Overtime, the model learns just fine. However, after adding just one LSTM layer, which consists of 32 LSTM cells, the process of training and evaluating takes about 10x longer. I added the LSTM layer to a VGG framework as follows def ma...
Yes, since LSTM (and many other RNNs) rely on sequential feeding of information you lose a big portion of parallelization speed ups you generally have with CNNs. There are other types of RNNs you can explore that leverage more parallelizable algorithms but the verdict on their predictive performance compared to LSTM/GR...
https://stackoverflow.com/questions/51637854/
How do you change require_grad to false for each parameters in your model in pytorch?
My code is below which I thought would do what I want but the output shows require_grad didn't change to false. import torch import torch.nn as nn encoder = nn.Sequential( nn.Conv2d(1, 4, 1), nn.Sigmoid()) for params in encoder.parameters(): params.require_grad = False print(params.requires_grad) # prints t...
You just have a typo :) Simply add an s at the end of grad in params.require_grad = False Change this to params.requires_grad = False (note the added s) Typos can be hard to catch sometimes ;)
https://stackoverflow.com/questions/51638932/
Cloud Storage Buckets for PyTorch
For a particular task I'm working on I have a dataset that is about 25 GB. I'm still experimenting with several methods of preprocessing and definitely don't have my data to it's final form yet. I'm not sure what the common workflow is for this sort of problem, so here is what I'm thinking: Copy dataset from bucket s...
On the billing side, the charges would be the same, as the fuse operations are charged like any other Cloud Storage interface according to the documentation. In your use case I don’t know how you are going to train the data, but if you do more than one operation to files it would be better to have them downloaded, trai...
https://stackoverflow.com/questions/51639141/
Can a Neural Network learn a simple interpolation?
I’ve tried to train a 2 layer neural network on a simple linear interpolation for a discrete function, I’ve tried lots of different learning rates as well as different activation functions, and it seems like nothing is being learned! I’ve literally spent the last 6 hours trying to debug the following code, but it seem...
Although your problem is quite simple, it is poorly scaled: x ranges from 255 to 200K. This poor scaling leads to numerical instability and overall makes the training process unnecessarily unstable. To overcome this technical issue, you simply need to scale your inputs to [-1, 1] (or [0, 1]) range. Note that this scal...
https://stackoverflow.com/questions/51640064/
pytorch how to remove cuda() from tensor
I got TypeError: expected torch.LongTensor (got torch.cuda.FloatTensor). How do I convert torch.cuda.FloatTensor to torch.LongTensor? Traceback (most recent call last): File "train_v2.py", line 110, in <module> main() File "train_v2.py", line 81, in main model.update(batch) File "/home/Desktop/...
You have a float tensor f and want to convert it to long, you do long_tensor = f.long() You have cuda tensor i.e data is on gpu and want to move it to cpu you can do cuda_tensor.cpu(). So to convert a torch.cuda.Float tensor A to torch.long do A.long().cpu()
https://stackoverflow.com/questions/51664192/
Data Augmentation in PyTorch
I am a little bit confused about the data augmentation performed in PyTorch. Now, as far as I know, when we are performing data augmentation, we are KEEPING our original dataset, and then adding other versions of it (Flipping, Cropping...etc). But that doesn't seem like happening in PyTorch. As far as I understood from...
The transforms operations are applied to your original images at every batch generation. So your dataset is left unchanged, only the batch images are copied and transformed every iteration. The confusion may come from the fact that often, like in your example, transforms are used both for data preparation (resizing/cr...
https://stackoverflow.com/questions/51677788/
AttributeError: 'Image' object has no attribute 'new' occurs when trying to use Pytorchs AlexNet Lighting preprocessing
I tried to train my model on ImageNet using inception and Alexnet like preprocessing. I used Fast-ai imagenet training script provided script. Pytorch has support for inception like preprocessing but for AlexNets Lighting, we have to implement it ourselves : __imagenet_pca = { 'eigval': torch.Tensor([0.2175, 0.0...
Thanks to @iacolippo's comment, I finally found the cause! Unlike the example I wrote here, in my actual script, I had used transforms.ToTensor() after the lighting() method. Doing so resulted in a PIL image being sent as the input for lightining()which expects a Tensor and that's why the error occurs. So basically...
https://stackoverflow.com/questions/51685753/
CUDA runtime error (59) : device-side assert triggered
THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1524584710464/work/aten/src/THC/generated/../generic/THCTensorMathPointwise.cu line=265 error=59 : device-side assert triggered Traceback (most recent call last): File "main.py", line 109, in <module> train(loader_train, model, criterion, optimize...
In general, when encountering cuda runtine errors, it is advisable to run your program again using the CUDA_LAUNCH_BLOCKING=1 flag to obtain an accurate stack trace. In your specific case, the targets of your data were too high (or low) for the specified number of classes.
https://stackoverflow.com/questions/51691563/
Best way to bound outputs from neural networks on reinforcement learning
I am training a neural network (feedforward, Tanh hidden layers) that receives states as inputs and gives actions as outputs. I am following the REINFORCE algorithm for policy-gradient reinforcement learning. However, I need my control actions to be bounded (let us say from 0-5). Currently the way I am doing this is b...
Have you considered using nn.ReLU6()? This is a bounded version of the rectified linear unit, which output is defined as out = min( max(x, 0), 6)
https://stackoverflow.com/questions/51693567/
How to construct a network with two inputs in PyTorch
Suppose I want to have the general neural network architecture: Input1 --> CNNLayer \ ---> FCLayer ---> Output / Input2 --> FCLayer Input1 is image data, input2 is non-image data. I have implemented this architecture in Tensorflow. All pytorc...
By "combine them" I assume you mean to concatenate the two inputs. Assuming you concat along the second dimension: import torch from torch import nn class TwoInputsNet(nn.Module): def __init__(self): super(TwoInputsNet, self).__init__() self.conv = nn.Conv2d( ... ) # set up your layer here self.fc1 = n...
https://stackoverflow.com/questions/51700729/
Issue with running a single prediction with PyTorch
I have a trained model using PyTorch now I want to simpy run it on one example >>> model nn.Sequential { [input -> (0) -> (1) -> (2) -> (3) -> (4) -> (5) -> (6) -> (7) -> (8) -> (9) -> (10) -> output] (0): nn.SpatialConvolutionMap (1): nn.Tanh (2): nn.SpatialMaxPoo...
It seems like your model is not nn.Sequential (pytorch Sequential), but rather torch.legacy.nn.Sequential (a legacy lua torch model). Try using this model forward() explicitly: output = model.forward(inp[None, ...]) # don't forget to add "batch" dimension
https://stackoverflow.com/questions/51701908/
Make personnal Dataloader with PYTORCH
I'm searching to create a personnal dataloader with a specific format to use Pytorch library, someone have an idea how can I do it ? I have follow Pytorch Tutorial but I don't find my answer! I need a DataLoader that yields the tuples of the following format: (Bx3xHxW FloatTensor x, BxHxW LongTensor y, BxN Lon...
You simply need to have a database derived from torch.utils.data.Dataset, where __getitem__(index) returns a tuple (x, y, y_cls) of the types you want, pytorch will take care of everything else. from torch.utils import data class MyTupleDataset(data.Dataset): def __init__(self): super(MyTupleDataset, self).__in...
https://stackoverflow.com/questions/51702669/
Pytorch tensor - How to get the indexes by a specific tensor
I have a tensor t = torch.tensor([[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0]]) and a query tensor q = torch.tensor([1, 0, 0, 0]) Is there a way to get the indexes of q like indexes = t.index(q) # get back [0, 3] in pytorch?
How about In [1]: torch.nonzero((t == q).sum(dim=1) == t.size(1)) Out[1]: tensor([[ 0], [ 3]]) Comparing t == q performs element-wise comparison between t and q, since you are looking for entire row match, you need to .sum(dim=1) along the rows and see what row is a perfect match == t.size(1). As of v0.4...
https://stackoverflow.com/questions/51703981/
Bidirectional RNN cells - shared or not?
Should I use the same weights to compute forward and backward passes in a bidirectional RNN, or should those weights be learned independently?
They should be learned independently as they learn different patterns, unless you have palindromes. In fact that is the default in the Bidirectional wrapper in Keras: self.forward_layer = copy.copy(layer) config = layer.get_config() config['go_backwards'] = not config['go_backwards'] self.backward_layer = layer.__clas...
https://stackoverflow.com/questions/51714462/
Why is it in Pytorch when I make a COPY of a network's weight it would be automatically updated after back-propagation?
I wrote the following code as a test because in my original network I use a ModuleDict and depends on what index I feed it would slice and train only parts of that network. I wanted to make sure that only the sliced layers would update their weight so I wrote some test code to double check. Well I am getting some weir...
You have to clone the parameters, otherwise you just copy the reference. weights = [] for param in model.parameters(): weights.append(param.clone()) criterion = nn.BCELoss() # criterion and optimizer setup optimizer = optim.Adam(model.parameters(), lr=0.001) foo = torch.randn(3, 10) # fake input target = torch....
https://stackoverflow.com/questions/51717874/
Skorch training object from scratch
I'm trying to use skorch class to execut GridSearch on a classifier. I tried running with the vanilla NeuralNetClassifier object, but I haven't found a way to pass the Adam optimizer only the trainable weights (I'm using pre-trained embeddings and I would like to keep them frozen). It's doable if a module is initializ...
but module needs an uninitialized model That is not correct, you can pass an initialized model as well. The documentation of the model parameter states: It is, however, also possible to pass an instantiated module, e.g. a PyTorch Sequential instance. The problem is that when passing an initialized model you...
https://stackoverflow.com/questions/51730294/
Where do I get a CPU-only version of PyTorch?
I'm trying to get a basic app running with Flask + PyTorch, and host it on Heroku. However, I run into the issue that the maximum slug size is 500mb on the free version, and PyTorch itself is ~500mb. After some google searching, someone wrote about finding a cpu-only version of PyTorch, and using that, which is much ...
Per the Pytorch website, you can install pytorch-cpu with conda install pytorch-cpu torchvision-cpu -c pytorch You can see from the files on Anaconda cloud, that the size varies between 26 and 56MB depending on the OS where you want to install it. You can get the wheel from http://download.pytorch.org/whl/cpu/. The...
https://stackoverflow.com/questions/51730880/
How to include batch size in pytorch basic example?
I am new to pytorch. The following is the basic example of using nn module to train a simple one-layer model with some random data (from here) import torch N, D_in, H, D_out = 64, 1000, 100, 10 x = torch.randn(N, D_in) y = torch.randn(N, D_out) model = torch.nn.Sequential( torch.nn.Linear(D_in, H), torch.nn....
In fact N is the batch size. So you just need to modify N currently its set to 64. So you have in every training batch 64 vectors with size / dim D_in. I checked the link you posted, you can also take a look at the comments - there is some explanation too :) # -*- coding: utf-8 -*- import numpy as np # N is batch si...
https://stackoverflow.com/questions/51735001/
Is .data still useful in pytorch?
I'm new to pytorch. I read much pytorch code which heavily uses tensor's .data member. But I search .data in the official document and Google, finding little. I guess .data contains the data in the tensor, but I don't know when we need it and when not?
.data was an attribute of Variable (object representing Tensor with history tracking e.g. for automatic update), not Tensor. Actually, .data was giving access to the Variable's underlying Tensor. However, since PyTorch version 0.4.0, Variable and Tensor have been merged (into an updated Tensor structure), so .data dis...
https://stackoverflow.com/questions/51743214/
pytorch how to set .requires_grad False
I want to set some of my model frozen. Following the official docs: with torch.no_grad(): linear = nn.Linear(1, 1) linear.eval() print(linear.weight.requires_grad) But it prints True instead of False. If I want to set the model in eval mode, what should I do?
requires_grad=False If you want to freeze part of your model and train the rest, you can set requires_grad of the parameters you want to freeze to False. For example, if you only want to keep the convolutional part of VGG16 fixed: model = torchvision.models.vgg16(pretrained=True) for param in model.features.paramete...
https://stackoverflow.com/questions/51748138/
PyTorch - Effect of normal() initialization on gradients
Suppose I have a neural network where I use a normal distribution initialization and I want to use the mean value which is used for initialization as a parameter of the network. I have a small example: import torch parameter_vector = torch.tensor(range(10), dtype=torch.float, requires_grad=True) sigma = torch.ones(pa...
Thanks to @iacolippo (see comments below the question) the problem is solved now. I just wanted to supplement this by posting what code I am using now, so this may help anyone else. As presumed in the question and also stated by @iacolippo the code posted in the question is not backpropable: import torch parameter_vect...
https://stackoverflow.com/questions/51751231/
How to re-use old weights in a slightly modified model?
I have a CNN network built like this for a particular task. class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv11 = nn.Conv2d(1, 128, kernel_size=3, padding=1) self.conv12 = nn.Conv2d(128, 256, kernel_size=3, padding=1) self.conv13 = nn.Conv2d(256, 2...
Assume you trained the following model and now you make a minor modification to it (like adding a layer) and want to use your trained weights import torch import torch.nn as nn import torch.optim as optim class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv11 = nn.Conv2d...
https://stackoverflow.com/questions/51754789/
How do I turn a Pytorch Dataloader into a numpy array to display image data with matplotlib?
I am new to Pytorch. I have been trying to learn how to view my input images before I begin training on my CNN. I am having a very hard time changing the images into a form that can be used with matplotlib. So far I have tried this: from multiprocessing import freeze_support import torch from torch import nn import ...
First of all, dataloader output 4 dimensional tensor - [batch, channel, height, width]. Matplotlib and other image processing libraries often requires [height, width, channel]. You are right about using the transpose, just not in the right way. There will be a lot of images in your images so first you need to pick one...
https://stackoverflow.com/questions/51756581/
In pytorch how do you use add_param_group () with a optimizer?
The documentation is pretty vague and there aren't example codes to show you how to use it. The documentation for it is Add a param group to the Optimizer s param_groups. This can be useful when fine tuning a pre-trained network as frozen layers can be made trainable and added to the Optimizer as training ...
Per the docs, the add_param_group method accepts a param_group parameter that is a dict. Example of use: import torch import torch.optim as optim w1 = torch.randn(3, 3) w1.requires_grad = True w2 = torch.randn(3, 3) w2.requires_grad = True o = optim.Adam([w1]) print(o.param_groups) gives [{'amsgrad': False, 'be...
https://stackoverflow.com/questions/51756913/
Why does pytorch F.mse_loss behave differently w.r.t. Tensor and Parameter?
Below is my code: import torch as pt from torch.nn import functional as F a = pt.Tensor([[0, 1], [2, 3]]) b = pt.Tensor([[1, 0], [5, 4]]) print(F.mse_loss(a, b), F.mse_loss(a, b, reduction='elementwise_mean')) a = pt.nn.Parameter(a) b = pt.nn.Parameter(b) print(F.mse_loss(a, b), F.mse_loss(a, b, reduction='elementwi...
It is a bug according to pytorch forum.
https://stackoverflow.com/questions/51759566/
Is it possible to create a FIFO queue with pyTorch?
I need to create a fixed length Tensor in pyTorch that acts like a FIFO queue. I have this fuction to do it: def push_to_tensor(tensor, x): tensor[:-1] = tensor[1:] tensor[-1] = x return tensor For example, I have: tensor = Tensor([1,2,3,4]) >> tensor([ 1., 2., 3., 4.]) then using the funct...
I implemented another FIFO queue: def push_to_tensor_alternative(tensor, x): return torch.cat((tensor[1:], Tensor([x]))) The functionality is the same, but then I checked their performance in speed: # Small Tensor tensor = Tensor([1,2,3,4]) %timeit push_to_tensor(tensor, 5) >> 30.9 µs ± 1.26 µs per loop ...
https://stackoverflow.com/questions/51761806/
pytorch skip connection in a sequential model
I am trying to wrap my head around skip connections in a sequential model. With the functional API I would be doing something as easy as (quick example, maybe not be 100% syntactically correct but should get the idea): x1 = self.conv1(inp) x = self.conv2(x) x = self.conv3(x) x = self.conv4(x) x = self.deconv4(x) x = ...
Your observations are correct, but you may have missed the definition of UnetSkipConnectionBlock.forward() (UnetSkipConnectionBlock being the Module defining the U-Net block you shared), which may clarify this implementation: (from pytorch-CycleGAN-and-pix2pix/models/networks.py#L259) # Defines the submodule with sk...
https://stackoverflow.com/questions/51773208/
Pytorch trying to make a NN received an invalid combination of arguments
I am trying to build my first NN with pytroch and got an issue. TypeError: new() received an invalid combination of arguments - got (float, int, int, int), but expected one of: * (torch.device device) * (torch.Storage storage) * (Tensor other) * (tuple of ints size, torch.device device) * (object dat...
You might have to look out as to what you are passing to your convolutional layers in the Residual class. Per default, Python 3 will convert any division operation into a float variable. Try casting your variables back to an integer, and see if that helps. Fixed code for Residual: class Residual(nn.Module): #set the ...
https://stackoverflow.com/questions/51780251/
Understanding Bilinear Layers
When having a bilinear layer in PyTorch I can't wrap my head around how the calculation is done. Here is a small example where I tried to figure out how it works: In: import torch.nn as nn B = nn.Bilinear(2, 2, 1) print(B.weight) Out: Parameter containing: tensor([[[-0.4394, -0.4920], [ 0.6137, 0.4174]]...
The operation done by nn.Bilinear is B(x1, x2) = x1*A*x2 + b (c.f. doc) with: A stored in nn.Bilinear.weight b stored in nn.Bilinear.bias If you take into account the (optional) bias, you should obtain the expected results. import torch import torch.nn as nn def manual_bilinear(x1, x2, A, b): return torch.m...
https://stackoverflow.com/questions/51782321/
Torchtext TabularDataset: data.Field doesn't contain actual imported data?
I learned from the Torchtext documentation that the way to import csv files is through TabularDataset. I did it like this: train = data.TabularDataset(path='./data.csv', format='csv', fields=[("label",data.Field(use_vocab=True,include_lengths=False)), ...
The fields must be defined separately like this TEXT = data.Field(sequential=True,tokenize=tokenize, lower=True, include_lengths=True) LABEL = data.Field(sequential=True,tokenize=tokenize, lower=True) train = data.TabularDataset(path='./data.csv', format='csv', ...
https://stackoverflow.com/questions/51790509/
How to apply layer-wise learning rate in Pytorch?
I know that it is possible to freeze single layers in a network for example to train only the last layers of a pre-trained model. What I’m looking for is a way to apply certain learning rates to different layers. So for example a very low learning rate of 0.000001 for the first layer and then increasing the learning ...
Here is the solution: from torch.optim import Adam model = Net() optim = Adam( [ {"params": model.fc.parameters(), "lr": 1e-3}, {"params": model.agroupoflayer.parameters()}, {"params": model.lastlayer.parameters(), "lr": 4e-2}, ], lr=5e-4, ) Other parameters that are didn't spec...
https://stackoverflow.com/questions/51801648/
What exactly is the definition of a 'Module' in PyTorch?
Please excuse the novice question, but is Module just the same as saying model? That's what it sounds like, when the documentation says: Whenever you want a model more complex than a simple sequence of existing Modules you will need to define your model (as a custom Module subclass). Or... when they mention Modu...
It's a simple container. From the docs of nn.Module Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes. Submodules assigned in this way will be...
https://stackoverflow.com/questions/51804692/
TypeError: tensor is not a torch image
While working through the AI course at Udacity I came across this error during the Transfer Learning section. Here is the code that seems to be causing the trouble: import torch from torch import nn from torch import optim import torch.nn.functional as F from torchvision import datasets, transforms, models data_dir =...
The problem is with the order of the transforms. The ToTensor transform should come before the Normalize transform, since the latter expects a tensor, but the Resize transform returns an image. Correct code with the faulty lines changed: train_transforms = transforms.Compose([ transforms.Resize((224,224)), tr...
https://stackoverflow.com/questions/51807040/
Is GEMM or BLAS used in Tensorflow, Theano, Pytorch
I know that Caffe uses GEneral Matrix to Matrix Multiplication (GEMM) which is part of Basic Linear Algebra Subprograms (BLAS) library for performing convolution operations. Where a convolution is converted to matrix multiplication operation. I have referred below article. https://petewarden.com/2015/04/20/why-gemm-is-...
tensorflow has multiple alternatives for the operations. for GPU, cuda support is used. Most of the operations are implemented with cuDNN, some use cuBLAS, and others use cuda. You can also use openCL instead of cuda, but you should compile tensorflow by yourself. for CPU, intel mkl is used as the blas library. I'm...
https://stackoverflow.com/questions/51814148/
Pytorch RuntimeError: "host_softmax" not implemented for 'torch.cuda.LongTensor'
I am using pytorch for training models. But I got an runtime error when it was computing the cross-entropy loss. Traceback (most recent call last): File "deparser.py", line 402, in <module> d.train() File "deparser.py", line 331, in train total, correct, avgloss = self.train_util() File "deparser....
I know where the problem is. y should be in torch.int64 dtype without one-hot encoding. And CrossEntropyLoss() will auto encoding it with one-hot (while out is the probability distribution of prediction like one-hot format). It can run now!
https://stackoverflow.com/questions/51818225/
Why the loss function can be apply on different size tensors
For example, I have a net that take tensor [N, 7](N is the samples num) as input and tensor [N, 4] as output, the “4” represents the different classes’ probabilities. And the training data’s labels are the form of tensor [N], from range 0 to 3(represent the ground-truth class). Here’s my question, I’ve seen some demo...
In PyTorch the implementation is: Link to the Documentation: https://pytorch.org/docs/stable/nn.html#torch.nn.CrossEntropyLoss So implementing this formula in pytorch you get: import torch import torch.nn.functional as F output = torch.tensor([ 0.1998, -0.2261, -0.0388, 0.1457]) target = torch.LongTensor([1]) # im...
https://stackoverflow.com/questions/51822974/
How to print a tensor without showing gradients
If I do something like this: tmp = torch.ones(3, 2, 2, requires_grad=True) out = tmp ** 2 print("\n{}".format(out)) I get as an output: tensor([[[1., 1.], [1., 1.]], [[1., 1.], [1., 1.]], [[1., 1.], [1., 1.]]], grad_fn=<PowBackward0>) I would like to print out ju...
Using the data should do the job for you: tmp = torch.ones(3, 2, 2, requires_grad=True) out = tmp ** 2 print("\n{}".format(out.data)) Output: tensor([[[1., 1.], [1., 1.]], [[1., 1.], [1., 1.]], [[1., 1.], [1., 1.]]])
https://stackoverflow.com/questions/51828551/
PyTorch LSTM States
Consider the following code snipped: lstm = nn.LSTM(10, 5, batch_first=True) states = (torch.rand(1, 1, 5), torch.rand(1, 1, 5)) h, states = lstm(torch.rand(1, 1, 10), states) print('h:') print(h) print('states[0]:') print(states[0]) Output: h: tensor([[[0.2808, 0.3357, 0.1290, 0.1413, 0.2648]]], grad_fn=<Transp...
It's best practice and more intuitive to use h or (often called output) since states are meant to be passed into the lstm for internal use (think of tensorflow's dynamic_rnn to see why this would be the case. That said you are correct that it actually doesn't make a difference. I'm not sure why the grad_fns are differ...
https://stackoverflow.com/questions/51845675/
pytorch .stack final shape after .squeeze
I had a pandas dataframe 200 columns by 2500 rows which I made it into a tensor tensor = torch.tensor(df.values) tensor.size() => ([2500,200]) which i chunked and enumerated list=[] for i,chunk in enumerate(tensor.chunk(100,dim=0)) chunk.size =>([25,200]) output = hiddenlayer(chunks) output.size(...
Renaming list to tensor_list since it's bad practice to use reserved keywords as variable names. tensor_list =[] for i,chunk in enumerate(tensor.chunk(100,dim=0)): output = hiddenlayer(chunk).squeeze() tensor_list.append(output) result = torch.reshape(torch.stack(tensor_list,0), (-1, 1)) result.size() shoul...
https://stackoverflow.com/questions/51851966/
Parsing CSV into Pytorch tensors
I have a CSV files with all numeric values except the header row. When trying to build tensors, I get the following exception: Traceback (most recent call last): File "pytorch.py", line 14, in <module> test_tensor = torch.tensor(test) ValueError: could not determine the shape of object type 'DataFrame' T...
Try converting it to an array first: test_tensor = torch.Tensor(test.values)
https://stackoverflow.com/questions/51858067/
pip - Installing specific package version does not work
I was trying to install a library (allennlp) via pip3. But it complained about the PyTorch version. While allennlp requires torch=0.4.0 I have torch=0.4.1: ... Collecting torch==0.4.0 (from allennlp) Could not find a version that satisfies the requirement torch==0.4.0 (from allennlp) (from versions: 0.1.2, 0.1.2.pos...
allennlp master branch specifies torch>=0.4.0,<0.5.0. The latest release is v0.6.0 - released only about 3 hours ago - and also specifies this range: https://github.com/allenai/allennlp/blob/v0.6.0/setup.py#L104 It's possible you are using an older release (probably v0.51) which pinned torch==0.4.0: https://g...
https://stackoverflow.com/questions/51860628/
pytorch (numpy) calculation about the closest pixels to points
I am trying to solve a complicated problem. For example, I have a batch of 2D predicted images (softmax output, value between 0 and 1) with size: Batch x H x W and ground truth Batch x H x W The light gray color pixels are the background with value 0, and the dark gray color pixels are the foreground with value 1. ...
As suggested by @Matin, you could consider Bresenham's algorithm to get your points on the AC line. A simplistic PyTorch implementation could be as follows (directly adapted from the pseudo-code here ; could be optimized): import torch def get_points_from_low(x0, y0, x1, y1, num_points=3): dx = x1 - x0 dy = ...
https://stackoverflow.com/questions/51873797/
Expected parameters of Conv2d
Below code : import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import torch.utils.data as data_utils import numpy as np train_dataset = [] mu, sigma = 0, 0.1 # mean and standard deviation num_instances = 20 batch_size_value = 10 for i in range(num_instances) : ima...
The error comes from your final fully-connected layer self.fc = nn.Linear(7*7*32, num_classes), not your convolution ones. Given your input dimensions ((10, 100)), the shape of out = self.layer2(out) is (batch_size, 32, 25, 2), and thus the shape of out = out.reshape(out.size(0), -1) is (batch_size, 32*25*2) = (batch_...
https://stackoverflow.com/questions/51885408/
Custom NN architecture using Pytorch
I am trying to make a custom CNN architecture using Pytorch. I want to have about the same control as what I would get if I make the architecture using numpy only. I am new to Pytorch and would like to see some code samples of CNNs implemented without the nn.module class, if possible.
You have to implement backward() function in your custom class. However from your question it is not clear whether your need just a new series of CNN block (so you better use nn.module and something like nn.Sequential(nn.Conv2d( ...) ) you just need gradient descent https://github.com/jcjohnson/pytorch-examples...
https://stackoverflow.com/questions/51893903/
Pytorch LSTM - Training for Q&A classification
I'm trying to train a model to classify if an answer answers the question given using this dataset. I'm training in batches and using GloVe word embeddings. I train in batches of 1000 except the last one. The method I'm trying to use is to first giving the first sentence (question), and then the second sentence (answe...
I would suggest to encode question and answer independently and put a classifier on top of it. For example, you can encode with biLSTM question and answer, concatenate their representations and feed to the classifier. The code could be something like this (not tested, but hope you got the idea): class QandA(nn.Module)...
https://stackoverflow.com/questions/51895142/
Get values of tensors in loss function
I would like to get the values of the y_pred and y_true tensors of this keras backend function. I need this to be able to perform some custom calculations and change the loss, these calculations are just possible with the real array values. def mean_squared_error(y_true, y_pred): #some code here return K.mean(...
No, in general you can't compute the loss that way, because Keras is based on frameworks that do automatic differentiation (like Theano, TensorFlow) and they need to know which operations you are doing in between in order to compute the gradients of the loss. You need to implement your loss computations using keras.ba...
https://stackoverflow.com/questions/51901952/