instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Pytorch NN and communication between classes
I am new at python, and pytorch, and I have a problem understanding how it works. import torch.nn as nn import torch.nn.functional as F import torch.optim as optim class Net(nn.Module): def __init__(self): .. def forward(self, x): .. return x net...
A) By setting it as a variable in one spot it helps make it easier to change the loss function in one location as opposed to having to type nn.MSELoss in many places as the code increases in size and complexity. Less likely to make errors basically. As for the error one would need more information to answer that bool ...
https://stackoverflow.com/questions/54063220/
How to customize number of multiple hidden layer units in pytorch LSTM?
In pytorch LSTM, RNN or GRU models, there is a parameter called "num_layers", which controls the number of hidden layers in an LSTM. I wonder that since there are multiple layers in an LSTM, why the parameter "hidden_size" is only one number instead of a list containing the number of hidden states in multiple layers, l...
Seems that I've found a solution to this, which is to use LSTMCell instead. Helpful links: [1], [2]. But is there an easier way?
https://stackoverflow.com/questions/54075230/
How to set the environment default python in anaconda?
It makes me crazy, In anaconda I create the environment with the defualt iterpreter python3.4 Next I install pytorch 0.4.1 conda install pytorch=0.4.1 cuda80 -c pytorch After this I found that the pytorch was installed in python3.6! And the environment defualt interpreter is chaged from python3.4 to python3.6. I...
As you can see here there is no version of pytorch for python3.4... The default version of pytorch is for python3.6 and that is the version you installed installed. In the process anaconda prompts you that it will have to upgrade/downgrade some package versions and there is probably the the line in which it says it wil...
https://stackoverflow.com/questions/54075383/
Efficient PyTorch DataLoader collate_fn function for inputs of various dimensions
I'm having trouble writing a custom collate_fn function for the PyTorch DataLoader class. I need the custom function because my inputs have different dimensions. I'm currently trying to write the baseline implementation of the Stanford MURA paper. The dataset has a set of labeled studies. A study may contain more than...
Very interesting problem! If I understand you correctly (and also checking the abstract of the paper), you have 40,561 images from 14,863 studies, where each study is manually labeled by radiologists as either normal or abnormal. I believe the reason why you had the issue you faced was, say, for example, you created a ...
https://stackoverflow.com/questions/54083349/
How to train a L2-SVM classifier on top of a flattened vector of representations as per DCGAN paper
In the original DCGAN paper, the GAN is partly evaluated by being used as a feature extractor to classify CIFAR-10, after having been trained on Imagenet. From the paper: To evaluate the quality of the representations learned by DCGANs for supervised tasks, we train on Imagenet-1k and then use the discriminator’...
DCGAN would give you a 28672 dimenstional vector for each image. Hence the shape of the output of DCGAN woud be (50000,28672) for a complete CIFAR10 dataset. you have to take this as input for your sklearn SVM x, which as you mentioned takes a 2D data.
https://stackoverflow.com/questions/54091864/
Image similarity using Tensorflow or PyTorch
I want to compare two images for similarity. Since my purpose is to match a given image against a massive collection of images, I want to run the comparisons on GPU. I came across tf.image.ssim and tf.image.psnr functions but I am unable to find and working examples only. The solutions in PyTorch is also appreciated. ...
There is no implementation of PSNR or SSIM in PyTorch. You can either implement them yourself or use a third-party package, like piqa which I have developed. Assuming you already have torch and torchvision installed, you can get it with pip install piqa Then for the image comparison import torch from torchvision impo...
https://stackoverflow.com/questions/54091984/
ModuleNotFoundError: No module named 'torch.utils.serialization'
When I run a project used Pytorch I came up with this error: Traceback (most recent call last): File "train_drnet.py", line 10, in <module> import utils File "/home/muse/drnet-py/utils.py", line 18, in <module> from data.kth import KTH File "/home/muse/drnet-py/data/kth.py", line 7, in <module> from...
I think it was removed from Pytorch about a year ago, you can try tourch file instead - https://github.com/bshillingford/python-torchfile
https://stackoverflow.com/questions/54107156/
Having issues with neural network training. Loss not decreasing
I'm largely following this project but am doing a pixel-wise classification. I have 8 classes and 9 band imagery. My images are gridded into 9x128x128. My loss is not reducing and training accuracy doesn't fluctuate much. I'm guessing I have something wrong with the model. Any advice is much appreciated! I get at...
It's hard to debug your model with those informations, but maybe some of those ideas will help you in some way: Try to overfit your network on much smaller data and for many epochs without augmenting first, say one-two batches for many epochs. If this one doesn't work, than your model is not capable to model relation...
https://stackoverflow.com/questions/54116080/
How can I write the below equivalent code of Keras Neural Net in Pytorch?
How can I write the below equivalent code of Keras Neural Net in Pytorch? actor = Sequential() actor.add(Dense(20, input_dim=9, activation='relu', kernel_initializer='he_uniform')) actor.add(Dense(20, activation='relu')) actor.add(Dense(27, activation='softmax', kernel_initializer='he_uniform')...
Similiar questions have already been asked, but here it goes: import torch actor = torch.nn.Sequential( torch.nn.Linear(9, 20), # output shape has to be specified torch.nn.ReLU(), torch.nn.Linear(20, 20), # same goes over here torch.nn.ReLU(), torch.nn.Linear(20, 27), # and here torch.nn.S...
https://stackoverflow.com/questions/54125698/
pytorch grad is None after .backward()
I just installed torch-1.0.0 on Python 3.7.2 (macOS), and trying the tutorial, but the following code: import torch x = torch.ones(2, 2, requires_grad=True) y = x + 2 z = y * y * 3 out = z.mean() out.backward() print(out.grad) prints None which is not what's expected. What's the problem?
This is the expected result. .backward accumulate gradient only in the leaf nodes. out is not a leaf node, hence grad is None. autograd.backward also does the same thing autograd.grad can be used to find the gradient of any tensor w.r.t to any tensor. So if you do autograd.grad (out, out) you get (tensor(1.),) as ...
https://stackoverflow.com/questions/54150684/
When does PyTorch automatically cast Tensor dtype?
When does PyTorch automatically cast Tensor dtype? Why does it sometimes do it automatically and other times throws and error? For example this automatically casts c to be a float: a = torch.tensor(5) b = torch.tensor(5.) c = a*b a.dtype >>> torch.int64 b.dtype >>> torch.float32 c.dtype >...
It looks like the PyTorch team is working on those types of problems, see this issue. It seems like some basic upcasting is already implemented in 1.0.0 as per your example (probably for the overloaded operators, tried some others like '//' or addition and they work fine), did not find any proof of this though (like gi...
https://stackoverflow.com/questions/54155275/
pytorch autoencoder model evaluation fail
I am literally a beginner of PyTorch. I trained an autoencoder network so that I can plot the distribution of the latent vectors (the result of encoders). This is the code that I used for network training. import torch import torchvision from torch import nn from torch.utils.data import DataLoader from torchvision im...
Hi and welcome to the PyTorch community :D TL;DR Change model = torch.load(check_point) to model.load_state_dict(torch.load(check_point)). The only problem is with the line: model = torch.load(check_point) The way you saved the checkpoint was: torch.save(model.state_dict(), check_point_file) That is, you sav...
https://stackoverflow.com/questions/54166865/
How to implement current pytorch activation functions with parameters?
I am looking for a simple way to use an activation function which exist in the pytorch library, but using some sort of parameter. for example: Tanh(x/10) The only way I came up with looking for solution was implementing the custom function completely from scratch. Is there any better/more elegant way to do this? edi...
Instead of defining it as a specific function, you could inline it in a custom layer. For instance your solution could look like: import torch import torch.nn as nn class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(4, 10) self.fc2 = nn.Linear(10,...
https://stackoverflow.com/questions/54174054/
How to put datasets created by torchvision.datasets in GPU in one operation?
I’m dealing with CIFAR10 and I use torchvision.datasets to create it. I’m in need of GPU to accelerate the calculation but I can’t find a way to put the whole dataset into GPU at one time. My model need to use mini-batches and it is really time-consuming to deal with each batch separately. I've tried to put each mini-...
TL;DR You won't save time by moving the entire dataset at once. I don't think you'd necessarily want to do that even if you have the GPU memory to handle the entire dataset (of course, CIFAR10 is tiny by today's standards). I tried various batch sizes and timed the transfer to GPU as follows: num_workers = 1 # Se...
https://stackoverflow.com/questions/54174854/
How to iterate over layers in Pytorch
Let's say I have a network model object called m. Now I have no prior information about the number of layers this network has. How can create a for loop to iterate over its layer? I am looking for something like: Weight=[] for layer in m._modules: Weight.append(layer.weight)
Let's say you have the following neural network. import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 5x5 square convolution # kernel self.conv1 = nn.Con...
https://stackoverflow.com/questions/54203451/
Torch C++: API to check NAN
I am using libtorch C++. In python version we can easily check the value of a tensor by calling its numpy value, and in numpy we have np.isnan(). I was wondering if there is a built in function in libtorch C++ to check whether a tensor has any NAN value? Thanks, Afshin
Adding on to Fábio's answer (my reputation is too low to comment): If you actually want to use the information about NANs in an assert or if condition you need convert it from a torch::Tensor to a C++ bool like so torch::Tensor myTensor; // do something auto tensorIsNan = at::isnan(myTensor).any().item<bool>();...
https://stackoverflow.com/questions/54205116/
How to speed up the "ImageFolder" for ImageNet
I am in an university, and all the file system are in a remote system, wherever I log in with my account, I could aways access my home directory. even though I log into the GPU servers through SSH command. This is the condition where I employ the GPU servers to read data. Currently, I use the PyTorch to train ResNet f...
Why it takes so long? Setting up an ImageFolder can take a long time, especially when the images are stored on a slow remote disk. The reason for this latency is that the __init__ function for the dataset goes over all files in the image folders and check whether this file is an image file. For ImageNet that can take q...
https://stackoverflow.com/questions/54207204/
How to use multiple GPUs in pytorch?
I use this command to use a GPU. device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") But, I want to use two GPUs in jupyter, like this: device = torch.device("cuda:0,1" if torch.cuda.is_available() else "cpu")
Assuming that you want to distribute the data across the available GPUs (If you have batch size of 16, and 2 GPUs, you might be looking providing the 8 samples to each of the GPUs), and not really spread out the parts of models across difference GPU's. This can be done as follows: If you want to use all the available G...
https://stackoverflow.com/questions/54216920/
Unable to optimize function using pytorch
I am trying to write an estimator for a Structural Equation Model. So basically I start with the random parameters for the model B, gamma, phi_diag, psi. And using this I compute the implied covariance matrix sigma. And my optimization function f_ml is computed based on the sigma and the covariance matrix of the data S...
The problem is that the value of sigma wasn't getting computed in each iteration. Basically, the computation code needs to be moved in a function and it needs to be computed in every iteration.
https://stackoverflow.com/questions/54219691/
Saving/Loading models in AllenNLP package
I am trying to load an AllenNLP model weights. I could not find any documentation on how to save/load a whole model, so playing with weights only. from allennlp.nn import util model_state = torch.load(filename_model, map_location=util.device_mapping(-1)) model.load_state_dict(model_state) I modified my input corpus ...
There's a functionality in AllenNLP allowing to load or save a model. Have you followed the steps outlined in AllenNLP's tutorial? Below I pasted a snippet from the tutorial that might be of interest to you: # Here's how to save the model. with open("/tmp/model.th", 'wb') as f: torch.save(model.state_dict(), f) v...
https://stackoverflow.com/questions/54227872/
Order of layers in hidden states in PyTorch GRU return
This is the API I am looking at, https://pytorch.org/docs/stable/nn.html#gru It outputs: output of shape (seq_len, batch, num_directions * hidden_size) h_n of shape (num_layers * num_directions, batch, hidden_size) For GRU with more than one layers, I wonder how to fetch the hidden state of the last layer, should ...
The documentation nn.GRU is clear about this. Here is an example to make it more explicit: For the unidirectional GRU/LSTM (with more than one hidden layer): output - would contain all the output features of all the timesteps t h_n - would return the hidden state (at last timestep) of all layers. To get the hidden stat...
https://stackoverflow.com/questions/54242123/
Pytorch - Can not slice torchvision MNIST dataset
In Pytorch, when using torchvision's MNIST dataset, we can get a digit as follows: from torchvision import datasets, transforms from torch.utils.data import DataLoader, Dataset, TensorDataset tsfm = transforms.Compose([transforms.Resize((16, 16)), transforms.ToTensor(), ...
You can use torch.utils.data.Subset() to get an index based slice of a torch Dataset e.g: import torch.utils.data as data_utils indices = torch.arange(12,15) mnist_12to14 = data_utils.Subset(tr, indices)
https://stackoverflow.com/questions/54251798/
Transferring pretrained pytorch model to onnx
I am trying to convert pytorch model to ONNX, in order to use it later for TensorRT. I followed the following tutorial https://pytorch.org/tutorials/advanced/super_resolution_with_caffe2.html, but my kernel dies all the time. This is the code that I implemented. # Some standard imports import io import numpy as np ...
What is the output you get? It seems SuperResolution is supported with the export operators in pytorch as mentioned in the documentation Are you sure the input to your model is: x = torch.rand(1, 64, 256, 1600, requires_grad=True) That could be the variable that you used for training, since for deployment you run the ...
https://stackoverflow.com/questions/54254313/
Saving and Loading Pytorch Model Checkpoint for inference not working
I have a trained model using LSTM. The model is trained on GPU (On Google COLABORATORY). I have to save the model for inference; which I will run on CPU. Once trained, I saved the model checkpoint as follows: torch.save({'model_state_dict': model.state_dict()},'lstmmodelgpu.tar') And, for inference, I loaded the mod...
There are two things to be considered here. You mentioned that you're training your model on GPU and using it for inference on CPU, so u need to add a parameter map_location in load function passing torch.device('cpu'). There is a mismatch of state_dict keys (indicated in your ouput message), which might be caused by...
https://stackoverflow.com/questions/54261892/
ImportError: No module named 'torchvision.datasets.mnist'
Even after installing pytorch, this error is coming for this line. from torchvision import datasets
If you're using anaconda distribution, first install torchvision using: $ conda install -c conda-forge torchvision If the package is not installed, then it will be installed. Else, it will throw the message # All requested packages already installed. After this, try to import the torchvision.datasets as you m...
https://stackoverflow.com/questions/54274716/
Pytorch softmax along different masks without for loop
Say I have a vector a , with an index vector b of the same length. The indexs are in range 0~N-1, corresponding to N groups. How can I do softmax for every group without for loop? I'm doing some sort of attention operation here. The numbers for every group are not the same, so I can't reshape a to a matrix and use the...
Maybe this answer will have to change slightly based on a potential response to my comment, but I'm just going ahead and throwing in my two cents about Softmax. Generally, the formula for softmax is explained rather well in the PyTorch documentation, where we can see that this is a exponential of the current value, div...
https://stackoverflow.com/questions/54284077/
batch_size not match in torchtext BucketIterator
I have set batch_size equals to 64, but when i print out the train_batch and val_batch, the size is not equal to 64. The train data and val data are in the below format: First, i define TEXT and LABEL field. tokenize = lambda x: x.split() TEXT = data.Field(sequential=True, tokenize=tokenize) LABEL = data.Field(seq...
The returned batch size not always equal to batch_size. ex: you have 100 train data, batch_size is 64. The returned batch_size should be [64, 36]. Code: https://github.com/pytorch/text/blob/1c2ae32d67f7f7854542212b229cd95c85cf4026/torchtext/data/iterator.py#L255-L271
https://stackoverflow.com/questions/54307824/
Modification to Caffe VGG 16 to handle 1 channel images on PyTorch
I am converting a VGG16 network to be a Fully Convolutional network and also modifying the the input to accept a single channel image. The complete code for reproducibilty is given below. import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np import t...
You need your input shape to be Batch-Channel-Height-Width, which is 4D. In your case, you only have one channel so you "squeezed out" this singleton dimension, but pytorch does not like it! try im2arr = im2arr[np.newaxis, np.newaxis, :, :] # add singleton for the channles as well
https://stackoverflow.com/questions/54324844/
ML Model inputs and outputs analogy
As I learn more and more about ML (I am a mobile DEV) I'm starting to form an analogy in my head. I would like the communities opinion / validation. As a front end DEV you have a backend and an API that you can make requests to. The standard format for the inputs and outputs to the API is JSON. I'm running into a pro...
Assuming this "ML Model" is in the context of running an input through say a trained pytorch model's forward pass to get an output, the unified way to define inputs and outputs for an ML model are through Tensors. Tensors are essentially a multi-dimensional matrix containing elements of a single data type. Think mult...
https://stackoverflow.com/questions/54338081/
Confusion in understand python commands for deep learning
I recently started learning the deep learning with pytorch using this tutorial. I am having problem with these lines of code. Parameter train=True means it will take out the training data. But how much data does it take for the training 50%? How can we specify the amount of data for training. Similarly, couldn't unders...
If you don't split your data previously, the trainloader will use the entire train folder. You can specify the amount of training by splitting your data, see: from torchvision import datasets # convert data to a normalized torch.FloatTensor transform = transforms.Compose([ transforms.ToTensor(), transforms.No...
https://stackoverflow.com/questions/54340766/
NumPy is faster than PyTorch for larger cross or outer products
I'm computing huge outer products between vectors of size (50500,) and found out that NumPy is (much?) faster than PyTorch while doing so. Here are the tests: # NumPy In [64]: a = np.arange(50500) In [65]: b = a.copy() In [67]: %timeit np.outer(a, b) 5.81 s ± 56.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop...
Unfortunately there's really no way to specifically speed up torch's method of computing the outer product torch.ger() without a vast amount of effort. Explanation and Options The reason numpy function np.outer() is so fast is because it's written in C, which you can see here: https://github.com/numpy/numpy/blob/7e...
https://stackoverflow.com/questions/54357836/
packed_padded_sequence gives error when used with GPU
I am trying to set up an RNN capable of utilizing a GPU but packed_padded_sequence gives me a RuntimeError: 'lengths' argument should be a 1D CPU int64 tensor here is how I direct gpu computing parser = argparse.ArgumentParser(description='Trainer') parser.add_argument('--disable-cuda', action='store_true', ...
I assume you are using the GPU and probably on the Google Colab. Check yours device device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") device you may solve this error by downgrading the torch version, if you are using colab the following command will help you: !pip install torc...
https://stackoverflow.com/questions/54358280/
Implementing an “infinite loop” Dataset & DataLoader in PyTorch
I’d like to implement an infinite loop Dataset & DataLoader. Here’s what I tried: class Infinite(Dataset): def __len__(self): return HPARAMS.batch_size # return 1<<30 # This causes huge memory usage. def __getitem__(self, idx): """Randomly generates one new example.""" ...
This seems to be working without periodically duplicating the data: import numpy as np import torch from torch.utils.data import Dataset, DataLoader BATCH_SIZE = 2 class Infinite(Dataset): def __len__(self): return BATCH_SIZE def __getitem__(self, idx): return torch.randint(0, 10, (3,)) d...
https://stackoverflow.com/questions/54359243/
How to fix this strange error: "RuntimeError: CUDA error: out of memory"
I successfully trained the network but got this error during validation: RuntimeError: CUDA error: out of memory
The error occurs because you ran out of memory on your GPU. One way to solve it is to reduce the batch size until your code runs without this error.
https://stackoverflow.com/questions/54374935/
How do I extract only subset of classes from torchvision.datasets.CIFAR10?
How do I extract only 2 or 3 classes from torchvision.datasets.CIFAR10? Standard way of loading all 10 classes transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform...
By inspecting the code of CIFAR10, you can see that the data is stored as numpy array and the labels are stored as a list. You can therefore subclass this and filter the two arrays adequately. An example is below: class SubLoader(torchvision.datasets.CIFAR10): def __init__(self, *args, exclude_list=[], **kwargs): ...
https://stackoverflow.com/questions/54380140/
Compute the number of epoch from iteration in training?
I have a Caffe prototxt as follows: stepsize: 20000 iter_size: 4 batch_size: 10 gamma =0.1 in which, the dataset has 40.000 images. It means after 20000 iters, the learning rate will decrease 10 times. In pytorch, I want to compute the number of the epoch to have the same behavior in caffe (for learning rate). How m...
You did not take into account iter_size: 4: when batch is too large to fit into memory, you can "split" it into several iterations. In your example, the actual batch size is batch_sizexiter_size=10 * 4 = 40. Therefore, an epoch takes only 1,000 iterations and therefore you need to decrease the learning rate after 20 ep...
https://stackoverflow.com/questions/54385679/
Preprocessing in image recognition
I am a beginner in image recognition and need some help about preprocessing images. I use transfer learning model resnet18 to do the recognition work. And I get: In [3]: pretrainedmodels.pretrained_settings['resnet18'] Out[3]: {'imagenet': {'url': 'https://download.pytorch.org/models/resnet18- ...
If you training a new model with your own dataset, with the pre-trained weights, you will need to a new mean and std for your new dataset. Basically you will need to repeat the process of how ImageNet did it. Make a script that calculates the general [mean, std] value of your entire dataset. But remember to keep watc...
https://stackoverflow.com/questions/54395051/
How to (quickly) extract bilinear-interpolated patches from a 2d image at specific points?
Update: The original question formulation was a bit unclear. I am not just cropping the image but applying bilinear interpolation during the patches extraction process. (See the paper reference below). That's why the algorithm is a bit more involved than just taking slices. I am trying to train a deep learning m...
1) use numpy 2) select patches with index extraction. Example: Patch=img[0:100,0:100] 3) create 3 dimensional body where in 3rd dimension are patches. [15x15xnumber of patches] 4) do your bilinear int. With numpy for all patches in the same time( insted of one pixel calculate with all pixels in 3rd dimension). T...
https://stackoverflow.com/questions/54421321/
Using CNN for pixel classification,how?
I have already learn about some classification using CNN like for Mnist. But recently I received a dataset which is consist of a vector set. The normal image dataset(mnist) is like nxcxwxh. The one I received is (w*h)x1xc. The goal is to train a network to classify these pixels(as I understand,is classification for pix...
I guess what you're supposed to do is image segmentation and in the shape of the labels you got, the last dimension of 200 corresponds to 200 possible categories of pixels (that sounds like a lot to me, but without more context I cannot judge). The problem of image segmentation is way too broad to explain in an SO answ...
https://stackoverflow.com/questions/54426268/
Accessing PyTorch GPU matrix from TensorFlow directly
I have a neural network written in PyTorch, that outputs some Tensor a on GPU. I would like to continue processing a with a highly efficient TensorFlow layer. As far as I know, the only way to do this is to move a from GPU memory to CPU memory, convert to numpy, and then feed that into TensorFlow. A simplified exampl...
I am not familiar with tensorflow, but you may use pyTorch to expose the "internals" of a tensor. You can access the underlying storage of a tensor a.storage() Once you have the storage, you can get a pointer to the memory (either CPU or GPU): a.storage().data_ptr() You can check if it is pinned or not a.storage...
https://stackoverflow.com/questions/54444137/
conda list returning run-time error Path not Found after installing PyTortch
Recently I tried to install Pytrotch using the command conda install pytorch torchvision cuda100 -c pytorch To verity the package installed correctly I ran conda list in the anaconda prompt and got the following error: RuntimeError: Path not found: C:\Users\[name]\AppData\Local\Continuum\Anaconda3\Lib\site-packag...
AS @P.Antoniadis said, this is an ongoing issue. And removing 'Sphinx-1.5.6-py3.6.egg' folder is the suggested workaround. https://github.com/conda/conda/issues/8156#issuecomment-458777849
https://stackoverflow.com/questions/54445893/
How to use GPUs with Ray in Pytorch? Should I specify the num_gpus for the remote class?
When I use the Ray with pytorch, I do not set any num_gpus flag for the remote class. I get the following error: RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. The main process is: I create a remote class and transfer a pytorch model state_dict()(created i...
If you also want to deploy the model on a gpu, you need to make sure that your actor or task indeed has access to a gpu (with @ray.remote(num_gpus=1), this will make sure that torch.cuda.is_available() will be true in that remote function). If you want to deploy your model on a CPU, you need to specify that when loadin...
https://stackoverflow.com/questions/54451362/
AttributeError: module 'torch' has no attribute 'device'
In following the Pytorch tutorial at https://pytorch.org/tutorials/beginner/deep_learning_60min_blitz.html I received the following error: (pt_gpu) [martin@A08-R32-I196-3-FZ2LTP2 mlm]$ python pytorch-1.py Traceback (most recent call last): File "pytorch-1.py", line 39, in <module> device = torch.device("...
Although this question is very old, I would recommend those who are facing this problem to visit pytorch.org and check the command to install pytorch from there, there is a section dedicated to this: or in your case: As you can see, the command you used to install pytorch is different from the one here. I have not te...
https://stackoverflow.com/questions/54466772/
GANs on color images
Most (PyTorch) open source GANs work on MNIST dataset, i.e. gray level image. Can I use a GAN on each channel of a color image, then combine the result?
You can just have your generator and discriminator generate and classify 3-channel images - speaking in terms of implementation, make them work on B x 3 x H x W tensors instead of B x 1 x H x W, as they do for MNIST. You can't just use your GAN on each channel separately and concatenate at the end, because you would h...
https://stackoverflow.com/questions/54484832/
How to return back to cpu from gpu in pytorch?
I have a text classifier in pytorch and I want to use GPUs to increase running speed. I have used this part of code to check CUDA and use it: if torch.cuda.device_count() > 1: print("Let's use", torch.cuda.device_count(), "GPUs!") my_rnn_model = nn.DataParallel(my_rnn_model) if torch.cuda.is_available(): ...
You can set the GPU device that you want to use using: device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') And in your case just you can return to CPU using: torch.device('cpu')
https://stackoverflow.com/questions/54490351/
Problem with building PyTorch from source on Linux
❓ Problem with building PyTorch from source Hello everyone, I have problem with building PyTorch from source. I followed the official build instructions. I use Anaconda Python 3.7.1 (version 2018.12, build py37_0). I installed all neccessary dependencies using conda and issued python setup.py install command to buil...
Problem solved. I found what was wrong and I fixed it. The whole problem lies in the fact that Anaconda distribution comes with its own ld linker that is located in /opt/anaconda/compiler_compat/ and it overshadows system ld residing at /usr/bin. To fix my error I ran python setup.py clean and then I temporarily ren...
https://stackoverflow.com/questions/54492378/
Running LSTM with multiple GPUs gets "Input and hidden tensors are not at the same device"
I am trying to train a LSTM layer in pytorch. I am using 4 GPUs. When initializing, I added the .cuda() function move the hidden layer to GPU. But when I run the code with multiple GPUs I am getting this runtime error : RuntimeError: Input and hidden tensors are not at the same device I have tried to solve the probl...
When you call .cuda() on the tensor, Pytorch moves it to the current GPU device by default (GPU-0). So, due to data parallelism, your data lives in a different GPU while your model goes to another, this results in the runtime error you are facing. The correct way to implement data parallelism for recurrent neural netw...
https://stackoverflow.com/questions/54511769/
How does PyTorch handle labels when loading image/mask files for image segmentation?
I am starting an image segmentation project using PyTorch. I have a reduced dataset in a folder and 2 subfolders - "image" to store the images and "mask" for the masked images. Images and masks are .png files with 3 channels and 256x256 pixels. Because it is image segmentation, the labelling has to be performed a pixel...
The class torchvision.datasets.ImageFolder is designed for image classification problems, and not for segmentation; therefore, it expects a single integer label per image and the label is determined by the subfolder in which the images are stored. So, as far as your dataloader concern you have two classes of images "im...
https://stackoverflow.com/questions/54528338/
Pytorch - Efficient Elementwise Multiply?
I have a tensor of 3D Points of [100x3] I have a vector of weights of [100x1], which needs to be element wise multiplied into the X,Y,Z coordinates. Currently, I am creating a new vector W where I stack the [100x3] element with repetition into a [100x3] tensor, before i do an element wise multiply. I need to do this...
Standard multiplication (*) in PyTorch already is elementwise. Additionally, it broadcasts. So import torch xyz = torch.randn(100, 3) w = torch.randn(100, 1) multiplied = xyz * w will just do the trick.
https://stackoverflow.com/questions/54543082/
How to Save pytorch tensor in append mode
How to save several tensor appending using torch.save()? For example for i in range(20): ...... loss = criterion(scores, labels) torch.save(loss,'loss.pt') How to save these all 20 losses?
It's probably not possible to directly append to the file, at least, I could not find documentation for this. In your example, however, a better approach is to append to a list, and save at the end. import torch losses = [] for i in range(20): # ...... loss = criterion(scores, labels) losses.append(los...
https://stackoverflow.com/questions/54570525/
How to create a custom PyTorch dataset when the order and the total number of training samples is not known in advance?
I have a 42 GB jsonl file. Every element of this file is a json object. I create training samples from every json object. But the number of training samples from every json object that I extract can vary between 0 to 5 samples. What is the best way to create a custom PyTorch dataset without reading the entire jsonl fil...
You have a couple of options. The simplest option, if having lots of small files is not a problem, is to preprocess each json object into a single file. Then you can just read each one depending on the index requested. E.g class SingleFileDataset(Dataset): def __init__(self, list_of_file_paths): ...
https://stackoverflow.com/questions/54571377/
What does log_prob do?
In some (e.g. machine learning) libraries, we can find log_prob function. What does it do and how is it different from taking just regular log? For example, what is the purpose of this code: dist = Normal(mean, std) sample = dist.sample() logprob = dist.log_prob(sample) And subsequently, why would we first take a l...
As your own answer mentions, log_prob returns the logarithm of the density or probability. Here I will address the remaining points in your question: How is that different from log? Distributions do not have a method log. If they did, the closest possible interpretation would indeed be something like log_prob but it w...
https://stackoverflow.com/questions/54635355/
How to load a checkpoint file in a pytorch model?
In my pytorch model, I'm initializing my model and optimizer like this. model = MyModelClass(config, shape, x_tr_mean, x_tr,std) optimizer = optim.SGD(model.parameters(), lr=config.learning_rate) And here is the path to my checkpoint file. checkpoint_file = os.path.join(config.save_dir, "checkpoint.pth") To load...
You saved the model parameters in a dictionary. You're supposed to use the keys, that you used while saving earlier, to load the model checkpoint and state_dicts like this: if os.path.exists(checkpoint_file): if config.resume: checkpoint = torch.load(checkpoint_file) model.load_state_dict(checkpoin...
https://stackoverflow.com/questions/54677683/
Apply a PyTorch CrossEntropy method for multiclass segmentation
I am trying to implement a simple example of how to apply cross-entropy to what is supposed to be the output of my semantic segmentation CNN. Using the pytorch format I would have something like this: out = np.array([[ [ [1.,1, 1], [0, 0, 0], [0, 0, 0], [0, 0, 0] ], [ ...
Look at the description of nn.CrossEntropyLoss function, the prediction out you provide to nn.CrossEntropyLoss are not treated as class probabilities, but rather as logits; The loss function derive the class probabilities from out using soft max therefore nn.CrossEntropyLoss will never output exactly zero loss.
https://stackoverflow.com/questions/54680267/
Optional tensors in PyTorch c++ extension
I'm writing a C++ extension for pytorch, and using the c++ api to do so. To my forward function, I need to pass an optional tensor. Inside the function, I want to do different things based on whether this optional parameter was passed or not. In general, we use NULL for optional pointer arguments in C++ and check insi...
One possibility could be to use std::optional as std::optional<at::Tensor> optional_constraints = std::nullopt. It is contextually convertible to bool, so you can check it with if (optional_constraints). Use the .value() method to get the tensor if you pass one, otherwise the default value will be std::nullopt.
https://stackoverflow.com/questions/54685444/
Can anyone solve this?
torch.tensor(2,require_grad=True) Traceback (most recent call last): File "", line 1, in torch.tensor(2,require_grad=True) TypeError: tensor() got an unexpected keyword argument 'require_grad'
It's actually: requires_grad
https://stackoverflow.com/questions/54686300/
How does one determine when the CartPole environment has been solved?
I was going through this tutorial and saw the following piece of code: # Calculate score to determine when the environment has been solved scores.append(time) mean_score = np.mean(scores[-100:]) if episode % 50 == 0: print('Episode {}\tAverage length (last 100 episodes): ...
The time used in case of cartpole equals the reward of the episode. The longer you balance the pole the higher the score, stopping at some maximum time value. So the episode would be considered solved if the running average of the last episodes is near enough that maximum time.
https://stackoverflow.com/questions/54737990/
Calling super's forward() method
What is the most appropriate way to call the forward() method of a parent Module? For example, if I subclass the nn.Linear module, I might do the following class LinearWithOtherStuff(nn.Linear): def forward(self, x): y = super(Linear, self).forward(x) z = do_other_stuff(y) return z Howeve...
TLDR; You can use super().forward(...) freely even with hooks and even with hooks registered in super() instance. Explanation As stated by this answer __call__ is here so the registered hooks (e.g. register_forward_hook) will be run. If you inherit and want to reuse base class's forward, e.g. this: import torch class...
https://stackoverflow.com/questions/54752983/
How to work with large dataset in pytorch
I have a huge dataset that does not fit in memory (150G) and I'm looking for the best way to work with it in pytorch. The dataset is composed of several .npz files of 10k samples each. I tried to build a Dataset class class MyDataset(Dataset): def __init__(self, path): self.path = path self.files =...
How large are the individual .npz files? I was in similar predicament a month ago. Various forum posts, google searches later I went the lmdb route. Here is what I did Chunk the large dataset into small enough files that I can fit in gpu — each of them is essentially my minibatch. I did not optimize for load time at ...
https://stackoverflow.com/questions/54753720/
Espresso ANERuntimeEngine Program Inference overflow
I have two CoreML models. One works fine, and the other generates this error message: [espresso] [Espresso::ANERuntimeEngine::__forward_segment 0] evaluate[RealTime]WithModel returned 0; code=5 err=Error Domain=com.apple.appleneuralengine Code=5 "processRequest:qos:qIndex:error:: 0x3: Program Inference overflow" UserI...
That's a LOT of layers! Espresso is the C++ library that runs the Core ML models. ANERuntimeEngine is used with the Apple Neural Engine chip. By passing in an MLModelConfiguration with computeUnits set to .cpuAndGPU when you load the Core ML model, you can tell Core ML to not use the Neural Engine.
https://stackoverflow.com/questions/54773171/
Correctly converting a NumPy array to a PyTorch tensor running on the gpu
I have created a DataLoader that looks like this class ToTensor(object): def __call__(self, sample): return torch.from_numpy(sample).to(device) class MyDataset(Dataset): def __init__(self, data, transform=None): self.data = data self.transform = transform def __len__(self): ...
Try this one: Code: import numpy as np import torch import torch.nn as nn torch.cuda.set_device(0) X = np.ones((1, 10), dtype=np.float32) print(type(X), X) X = torch.from_numpy(X).cuda(0) print(type(X), X) model = nn.Linear(10, 10).cuda(0) Y = model(X) print(type(Y), Y) Output: <class 'numpy.ndarray'> [[1...
https://stackoverflow.com/questions/54773293/
The strange loss fluctuation when loading previous trained model
I am using PyTorch for deep learning now. I trained a model before and had the parameters saved. Loss values before the end of the training were about 0.003~0.006. However, when I load the same model with the same training data, loss values at first fluctuate to around 0.5. The loss values then decrease very quick...
When resuming a training, you should not only load the network's weights but also the optimizer state. For that, you can use torch.save: torch.save({ 'epoch': epoch, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'loss': loss, ...
https://stackoverflow.com/questions/54806742/
PyTorch why does the forward function run multiple times and can I change the input shape?
import torch import torch.nn as nn import torchvision.datasets as dsets from skimage import transform import torchvision.transforms as transforms from torch.autograd import Variable import pandas as pd; import numpy as np; from torch.utils.data import Dataset, DataLoader import statistics import random import math c...
You are calling forward twice in run: Once for the training data Once for the validation data However, you do not appear to have applied the following transformation to your validation data: images = images.resize_((100,616)) Maybe consider doing the resize in the forward function.
https://stackoverflow.com/questions/54840612/
Load Pre-trained model in Pytorch
I am currently working on GANS, I have downloaded the code and models from http://www.cs.columbia.edu/~vondrick/tinyvideo/, where I just need to run to get output. I have given paths and all correctly, and the code where i am receiving an error is shown below. The have wrote the lines correctly but still getting syntax...
you are trying to init a python dictionary. this is how you do it: opt = { 'model': 'models/beach/iter63000_net.t7', 'batchSize': 128, 'gpu': 1, 'cudnn': 1, }
https://stackoverflow.com/questions/54851182/
Pytorch: Set Block-Diagonal Matrix Efficiently?
I have a Tensor A of size [N x 3 x 3], and a Matrix B of size [N*3 x N*3] I want to copy the contents of A -> B, so that the diagonal elements are filled up basically, and I want to do this efficiently: It should kind of fill up B to look something filled like this: So each [i,3,3] fills into each [3x3] part in B d...
Use torch.block_diag(): # Setup A = torch.ones(3,3,3, dtype=int) # Unpack blocks and apply B = torch.block_diag(*A) >>> B tensor([[1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0], ...
https://stackoverflow.com/questions/54856333/
Input labels for semantic segmentation with U-Net as single layer
When doing semantic segmentation with the U-Net for example, it seems to be common-practice to provide the label data as one-hot-encoded tensors. In another SO question, a user pointed out that this is due to the labels usually representing categorical values. Feeding them to the network as class labels within only one...
This can help you save disk memory as you will be able to store the labels, the ground truth, as a greyscale image (width, heigh, 1) and not as a bigger 3D tensor of shape (width, height, n). But, during the training process, you will have to convert the greyscale ground truth images to 3D tensor to be able to train yo...
https://stackoverflow.com/questions/54869612/
RuntimeError: _thnn_mse_loss_forward is not implemented for type torch.cuda.LongTensor
I'm using PyTorch,but I get a error! My error code as following: for train_data in trainloader: example_count += 1 if example_count == 100: break optimer.zero_grad() image, label = train_data image = image.cuda() label = label.cuda() out = model(image) _, out = torch.max(out, 1...
Look at the documentation of torch.max(): torch.max(input, dim, keepdim=False, out=None) -> (Tensor, LongTensor) Returns the maximum value of each row of the input tensor in the given dimension dim. The second return value is the index location of each maximum value found (argmax). Your line of code _...
https://stackoverflow.com/questions/54878415/
RuntimeError: Expected hidden[0] size (2, 20, 256), got (2, 50, 256)
I get this error while trying to build a multiclass text classification network using LSTM (RNN). The code seems to run fine for the training part of the code whereas it throws the error for the validation part. Below is the network architecture and training code. Appreciate any help here. I tried taking an existing c...
Try adding drop_last=True in your line of codes that loads data using DataLoader, for example for loading training data from data set train_data: train_loader = DataLoader(train_data, shuffle=True, batch_size=batch_size, drop_last=True) Explanation: The error may caused by your training data not being divisible by bat...
https://stackoverflow.com/questions/54878904/
Choosing a margin for contrastive loss in a siamese network
I'm building a siamese network for a metric-learning task, using a contrastive loss function, and I'm uncertain on how to set the 'margin' hyperparameter for the loss. My inputs to the loss function are currently 1024-dimension dense embeddings from an RNN layer - Does the dimensionality of that input affect how I pi...
You don't need to project it to a lower dimensional space. The dependence of the margin with the dimensionality of the space depends on how the loss is formulated: If you don't normalize the embedding values and compute a global difference between vectors, the right margin will depend on the dimensionality. But if you...
https://stackoverflow.com/questions/54892607/
Mismatching Conda and Pycharm
I'm new in python and I'm confused about mismatching Conda packages list and Pycharm. In a project I need to install pytorch. Installing with pycharm lead to some error and when I install it through conda, It does not appear in pycharm. Both list is the same env. Thanks in advance. pycharm list Anaconda list
PyCharm shows you the list of installed packages with pip, while conda list shows both pip and conda. Meanwhile, you can switch between pip and conda with a dedicated button in PyCharm:
https://stackoverflow.com/questions/54909322/
Fastai learner not loading
So I'm trying to load a model using: learn = create_cnn(data, models.resnet50, lin_ftrs=[2048], metrics=accuracy) learn.clip_grad(); learn.load(f'{name}-stage-2.1') But I get the following error RuntimeError: Error(s) in loading state_dict for Sequential: size mismatch for 1.8.weight: copying a param with shape to...
Use cnn_learner method and latest Pytorch with latest FastAI. There was a breaking change and discontinuity so you suffer now. The fastai website has many examples such as this one. learn = cnn_learner(data, models.resnet50, metrics=accuracy)
https://stackoverflow.com/questions/54914106/
How to convert a Label matrix to colour matrix for image segmentation?
I have a label matrix of 256*256 for example. And the classes are 0-11 so 12 classes. I want to convert the label matrix to colour matrix. I tried do it in a code like this `for i in range(256): for j in range(256): if x[i][j] == 11: dummy[i][j] = [255,255,255] if x[i][j] == 1: ...
You are looking into indexed RGB images - an RGB image where you have a fixed "pallet" of colors, each pixel indexes to one of the colors of the pallet. See this page for more information. from PIL import Image img = Image.fromarray(x, mode="P") img.putpalette([ 255, 255, 255, # index 0 144, 0, 0, # index 1...
https://stackoverflow.com/questions/54928522/
Efficient way to implement matrix multiplication when one matrix is extremely wide?
I need to multiply 3 matrices, A: 3000x100, B: 100x100, C: 100x3.6MM. I currently am just using normal matrix multiplication in PyTorch A_gpu = torch.from_numpy(A) B_gpu = torch.from_numpy(B) C_gpu = torch.from_numpy(C) D_gpu = (A_gpu @ B_gpu @ C_gpu.t()).t() C is very wide so the data reuse on gpu is limited but a...
Since you have four GPUs, you can harness them to perform efficient matrix multiplication. Notice however that the results of the multiplication has size 3000x3600000, which takes up 40GB in single precision floating point (fp32). Unless you have a large enough RAM for the CPU, you cannot store the results of this comp...
https://stackoverflow.com/questions/54932734/
CUDA out of memory with matrix multiply
I'm trying to multiply 3 matrices, but am running out of CUDA memory. # A: 3000 x 100 (~2MB) # B: 100 x 100 (~0.05MB) # C: 100 x 3MM (~2GB) A = np.random.randn(3000, 100) B = np.random.randn(100, 100) C = np.random.randn(100, 3e6) A_gpu = torch.from_numpy(A).cuda() B_gpu = torch.from_numpy(B).cuda() C_gpu = torch....
Multiplying matrices, your output size is going to be 3,000 x 3,000,000 matrix! so despite A and B being relatively small, the output R is HUGE: 9G elements. Moreover, I suspect dtype of your matrices is float64 and not float32 (because you used numpy to init them). Therefore, each of the 9G elements of R_gpu requires ...
https://stackoverflow.com/questions/54936628/
'NoneType' object has no attribute 'add_summary'
I'm having trouble with visualizing the weights and bias of my model using tensorboardX. Here is my model (it's pretty simple anyway): self.pipe = nn.Sequential(nn.Linear(9, 128), nn.ReLU(), nn.Linear(128, 256), nn.ReLU(), ...
The posted code snippet is insufficient to root cause the issue. The member variable file_writer is set to None when the close() method is invoked on writer. Please check if the close() method was invoked on writer. The close() method is also invoked when the writer object is used as a Context manager and the with blo...
https://stackoverflow.com/questions/54937532/
Data Augmentation with torchvision.transforms in pytorch
I found out data augmentation can be done in PyTorch by using torchvision.transforms. I also read that transformations are apllied at each epoch. So I'm wondering whether or not the effect of copying each sample multiple times and then applying random transformation to them is same as using torchvision.transforms on or...
This is a question to be answered in a broad scale. don't get misunderstood that the TorchVision Transforms doesn't increase your dataset. It applies random or non-random transforms to your current data set at runtime. (hence unique each time and each epoch). the effect of copying each sample multiple times and the...
https://stackoverflow.com/questions/54972534/
"function 'AddDllDirectory' not found" while importing pytorch
I keep getting this error while trying to import pytorch in jupyter notebook import torch AttributeError: function 'AddDllDirectory' not found this error occur only when I try installing pytorch in anaconda (I used both command to install pytorch pip and conda, I also tried installing only the cpu version and ...
I fixed the issue by installing the file (KB2533623) from Here (for windows 7 users). this file apparently contains the missing "AddDllDirectory" function. Posting this answe in case someone ran into the same problem.
https://stackoverflow.com/questions/54985803/
Calling forward function without .forward()
While looking at some pytorch code on pose estimation AlphaPose I noticed some unfamiliar syntax: Basically, we define a Darknet class which inherits nn.Module properties like so: class Darknet(nn.Module) This re-constructs the neural net from some config file and also defines functions to load pre-trained weights an...
This is nothing torch specific. When you call something as class_object(fn params) it invokes the __call__ method of that class. If you dig the code of torch, specifically nn.Module you will see that __call__ internally invokes forward but taking care of hooks and states that pytorch allows. So when you are calling s...
https://stackoverflow.com/questions/54989230/
how sort randomly images and its mask?
before splitting the dataset I need to randomly load the data and then do splitting . This is the snippet for splitting the dataset which is not randomly. I am wondering how can I do this for images and corresponding mask in folder_mask? folder_data = glob.glob("D:\\Neda\\Pytorch\\U-net\\my_data\\imagesResized\\*.png"...
As far as I understood, you want to randomize the order of the pictures, so that with each rerun there are different photos in the train and test set. Assuming you want to do this in more or less plain Python you can do the following. The easiest way to use shuffle a list of elements in python is: import random rando...
https://stackoverflow.com/questions/55011980/
shall I apply softmax before cross entropy?
The pytorch tutorial (https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py) trains a convolutional neural network (CNN) on a CIFAR dataset. class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = n...
CrossEntropyLoss in PyTorch is already implemented with Softmax: https://pytorch.org/docs/stable/nn.html#torch.nn.CrossEntropyLoss This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class. The answer to the second part of your question is a little more complicated. There can be multiple causes for...
https://stackoverflow.com/questions/55030217/
CycleGAN with 1-channel tiffs both as input and as output
I am running CycleGAN with different types of tiffs in trainA and trainB. The tiffs are 256x256 pixels in size and have 1 channel per pixel. I am using tiffs to have a wide range of values. I changed the code as suggested in the pytorch-CycleGAN-and-pix2pix repo (https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix...
Have you tried adding the parameters --input_nc 1 --output_nc 1 during training? It will convert the number of channels from 3 to 1.
https://stackoverflow.com/questions/55032389/
cuDNN error: CUDNN_STATUS_BAD_PARAM.Can someone explain why i am getting this error and how can i correct it?
I am trying to implement a Character LSTM using Pytorch.But I am getting cudnn_status_bad_params errors.This is the training loop.I getting error on line output = model(input_seq). for epoch in tqdm(range(epochs)): for i in range(len(seq)//batch_size): sidx = i*batch_size eidx = sidx + batch_size x = seq[si...
I got the same error, if you switch to CPU, you'll get a much better description of the error. In my case the problem was in type of input that I was giving to the network. I was sending I guess long, while the model needed float. I made the following changes and the code worked. Basically switching to cpu gives better...
https://stackoverflow.com/questions/55042931/
Torchtext AttributeError: 'Example' object has no attribute 'text_content'
I'm working with RNN and using Pytorch & Torchtext. I've got a problem with building vocab in my RNN. My code is as follows: TEXT = Field(tokenize=tokenizer, lower=True) LABEL = LabelField(dtype=torch.float) trainds = TabularDataset( path='drive/{}'.format(TRAIN_PATH), format='tsv', fields=[ ('lab...
This problem arises when the fields are not passed in the same order as they are in the csv/tsv file. Order must be same. Also check if no extra or less fields are mentioned than there are in the csv/tsv file..
https://stackoverflow.com/questions/55060888/
convert cv2.umat to numpy array
Processed_image() function returns a cv2.Umat type value which is to be reshaped from 3 dimensions(h, ch, w) to 4 dimensions(h, ch, w, 1) so i need it to be converted to numpy array or also if possible help me to directally rehshape cv2.umat type variable to be directally reshaped and converted to a pytorch tensor a...
I didn't quite catch your question, but you can get numpy data of an opencv's umat with "get()" like this and you should probably permute your tensor before feeding it into your model.
https://stackoverflow.com/questions/55062886/
How to load images with multiple JSON annotation in PyTorch
I would like to know how I can use the data loader in PyTorch for the custom file structure of mine. I have gone through PyTorch documentation, but all those are with separate folders with class. My folder structure consists of 2 folders(called training and validation), each with 2 subfolders(called images and json_an...
You should be able to implement your own dataset with data.Dataset. You just need to implement __len__ and __getitem__ methods. In your case, you can iterate through all images in the image folder (then you can store the image ids in a list in your Dataset). Then, you use the index passed to __getitem__ to get the cor...
https://stackoverflow.com/questions/55075715/
Display a tensor image in matplotlib
I'm doing a project for Udacity's AI with Python nanodegree. I'm trying to display a torch.cuda.FloatTensor that I obtained from an image file path. Below that image will be a bar chart showing the top 5 most likely flower names with their associated probabilities. plt.figure(figsize=(3,3)) path = 'flowers/test/1/im...
You are trying to apply numpy.transpose to a torch.Tensor object, thus calling tensor.transpose instead. You should convert flower_tensor_image to numpy first, using .numpy() axs = imshow(flower_tensor_image.detach().cpu().numpy(), ax = plt)
https://stackoverflow.com/questions/55083571/
RuntimeError: Only tuples, lists and Variables supported as JIT inputs, but got NoneType
My code is a=torch.randn(1,80,100,requires_grad=True) torch.onnx.export(waveglow,a, "waveglow.onnx") I am trying to export a PyTorch model to ONNX format so i can use it in TensorRT. while testing my model in PyTorch the input tensor dimension is (1,80,x) where x varies depending on the input text length(the model ...
Given that you have NoneType, perhaps you could check if there is an actual input, because the fact is, you actually got None. Also, any reason to not use Variable? Variable converts your inputs to a tensor that can be accepted as an input for torch.onnx.export.
https://stackoverflow.com/questions/55085660/
Model returns a Nan value
I was trying to build a neural network with 4 input nodes/ features and just one output feature(0/1). I wrote this code and it runs but while training the model returns NaN. I debugged too and weights and biases are fine until they go through the model. From what I've searched so far, this could be a problem in the w...
If you see NaN's in loss try gradient clipping and data normalisation. Normalising data is a must (i.e normalize input data such that mean = 0 and variance =1)
https://stackoverflow.com/questions/55087458/
A Basic Python Question about Defining Function
I have a basic question regarding Python code. For example, import torch import torch.nn as nn loss = nn.MSELoss() input = torch.randn(3, 5, requires_grad=True) target = torch.randn(3, 5) output = loss(input, target) output.backward() Why do I need to define the loss function at the first line? I can't replace loss()...
As a few others have pointed out, nn.MSELoss is a class and not a function. In line 1 you are creating an object of type torch.nn.modules.loss.MSELoss. And because it inherits from nn.Module, you can call this object like you would call a function, like you do in line 4. If you don't want to use the MSELoss class, you ...
https://stackoverflow.com/questions/55092187/
How to handle large JSON file in Pytorch?
I am working on a time series problem. Different training time series data is stored in a large JSON file with the size of 30GB. In tensorflow I know how to use TF records. Is there a similar way in pytorch?
I suppose IterableDataset (docs) is what you need, because: you probably want to traverse files without random access; number of samples in jsons is not pre-computed. I've made a minimal usage example with an assumption that every line of dataset file is a json itself, but you can change the logic. import json from t...
https://stackoverflow.com/questions/55109684/
How to visualize my training history in pytorch?
How do you guys visualize the training history of your pytorch model like in keras here. I have a pytorch trained model and I want to see the graph of its training. Can I do this using only matplotlib? If yes, can someone give me resources to follow.
You have to save the loss while training. A trained model won't have history of its loss. You need to train again. Save the loss while training then plot it against the epochs using matplotlib. In your training function, where loss is being calculated save that to a file and visualize it later. Also, you can use tenso...
https://stackoverflow.com/questions/55112960/
How to calculate Batch Pairwise Distance in PyTorch efficiently
I have tensors X of shape BxNxD and Y of shape BxNxD. I want to compute the pairwise distances for each element in the batch, i.e. I a BxMxN tensor. How do I do this? There is some discussion on this topic here: https://github.com/pytorch/pytorch/issues/9406, but I don't understand it as there are many implementatio...
I had a similar issue and spent some time to find the easiest and fastest solution. Now you can compute batched distance by using PyTorch cdist which will give you BxMxN tensor: torch.cdist(Y, X) Also, it works well if you just want to compute distances between each pair of rows of two matrixes.
https://stackoverflow.com/questions/55126072/
.py not reading from the content folder
|-content |-utils |- parse_config.py |-models.py folder structure This is my folder structure in google colab. I have already installed Pytorch and all other requirments for the project. Here models.py file is not able to access the files in utils folder. In my models.py I'm importing utils.parse_config w...
Models.py seem not in utils folder. Please recheck
https://stackoverflow.com/questions/55129148/
GRU Language Model not Training Properly
I’ve tried reimplementing a simple GRU language model using just a GRU and a linear layer (the full code is also at https://www.kaggle.com/alvations/gru-language-model-not-training-properly): class Generator(nn.Module): def __init__(self, vocab_size, embedding_size, hidden_size, num_layers): super(Generato...
I'm by no means a PyTorch expert, but that snippet looks fishy to me: # Put the embedded inputs into the GRU. output, hidden = self.gru(embedded, hidden) # Matrix manipulation magic. batch_size, sequence_len, hidden_size = output.shape # Technically, linear layer takes a 2-D matrix as input, so mor...
https://stackoverflow.com/questions/55137631/
Curious on how to use some basic machine learning in a web application
A co-worker and I had an idea to create a little web game where a user enters a chunk of data about themselves and then the application would write for them to sound like them in certain structures. (Trying to leave the idea a little vague.) We are both new to ML and thought this could be a fun first dive. We have a d...
It sounds like you are looking for something like Tensorflow JS
https://stackoverflow.com/questions/55149138/
Implement dropout to fully connected layer in PyTorch
How to apply dropout to the following fully connected network in Pytorch: class NetworkRelu(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784,128) self.fc2 = nn.Linear(128,64) self.fc3 = nn.Linear(64,10) def forward(self,x): x = F.relu(self.fc...
Since there is functional code in the forward method, you could use functional dropout, however, it would be better to use nn.Module in __init__() so that the model when set to model.eval() evaluate mode automatically turns off the dropout. Here is the code to implement dropout: class NetworkRelu(nn.Module): def...
https://stackoverflow.com/questions/55157514/
Pytorch sum over a list of tensors along an axis
I have a list of tensors of the same shape. I would like to sum the entire list of tensors along an axis. Does torch.cumsum perform this op along a dim? If so it requires the list to be converted to a single tensor and summed over?
you don't need cumsum, sum is your friend and yes you should first convert them into a single tensor with stack or cat based on your needs, something like this: import torch my_list = [torch.randn(3, 5), torch.randn(3, 5)] result = torch.stack(my_list, dim=0).sum(dim=0).sum(dim=0) print(result.shape) #torch.Size([5]) ...
https://stackoverflow.com/questions/55159955/
Faster pytorch dataset file
I have the following problem, I have many files of 3D volumes that I open to extract a bunch of numpy arrays. I want to get those arrays randomly, i.e. in the worst case I open as many 3D volumes as numpy arrays I want to get, if all those arrays are in separate files. The IO here isn't great, I open a big file only to...
I iterated through my dataset, created an hdf5 file and stored elements in the hdf5. Turns out, when the hdf5 is opened, it doesn't load all data in ram, it loads the header instead. The header is then used to fetch the data on request, that's how I solved my problem. Reference: http://www.machinelearninguru.com/deep_...
https://stackoverflow.com/questions/55166874/
Need very different learning rate for manual updates vs. using model
I am currently just trying to write some pedagogical material, in which I borrow from some common examples that have been reworked numerous times on the web. I have a simple bit of code where I manually create tensors for layers, and update them within a loop. E.g.: w1 = torch.randn(D_in, H, dtype=torch.float, requi...
The crucial difference is the initialization of the weights. The weight matrix in a nn.Linear is initialized smart. I'm pretty sure that if you construct both the models and copy the weight matrices in one way or the other, you'll get consistent behavior. Additionally, please note that the two models are not equivalen...
https://stackoverflow.com/questions/55170175/
Convert a python list of python lists to pytorch tensor
What is the conventional way to convert python list of lists to PyTorch tensors? a = [0,0] b = [1,1] c = [2] c = [a, b, c] I want c to be converted to a flattened Torch tensor as below: torch([ 0, 0, 1, 1, 2])
You can flatten your list first in Python: flat_list = [item for sublist in c for item in sublist] And create your Tensor: flattened_tensor = torch.FloatTensor(flat_list)
https://stackoverflow.com/questions/55193322/