instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Pytorch get "RuntimeError: CUDA error: device-side assert triggered"
Snippet from my code : max = torch.tensor([3]) if USE_CUDA: max = max.cuda() max_embedding = self.max_embedding(max) # dim of max_embedding: 1*5 item_dict = {} for item in item_list: item = torch.tensor(item) if USE_CUDA: item = item.cuda() item_embedding = self.item_embedding(item) # dim of item_embeddi...
This is a typical case of index-out-of-bounds error manifested itself in the context of embeddings. Check this link for solution to a similar problem.
https://stackoverflow.com/questions/58889968/
Saving Numpy Array as Lab Image via PIL
Hello everyone! I am writing a function which gets two Pytorch-Tensors as input and merges parts of both tensors to a new array which will be converted to a Lab-image afterwards. net_input is a tensor with 3 channels (L, a, b) and output is a tensor with 2 channels (a, b). Now, I want to take the L-channel from net_...
If you do this with PIL: im = Image.new('LAB',(80,80),color=(255,0,0)).save('a.tif') you'll get a cyan colour the same as if you use this colour converter and put in L/a/b = 100/-128/-128 If you do this: im = Image.new('LAB',(80,80),color=(255,255,0)).save('a.tif') you'll find that corresponds to L/a/b=...
https://stackoverflow.com/questions/58892179/
Why does pre-trained ResNet18 have a higher validation accuracy than training?
For PyTorch's tutorial on performing transfer learning for computer vision (https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html), we can see that there is a higher validation accuracy than training accuracy. Applying the same steps to my own dataset, I see similar results. Why is this the case? Does ...
Assuming there aren't bugs in your code and the train and validation data are in the same domain, then there are a couple reasons why this may occur. Training loss/acc is computed as the average across an entire training epoch. The network begins the epoch with one set of weights and ends the epoch with a different (...
https://stackoverflow.com/questions/58895804/
Using MIT Indoor scene database in CNN
I'm an engineering student and kind of a noob to programming. I'm taking an AI course, currently trying to do my final project. I have to create a CNN net, I have to use de MIT Indoor scene database (it can be found here: http://web.mit.edu/torralba/www/indoor.html). I don't have a problem doing the CNN since I've do...
you can generate your own csv files, although, you might not need it. There is a good tutorial on pytorch website https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#load-data, which is very similar or easily applicable to your case. MIT Indoor dataset has the images one folder per class, and the tx...
https://stackoverflow.com/questions/58903554/
How to compose several matrices into a big matrix diagonally in Pytorch
I have several matrices, let's say [M1,M2,M3,M4]. Each matrix has a different shape. How do I compose these matrices into one big matrix diagonally like: [[M1, 0, 0, 0] [0, M2, 0, 0] [0, 0, M2, 0] [0, 0, 0, M2]] Example: M1 = [[1,2],[2,1]] M2 = [[1,2]] M3 = [[3]] M4 = [[3,4,5],[4,5,6]] To compose this big matrix:...
Use PyTorch's torch.block_diag(): >>> torch.block_diag(M1,M2,M3,M4) tensor([[1, 2, 0, 0, 0, 0, 0, 0], [2, 1, 0, 0, 0, 0, 0, 0], [0, 0, 1, 2, 0, 0, 0, 0], [0, 0, 0, 0, 3, 0, 0, 0], [0, 0, 0, 0, 0, 3, 4, 5], [0, 0, 0, 0, 0, 4, 5, 6]])
https://stackoverflow.com/questions/58905583/
How to free GPU memory for a specific tensor in PyTorch?
I’m currently running a deep learning program using PyTorch and wanted to free the GPU memory for a specific tensor. I’ve thought of methods like del and torch.cuda.empty_cache(), but del doesn’t seem to work properly (I’m not even sure if it frees memory at all) and torch.cuda.empty_cache() seems to free all unused m...
del operator works but you won't see a decrease in the GPU memory used as the memory is not returned to the cuda device. It is an optimization technique and from the user's perspective, the memory has been "freed". That is, the memory is available for making new tensors now. Source: Pytorch forum
https://stackoverflow.com/questions/58925249/
how to batch dialog dataset in pytorch?
I want to do a task oriented dialog chatbot which is used to book restaurant.Because every dialog has different sequences(eg. some has 5 turns of dialogs which is 10 sentences while another may has 6 turns of dialogs which is 12 sentences totally),I don't know how to batch dataset. Could you give me some tutorial or g...
There are some related questions to this on Stackoverflow. I liked the explanation/answer provided here. The tldr version is to use Packed Sequence. The answer I linked to provides the following example (copied from the link): a = [torch.tensor([1,2,3]), torch.tensor([3,4])] b = torch.nn.utils.rnn.pad_sequence(a, batc...
https://stackoverflow.com/questions/58929441/
How to set up loss function in PyTorch for Soft-Actor-Critic
I'm trying to implement a custom loss function for a soft Q-learning, actor-critic policy gradient algorithm in PyTorch. This comes from the following paper Learning from Imperfect Demonstrations. The structure of the algorithm is similar to deep q-learning, in that we are using a network to estimate Q-values, and we u...
This turns out to be fairly simple assuming you can calculate V, Q, and Q^. After discussing this with some people offline I was able to get pytorch to calculate this loss by setting it up as: loss = (Q-V)*(Q-Q_hat).detach() optimizer.zero_grad() loss.backward() optimizer.step()
https://stackoverflow.com/questions/58943164/
Pytorch customize weight
I have a network class Net(nn.Module) and two different weights w0 and w1 (concatenate weights of all layers into a vector). Now I want to optimize the network on the line connecting w0 and w1, which means that the weight will have the form theta * w0 + (1-theta) * w1. So now the parameter I want to optimize is no ...
You can define the parameter theta in your net as an nn.Parameter. You'd define the forward function the same way as normal - pass the data through the layers or operations you want and then return it. Here's a minimal example, where I train a "network" to learn to multiply a Tensor by 2: import numpy as np import to...
https://stackoverflow.com/questions/58946855/
Simple policy gradients (REINFORCE) overfits one action when playing Atari Breakout
Self-contained code: https://colab.research.google.com/drive/1HYEXMpicymPUySkhGOaCJdJ3pN4RzXYd The problem: I am trying to use a CNN to play Atari breakout from pixels (Breakout-V0 OpenAI gym). I am trying to use the simple policy gradients algorithm, implemented in PyTorch, to do this. There are four possible actions...
We ran into a similar problem while training Breakout with VPG (Vanilla Policy Gradient). The solution was to enforce entropy loss over the following Entropy loss over the policy model output (Penalise selecting a specific action with high likelihood) Scaling the MSE between rewards to go and value function Not sur...
https://stackoverflow.com/questions/58956125/
Different filters for 2d convolution
I’m having an input of shape (B(atch), F(features), N(odes), T(timestamps)). Right now if I apply a 2d convolution with a kernel of shape (1,2) I will have a total of (F_out, F_in, 1,2) weights to learn which is alright. I want to extend this so that for each Node in the input I have it’s own filter with shape (1,2). D...
You are looking for "grouped convolution". The doc for nn.Conv2d regarding the groups parameter: At groups=2, the operation becomes equivalent to having two conv layers side by side, each seeing half the input channels, and producing half the output channels, and both subsequently concatenated. In your case, you ...
https://stackoverflow.com/questions/58956579/
Expected dimension sizes for pytorch models
I'm struggling with understanding what sort of dimensions my pytorch model needs as input. My model setup is: import torch from torch import nn, tensor class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.rnn_b = nn.RNN(input_size=input_si...
You need to encapsulate more. This is because pytorch automatically allows batches: model(tensor([[[25.]]]), tensor([[[0., 0.]]])) Output: (tensor([[[-0.7704]]], grad_fn=<AddBackward0>), tensor([[[1., 1.]]], grad_fn=<StackBackward>)) You can use multiple input, as a batch: model(tensor([[[25.]], [[2...
https://stackoverflow.com/questions/58959707/
How to create upper triangular matrix in Pytorch?
Simple question, but is there a native way to create an upper triangular matrix from an existing matrix in Pytorch? I was thinking of using a mask, but even that requires creating the upper triangular matrix.
import torch upper_tri = torch.ones(rol, col).triu() Eg: >> mat = torch.ones(3, 3).triu() >> print(mat) tensor([[1., 1., 1.], [0., 1., 1.], [0., 0., 1.]])
https://stackoverflow.com/questions/58965717/
How to adapt the gpu batch size during training?
I found surprising that I could not find any resources online on how to dynamically adapt the GPU batch size without halting training. The idea is the following: 1) Have a training script that is (almost) agnostic to the GPU in use. The batch size will dynamically adjust without interference of the user or need for t...
There are different ways of solving this problem. But if specifying the GPU that can do the job, or using multiple GPUs are not an option, then it is handy to dynamically adapt the GPU batch size. I prepared this repo with an illustrative training example in pytorch (it should work similarly in TensorFlow) In the co...
https://stackoverflow.com/questions/58971123/
Why the resnet110 I train on CIFAR10 dataset only get 77% test acc
I trained the Resnet110 on CIFAR10 dataset, and I got 100% acc on training, but only 77.85% on test dataset. What is the problem probally be? Otherwise, I use Pytorch framwork. Thank U very much! ------------------------------------------------------------------------ Train Epoch: 200 [0/50000 (0%)] Loss: 0.000811...
ResNet-101 is definitely too big for CIFAR10, go with smaller versions, ResNet-18 from torchvision should be fine. Furthermore, you could train those really fast using super convergence (e.g. setting learning rate to 5 or 3), see this article or other related. You could do so in 18 epochs or so with torch.optim.AdamW ...
https://stackoverflow.com/questions/58986583/
Adapting Pytorch "NLP from Scratch" for bidirectional GRU
I have taken the code from the tutorial and attempted to modify it to include bi-directionality and any arbitrary numbers of layers for GRU. Link to the tutorial which uses uni-directional, single layer GRU: https://pytorch.org/tutorials/intermediate/seq2seq_translation_tutorial.html The model works fine, but when i ...
So I'm not sure if this is 100% correct as I'm just learning how to program RNNs, but i changed my code in a couple of extra areas. For one you'll notice that the error says m1: [1x384] so the result of torch.cat((embedded[0], hidden[0]), 1)) when putting this through the attn weight layer is not a dimension ending ...
https://stackoverflow.com/questions/58996451/
How to extract images, labels from csv file and create a trainset using torch?
I downloaded a dataset for facial key point detection the image and the labels were in a CSV file I extracted it using pandas but I don't know how to convert it into a tensor and load it into a data loader for training. dataframe = pd.read_csv("training_facial_keypoints.csv") dataframe['Image'] = dataframe['Image'].ap...
Create a subclass of torch.utils.data.Dataset, fill it with your data. You can pass desired torchvision.transforms to it and apply them to your data in __getitem__(self, index). Than you can pass it to torch.utils.data.DataLoader which allows multi-threaded loading of data. And PyTorch has an overwhelming documentati...
https://stackoverflow.com/questions/58997461/
error installing pytorch using pip on windows 10
I am trying to install pytorch with pip using pip install torch or pip3 install torch===1.3.1 torchvision===0.4.2 -f https://download.pytorch.org/whl/torch_stable.html with python 3.7.4 and with python 3.8 (latest stable release) both on 32 and 64 bit. and getting Collecting torch Using cached https://files...
I had the same problem. Now the problem is fixed. (2020-05-31) Visited the site pytorch.org and find "QUICK START LOCALLY" on homepage of pytorch.org. ( it' can find by scroll down little ) Checking the environment form of your system (ex: Windows, pip, python, ,,) then, you can see the install command. "pip install ...
https://stackoverflow.com/questions/59013496/
Turn CNN model into class
I am trying to build a CNN for multilabel classification in Pytorch (each image can have more than one label). So far I have built the model as follows: model.fc = nn.Sequential(nn.Linear(2048, 512), nn.ReLU(), nn.Dropout(0.2), ...
You should use torch.nn.BCEWithLogitsLoss for multilabel classification (and numerical stability), no LogSigmoid or NLLLoss as the output. You have to output N elements for each element in batch, where 1 on position N in vector would mean an existence of class N on image. Your network is fine, provided you only got 3...
https://stackoverflow.com/questions/59014699/
Can I specify kernel-weight specific learning rates in PyTorch?
I would like to set specific learning rates for each parameter on their lowest level. I.e. each value in a kernels weight and biases should have their own learning rate. I can specify filter-wise learning rates like that: optim = torch.optim.SGD([{'params': model.conv1.weight, 'lr': 0.1},], lr=0.01) But when I want...
I might have found a solution. As one can only input the whole weights and biases of a Conv Layer, we need to insert a learning rate having the same shape as the weight/bias tensor. Here is an example using torch.optim.Adam: torch.optim.CustomAdam([{'params': param, 'lr': torch.ones_like(param, requires_grad=False) *...
https://stackoverflow.com/questions/59018085/
I define a loss function but backward present error to me could someone tell me how to fix it
class loss(Function): @staticmethod def forward(ctx,x,INPUT): batch_size = x.shape[0] X = x.detach().numpy() input = INPUT.detach().numpy() Loss = 0 for i in range(batch_size): t_R_r = input[i,0:4] R_r = t_R_r[np.newaxis,:] t_R_i = inp...
Your forward(ctx,x,INPUT) takes two inputs, x and INPUT, thus backward should output two gradients as well, grad_x and grad_INPUT. In addition, in your snippet, you're not really computing a custom gradient, so you could compute that with Pytorch's autograd, without having to define a special Function. If this is w...
https://stackoverflow.com/questions/59019399/
pytorch debugging timeout with PyCharm
I have a frustrating problem, where I cannot debug my pytorch code while in Pycharm. While trying to inspect (breakpoint, then print e.g.) the code below, I receive a "Loading time out" import torch tensors = [] num_tensors = 16 shape = (1, 3, 512, 512) for i in range(num_tensors): tensors.app...
Are you using DataLoader? If yes, you can try reducing the num_workers to 0.
https://stackoverflow.com/questions/59030675/
.grad() returns None in pytorch
I am trying to write a simple script for parameter estimation (where parameters are weights here). I am facing problem when .grad() returns None. I have gone through this and this link also and understood the concept both theoretically and practically. For me following script should work but unfortunately, it is not w...
You're breaking the computation graph by declaring a new tensor for pred. Instead you can use torch.stack. Also, x_dt and pred are non-leaf tensors so the gradients aren't retained by default. You can override this behavior by using .retain_grad(). gamma = torch.tensor(2.0, device=device, dtype=torch.float, requires_g...
https://stackoverflow.com/questions/59031703/
any similar function like df.mask for tensor in pytorch?
I want to replace all 0s in a 2-D tensor with -5. With dataframe, i can easily do this: df = df.mask(df=0, -5) but this does not work for tensors. I have tried: y = torch.where(y = 0, -5, y)
There are two general ways. One, given above by prhmma is to use in-place mutation like y[y == 0] = -5. It is nice and efficient, but will break autograd operation. So if you want gradient to flow through y, you should not do that. The other is to use torch.where, as you have attempted. The proper incantation is y =...
https://stackoverflow.com/questions/59037704/
Pytorch equivalent of Google Seedbank
Does Pytorch have an equivalent of Google Seedbank ? Everything in Seedbank is (unsurprisingly) Tensorflow based, and I want to learn Pytorch.
You can check out Pytorch Hub. Compared to Seedback, it has more emphasis on re-useable models (and less on tutorials), although many entries do have Colab notebooks for reference.
https://stackoverflow.com/questions/59042241/
Conda package install [Errno 13] Permission denied while installing conda-forge::protobuf-3.8.0
I have a conda environment with Python 3.6 and something went wrong with my Pytorch installation so I tried to install it again. Towards the end of the installation I get this error: ERROR conda.core.link:_execute(700): An error occurred while installing package 'conda-forge::protobuf-3.8.0-py36h6de7cb9_1'. Rolling b...
I faced a similar error like this when I was trying to update/uninstall a python package(matplotlib) from my environment. The reason turned out to be that I had another python application which was running and had a matplotlib plot window open, so therefore since a process was accessing the package, it couldn't be dele...
https://stackoverflow.com/questions/59063954/
somehow my accuracy is very low on cifar10?
with torch.no_grad(): for data in test_loader: images,labels = data images, labels = images.to(device), labels.to(device) outputs, features = net(images) _ , predicted = torch.max(outputs,1) total += labels.size(0) correct += (predicted==labels).sum().item() print...
The trick training that exact dataset (cifar10) and getting better accuracy is to use data augmentation. Originally cifar10 has 50.000 images for training and 10.000 for validation. If you don't augment images while training you will overfit. Training accuracy will be much bigger than validation accuracy. So your go...
https://stackoverflow.com/questions/59067277/
Why multiprocessing suddenly stops after a certain number of tasks?
I'm trying to write some code to parallelize a bunch of tasks. Basically, the script is organized as the following. import multiprocessing as mp def obj_train(x): return x.train() class ServerModel(nn.Module): self.S = nn.Parameter(torch.rand(x, y), requires_grad=True) class ClientModel(nn.Module): s...
Could it be that you hit the maximum number of processes/threads your machine is able to handle? It is common, for example, when moving a web crawler from development to production that the machine does not allow more processes. I would give a look at the file /etc/sysctl.d and in case increase the number of pos...
https://stackoverflow.com/questions/59068181/
ModuleNotFoundError: No module named 'torch'
I try to use pytorch module by conda but I get an error Traceback (most recent call last): File "train.py", line 8, in <module> import torch ModuleNotFoundError: No module named 'torch' when I write conda list | findstr torch I see that torch is installed: What is the problem? I tried: conda update conda -...
Try the below mentioned one, surely it will work. conda install -c pytorch pytorch
https://stackoverflow.com/questions/59070936/
Use numpy in script class (torch.jit.script)
I was wondering if I can use numpy APIs in a function which is going to be scripted by torch.jit.script. I have this simple function which does not work: import torch import torch.nn as nn class MyModule(nn.Module): def __init__(self): super(MyModule, self).__init__() @torch.jit.ignore def call_np(): return...
I got an answered at the pytorch forum: https://discuss.pytorch.org/t/use-numpy-in-script-class-torch-jit-script/62351
https://stackoverflow.com/questions/59079411/
Forward Propagate RNN using Pytorch
I am trying to create an RNN forward pass method that can take a variable input, hidden, and output size and create the rnn cells needed. To me, it seems like I am passing the correct variables to self.rnn_cell -- the input values of x and the previous hidden layer. However, the error I receive is included below. I h...
I am not an expert at RNNs but giving it a try. class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size self.rnn_cell = nn.RNN(input_size, hidden_size) self.fc = nn.Linear(hidden_size, output_size) def forward(self, x...
https://stackoverflow.com/questions/59080681/
NOT using multiprocessing but get CUDA error on google colab while using PyTorch DataLoader
I've cloned my GitHub repo into google colab and trying to load data using PyTorch's DataLoader. global gpu, device if torch.cuda.is_available(): gpu = True device = 'cuda:0' torch.set_default_tensor_type('torch.cuda.FloatTensor') print("Using GPU") else: gpu = False device = 'cpu' print("U...
Not sure if you fixed it already but just in case someone else reads this, using n number of works activates pytorch multi processing. To disable it you need to have the default number of workers which is 0, not 1. Try setting num_workers to 0 or using the Torch Multiprocessing submodule.
https://stackoverflow.com/questions/59081290/
Running in Google Colab
Good evening. I want to run my python program on Google collab, but in what place I should download files and when open in python file? How do I open this file?
You can always upload files to Google colab and you can create a directory as well. You can create a directory named data And then upload the files which you want to be placed in the directory as shown below. * Remember the data uploaded or created during runtime will not be saved * Alternatively, you can save ...
https://stackoverflow.com/questions/59093925/
Flatten Tensor in Pytorch Convolutional Neural Network (size mismatch error)
I made a reproducible example with random pixels. I'm trying to flatten the tensors for the dense layers after the convolutional layers. The problem is at the intersection of the convolutional layers and the dense layers. I don't know how to put the right number of neurons. tl;dr I'm looking for the manual equivalent ...
Here's a function I made to automatically fit the right number of neurons while flattening a convolutional tensor: def flatten(w, k=3, s=1, p=0, m=True): """ Returns the right size of the flattened tensor after convolutional transformation :param w: width of image :param k: kernel size :par...
https://stackoverflow.com/questions/59108988/
How can I do to evaluate mean and std for a dataset?
I am using pytorch and the dataset fashion MNIST but I do not know how can I do to evaluate the mean and the std for this dataset. Here is my code : import torch from torchvision import datasets, transforms import torch.nn.functional as F transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize(...
Use this to calculate mean and std- loader = data.DataLoader(dataset, batch_size=10, num_workers=0, shuffle=False) mean = 0. std = 0. for images, _ in loader: batch_samples = images.size(0) # batch size (the last batch can have smaller siz...
https://stackoverflow.com/questions/59116831/
How to use gensim with pytorch to create an intent classifier (With LSTM NN)?
The problem to solve: Given a sentence, return the intent behind it (Think chatbot) Reduced example dataset (Intent on the left of dict): data_raw = {"mk_reservation" : ["i want to make a reservation", "book a table for me"], "show_menu" : ["what's the daily m...
You don't need neither a neural network nor word embeddings. Use parsed trees with NLTK, where intents are Verbs V acting on entities (N) in a given utterance: To classify a sentence, then you can use a Neural Net. I personally like BERT in fast.ai. Once again, you won't need embeddings to run the classification, an...
https://stackoverflow.com/questions/59120553/
Heroku: slug size too large after installing Pytorch
I've been getting the slug size too large warning (Compiled slug size: 789.8M is too large (max is 500M)) from Heroku and I can't figure out why, as my model size (cnn.pth below) is fairly small and my file directory is only 1.1mb in total: screenshot of directory. It seems like the size increase is caused by running ...
The pytorch package that you're installing comes with both cpu and gpu support, thus has a large size. It seems you're using the free version of heroku, and only require the cpu support. The solution is to install the pytorch package for cpu only i.e. In requirements.txt, write the wheel file path corresponding to the...
https://stackoverflow.com/questions/59122308/
How is spectral norm of a parameter calculated?
when I do, import torch, torch.nn as nn x = nn.Linear(3, 3) y = torch.nn.utils.spectral_norm(x) then it gives four different weight matrices, y.weight_u tensor([ 0.6534, -0.1644, 0.7390]) y.weight_orig Parameter containing: tensor([[ 0.2538, 0.3196, 0.3380], [ 0.4946, 0.0519, 0.1022], [-0.5...
I just finished reading the paper for this method which can be found on arxiv. If you have the appropriate mathematical background I would recommend reading it. See appendix A for the power algorithm which describes what u and v are. That said I'll try to summarize here. First, you should know that the spectral norm ...
https://stackoverflow.com/questions/59123577/
installing py-torch in anaconda , got error
C:\WINDOWS\system32>python -m pip install torch Collecting torch Using cached https://files.pythonhosted.org/packages/f8/02/880b468bd382dc79896eaecbeb8ce95e9c4b99a24902874a2cef0b562cea/torch-0.1.2.post2.tar.gz Requirement already satisfied: pyyaml in c:\programdata\anaconda3\lib\site-packages (from torch) (5.1) Bu...
Select the right options based on hardware configuration and install it from https://pytorch.org/get-started/locally/ Should work without any problems.
https://stackoverflow.com/questions/59129241/
Conv2d and the value of padding
I would like to ask about the value of padding we set in the Conv2d function. I know what zero-padding is. However, what does it mean that the padding is 0 for instance, or 1,2, or 3. What do these values mean? Do they represent the number of columns and rows that will be filled with zeros? Thanks a lot.
As the documentation states: padding controls the amount of implicit zero-paddings on both sides for padding number of points for each dimension. Therefore, padding=1 means you pad your input with 1 column and row from each size. If you want more control over the amount of padding and its value you can either use...
https://stackoverflow.com/questions/59131945/
How can we calculate receptive field of a network includes transposed convolutional layer?
A network I designed includes transposed convolutional layer. (ConvTranspose2d in pytorch) I want to get receptive field size of my network. Does the concept of receptive field also hold on with transposed convolutional layer? If yes, then how can I get it?
You can use the library pytorch-receptive-field to automatically compute all layers' receptive fields.
https://stackoverflow.com/questions/59132357/
Train a single pytorch model on multiple GPUs with some layers fixed?
I met some problems when using pytorch DistributedDataParallel. The situation is: My model is A, and it has been trained on a single GPU as usual. Suppose that there are three layers in A: class A(nn.module): def __init__(self): super(A,self).__init__() self.layer0 = layer0 self.layer1 = ...
If you only try to optimize part of the parameters, why not try controlling this via the optimizer, rather than the model? You can leave your model as-is (wrapped in a DistributedDataParallel) and pass only part of its parameters to the relevant optimizer.
https://stackoverflow.com/questions/59134785/
Receptive fields for feed forward network
I am pretty new to artificial intelligence and neural networks. I have implemented a feed-forward neural network in PyTorch for classification on the MNIST data set. Now I want to visualize the receptive fields of (a subset of) hidden neurons. But I am having some problems with understanding the concept of receptive fi...
I have previously described the concept of a receptive field for CNNs in this answer, just to give you some context that might be useful in my actual answer. It seems that you are also struggling with the idea of receptive fields. Generally, you can best understand it by asking the question "which part of the (previou...
https://stackoverflow.com/questions/59140195/
Running PyTorch multiprocessing in a Docker container with Gunicorn worker manager
I am trying to deploy a service on GCP. It's a Docker container that uses Gunicorn for worker management. The code runs a torch.multiprocessing.process to run a POST response as a background process. This works if I run the script using a python3 command. But hangs when using Gunicorn. My understanding is that C...
I spent a lot of time investigating a similar issue. Pytorch calls were stuck when running on a docker container with gunicorn. The solution that worked for me was removing the --preload flag from the Docker gunicorn command.
https://stackoverflow.com/questions/59144482/
Stacking tensors in a list of tuples of tensors
I have a list of tuples of PyTorch tensors. It looks like this: [ (tensor([1, 2, 3]), tensor([4, 5, 6, 7]), tensor([8])), (tensor([9, 10,11]), tensor([11,12,13,14]), tensor([15])), (tensor([16,17,18]), tensor([19,20,21,22]), tensor([23])), ... ] Tensors in each column (that is, tensors that positio...
If anyone gets themselves into the same convoluted scenario, I was able to solve it with a lovely one-liner: tuple(map(torch.stack, zip(*x))) In this case, x is the original list I mentioned above. This line of code transforms x into the exact desired format.
https://stackoverflow.com/questions/59149275/
How can I save model weights to mlflow tracking sever using pytorch-lightning?
I would like to save model weights to mlflow tracking using pytorch-lightning. pytorch-lightning supports logging. However, it seems that saving model weights as a artifact on mlflow is not supported. At first, I planed to override ModelCheckpoint class to do it, but I found it is difficult for me because of complex M...
As @xela said, you can use the experiment object of the mlflow logger to log artifacts. In case you want to frequently log model weights during training, you could extend ModelCheckpoint: class MLFlowModelCheckpoint(ModelCheckpoint): def __init__(self, mlflow_logger, *args, **kwargs): super().__init__(*arg...
https://stackoverflow.com/questions/59149725/
Cannot install pytorch in a virtualenv on windows
I know there are a few topics about that on this website but still, I can't find the solution. So here is what I did : I created a projecton Visual Studio 19 for python. I added an virtual environment with Python 3.7 using the file requirements.txt It contains mypy==0.750 pylint==2.4.4 pytest==5.3.1 matplotlib==3.1...
I went to the PyTorch documentation on how to "Start Locally" and selected what seems to be your environment: PyTorch Build: Stable (1.3) Your OS: Windows Package: Pip Language: Python 3.7 CUDA: None The resulting instruction I got back as a result is: pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https:...
https://stackoverflow.com/questions/59152261/
why is my Neural Network stuck at high loss value after the first epochs
I'm doing regression using Neural Networks. It should be a simple task for NN to do, I have 10 features and 1 output that I want to predict.I’m using pytorch for my project but my Model is not learning well. the loss start with a very high value (40000), then after the first 5-10 epochs the loss decrease rapidly to 600...
considering that your training and dev loss are decreasing over time, it seems like your model is training correctly. With respect to your worry regarding your training and dev loss values, this is entirely dependent on the scale of your target values (how big are your target values?) and the metric used to compute the...
https://stackoverflow.com/questions/59153248/
How to install PyTorch on Python 3.7 / Windows 10 with pip
I am trying to install PyTorch 1.3 using pip : pip3 install torch==1.3.1+cpu torchvision==0.4.2+cpu -f https://download.pytorch.org/whl/torch_stable.html I got the command line from this page : https://pytorch.org/get-started/locally/#start-locally It fails, with the following error message : ERROR: Could not fin...
You error is being triggered because the version 1.3.1+cpu doesn't exist. If you go to pytorch.org you will be able to select a version of pytorch and your OS, where it will give you a command to install pyTorch correctly, for Python 3.7 and PIP use the following: pip3 install --find-links https://download.pytorch.or...
https://stackoverflow.com/questions/59161453/
How I make pytorch read the numpy format?
I'm trying to create a code with PyTorch and Keras that uses the BERT algorithm to detect fake news, but I got an error tells me: can't convert np.ndarray of type numpy.bool_. The only supported types are: double, float, float16, int64, int32, and uint8. Please access the code on my Google Codelab. The error can be...
I can't confirm but I believe your problem will be solved by changing: train_y = np.array(train_labels) == 'fake' test_y = np.array(test_labels) == 'fake' to: train_y = (np.array(train_labels) == 'fake').astype(int) test_y = (np.array(test_labels) == 'fake').astype(int) The train_y data is currently an array of t...
https://stackoverflow.com/questions/59167119/
How to make a PyTorch Distribution on GPU
Is it possible to make the PyTorch distributions create their samples directly on GPU. If I do from torch.distributions import Uniform, Normal normal = Normal(3, 1) sample = normal.sample() Then sample will be on CPU. Of course it is possible to do sample = sample.to(torch.device("cuda")) to make it on GPU. But is...
Distributions use the reparametrization trick. Thus giving size 0 tensors which are on GPU to the distribution constructor works. As follows: normal = Normal(torch.tensor(0).to(device=torch.device("cuda")), torch.tensor(1).to(device=torch.device("cuda")))
https://stackoverflow.com/questions/59179609/
pytorch net creation does not generate weights if done in a list
I'm creating a net in pytorch by writing a class called MyNet with init() and forward() method. If I create a layer in init() like: self.fc = nn.Linear(5, 10) everything works fine and net = MyNet() paramL = list(net.parameters()) gives me a list with some weights inside. However, if I create layers in the follow...
In simple terms, this is because it is not a torch.nn object. For this use torch.nn.Sequential. For example, self.Layer = torch.nn.Sequential(nn.Linear(5,10), nn.Linear(10,10), ...)
https://stackoverflow.com/questions/59180955/
Wrong value of standard deviation
Hello I am trying to evaluate the standard deviation and the mean of the dataset MNIST and I get a wrong value for the standard deviation. Here is my code : import torch from torchvision import datasets, transforms import torch.nn.functional as F loader = torch.utils.data.DataLoader(datasets.MNIST( '../data', train=T...
torch.std uses the batches mean as part of the computation so it's not the same as using torch.std on the entire dataset since that would use a different mean. We can use the following well known expression for variance to get the desired result Var(X) = E[X**2] - E[X]**2 mean = 0. mean_square = 0. samples = 0 for im...
https://stackoverflow.com/questions/59182363/
windows spyder invalid syntax error while running py file
I am trying to run the last example from the page. I have cloned the repository in the directory C:/Users/nn/Desktop/BERT/transformers-master. I am on windows machine and using spyder IDE. Why i do get below error and how could i resolve it? How do i input the initial part of the poem? import os os.chdir('C:/Users/nn...
Did you read the pre-requisites of the task: Installing PyTorch-Transformers on your Machine Installing Pytorch-Transformers is pretty straightforward in Python. You can simply use pip install: pip install pytorch-transformers or if you are working on Colab: !pip install pytorch-transformers ...
https://stackoverflow.com/questions/59182421/
How to apply bounds on a variable when performing optimisation in Pytorch?
I am trying to use Pytorch for non-convex optimisation, trying to maximise my objective (so minimise in SGD). I would like to bound my dependent variable x > 0, and also have the sum of my x values be less than 1000. I think I have the penalty implemented correctly in the form of a ramp penalty, but am struggling wit...
I meet the same problem with you. I want to apply bounds on a variable in PyTorch, too. And I solved this problem by the below Way3. Your example is a little compliex but I am still learning English. So I give a simpler example below. For example, there is a trainable variable v, its bounds is (-1, 1) v = torch.tensor(...
https://stackoverflow.com/questions/59192705/
Weight Initialization from pretrained BERT error in pytorch
I am trying to train the model using pretrained model(BERT) using pytorch. The pretrained model weights still arent accepted. I see this error: Weights of BertForMultiLable not initialized from pretrained model: ['classifier.weight', 'classifier.bias'] Weights from pretrained model not used in BertForMultiLable: ['cl...
for the Error you cited, actually I think that is only a Warning that states you you are loading on your architecture BertForMultiLable the Weights from pretrained model that was not trained for that specific tasks. Similar warning discussion here The real error here it's another: IndexError: tuple index out of range....
https://stackoverflow.com/questions/59195071/
Text classification with torchnlp
i'm trying to build a neural network using pytorch-nlp (https://pytorchnlp.readthedocs.io/en/latest/). My intent is to build a network like this: Embedding layer (uses pytorch standard layer and from_pretrained method) Encoder with LSTM (also uses standard nn.LSTM) Attention mechanism (uses torchnlp.nn.Attention) Deco...
You are on the right track with padding all sequences to a specific dimension. You will have to pick a dimension that is larger than "most" of your sentences but you will need to cutoff some sentences. This blog article should help.
https://stackoverflow.com/questions/59215618/
PyTorch - to NumPy yields unsized object?
Converting a PyTorch tensor to NumPy I get print(nn_result.shape) # (2433, 2) np_result = torch.argmax(nn_result).numpy() type(np_result) # <type 'numpy.ndarray'> print(len(np_result)) TypeError: len() of unsized object Why? I thought per documentation the numpy() function would return a proper ndarray, yet i...
Perhaps you'd want to use torch.argmax(nn_result, dim=1) ? Since dim defaults to 0, it returns just a single number constructed as a tensor. Let me illustrate with the below example: >>> x = np.array(1) >>> x.shape () >>> len(x) Traceback (most recent call last): File "<stdin>", line...
https://stackoverflow.com/questions/59217874/
PyTorch vectorise sum lookup quantity into buckets
Using PyTorch, I have figured out the following code for calculating totals of an item's property by some "bucket index": DATASET_SIZE = 10 NUM_BUCKETS = 4 bucket_assignment = torch.tensor([0,1,2,3,0,1,2,3,0,1], dtype = torch.long) values_to_add = torch.tensor([1,2,3,4,5,6,7,8,9,10], dtype = torch.float) buckets = tor...
If the batch size is the problem you could use torch.masked_select to get the values to add up for each bucket torch.masked_select(values_to_add, bucket_assignment == bucket_num), where PyTorch will broadcast the values_to_add and then only iterate over the buckets in plain python like so: def bucket_sizes(bucket_num)...
https://stackoverflow.com/questions/59219635/
how to convert mnist images to variables images and labels
I have a code as below: dataset = MNIST(path=data_path, download=True, shuffle=True) if train: images, labels = dataset.get_train() else: images, labels = dataset.get_test() images, labels = images[:n_examples], labels[:n_examples] images, labels = iter(images.view(-1, 784) / 255), iter(labels) but when i ru...
Yes, it looks like class does not exist in the package anymore. I was able to find the source code for the package you are looking for: import os import functools import operator import gzip import struct import array import tempfile try: from urllib.request import urlretrieve except ImportError: from urllib ...
https://stackoverflow.com/questions/59223995/
Text generation using huggingface's distilbert models
I've been struggling with huggingface's DistilBERT model for some time now, since the documentation seems very unclear and their examples (e.g. https://github.com/huggingface/transformers/blob/master/notebooks/Comparing-TF-and-PT-models-MLM-NSP.ipynb and https://github.com/huggingface/transformers/tree/master/examples/...
To decode the output, you can do prediction_as_text = tokenizer.decode(output_ids, skip_special_tokens=True) output_ids contains the generated token ids. It can also be a batch (output ids at every row), then the prediction_as_text will also be a 2D array containing text at every row. skip_special_tokens=True ...
https://stackoverflow.com/questions/59240668/
CTC: blank must be in label range
summary I'm adding alphabets to captcha recognition, but pytorch's CTC seems to not working properly when alphabets are added. What I've tried At first, I modified BLANK_LABEL to 62 since there are 62 labels(0-9, a-z, A-Z), but it gives me runtime error blank must be in label range. I also tried BLANK_LABEL=0 and then ...
This error will occur when the index of blank is larger than the total number of classes, which equals number of chars + blank. What's more, the index starts from 0, instead of 1, so if you have 62 characters in total, their index should be 0-61 and the index of blank should be 62 instead of 63. (Or you can set blank a...
https://stackoverflow.com/questions/59242835/
Why does torch.from_numpy require a different byte ordering while matplotlib doesn't?
Here is a piece of code (running on Linux CentOS 7.7.1908, x86_64) import torch #v1.3.0 import numpy as np #v1.14.3 import matplotlib.pyplot as plt from astropy.io.fits import getdata #v3.0.2 data, hdr = getdata("afile.fits", 0, header=True) #gives dtype=float32 2d array plt.imshow(data) plt.show() This gives ...
FITS stores data in big-endian byte ordering (at the time FITS was developed this was a more common machine architecture; sadly the standard has never been updated to allow flexibility on this, although it could easily be done with a single header keyword to indicate endianness of the data...) According to the Numpy d...
https://stackoverflow.com/questions/59247385/
Using Pytorch's dataloaders & transforms with sklearn
I have been using pytorch a lot and got used to their dataloaders and transforms, in particular when it comes to data augmentation, as they're very user-friendly and easy to understand. However, I need to run some ML models from sklearn. Is there a way to use pytorch's dataloaders for sklearn ?
Yes, you can. You can do this with sklearn's partial_fit method. Read HERE. 6.1.3. Incremental learning Finally, for 3. we have a number of options inside scikit-learn. Although all algorithms cannot learn incrementally (i.e. without seeing all the instances at once), all estimators implementing the partia...
https://stackoverflow.com/questions/59253507/
State persistence in shared LSTM layers in Keras
I am trying to use a shared LSTM layer with state in a Keras model, but it seems that the internal state is modified by each parallel use. This raises two questions: When training a model with a shared LSTM layer and using stateful=True, are the parallel uses updating the same state also during training? If my observ...
Based on my current understanding of the behaviour of LSTMs (and other RNNs) in Keras is that using a shared LSTM layer in a stateful=True mode does not work as one would expect and there is only one state variable that gets updated through all the parallel uses. So the answers to the questions appear to be: Yes, th...
https://stackoverflow.com/questions/59281849/
PyTorch: initializing weight with numpy array + create a constant tensor
I have the following code : self.wi = nn.Embedding(num_embeddings, embedding_dim) self.wj = nn.Embedding(num_embeddings1, embedding_dim) self.bi = nn.Embedding(num_embeddings, 1) self.bj = nn.Embedding(num_embeddings1, 1) self.wi.weight.data.uniform_(-1, 1) self.wj.weight.data.uniform_(-1, 1) self.bi.weight.data.zero...
You can initialize embedding layers with the function nn.Embedding.from_pretrained(). In your specific case, you would still have to firstly convert the numpy.array to a torch.Tensor, but otherwise it is very straightforward: import torch as t import torch.nn as nn import numpy as np # This can be whatever initializ...
https://stackoverflow.com/questions/59294274/
Using tensorboard in pytorch, but get blank page?
I am using tensorboard in pytorch 1.3.1, and I did exactly the same in the pytorch docs for tensorboard. After running tensorboard --logdir=runs, I got this enter image description here. $ tensorboard --logdir=runs TensorFlow installation not found - running with reduced feature set. Serving TensorBoard on localhost;...
I am using Torch 1.4.0 on Windows and I had the same issue. Turns out I had installed the 2.x version of Tensorboard. I reverted back to 1.15.0 and it solved the issue.
https://stackoverflow.com/questions/59308202/
How to convert Conv1d into Conv2d? [PyTorch]
Is it possible with PyTorch to use Conv2d to perform a Conv1d? The question may seem weird, but I need to use a tool that is not compatible with conv1d, but it works with conv2d. What if I have Conv1d(in,out, kernel_size=3, stride=stride, padding=1, bias=False)? May unsqueeze help me? I have the same problem with Avg...
A Conv2D is mostly a generalized version of Conv1D. You can of course use a degenerate version of Conv2D to reproduce a 1D convolution - You'll need to add in another dimension to the data: data_pnt = data_pnt [..., numpy.newaxis] You'll also need to specify the kernel size - You'll be choosing a 1D kernel - for e...
https://stackoverflow.com/questions/59308390/
Is Pytorch DataLoader Iteration order stable?
Is the iteration order for a Pytorch Dataloader guaranteed to be the same (under mild conditions)? For instance: dataloader = DataLoader(my_dataset, batch_size=4, shuffle=True, num_workers=4) print("run 1") for batch in dataloader: print(batch["index"]) print("run 2") for batch in dataloade...
The short answer is no, when shuffle=True the iteration order of a DataLoader isn't stable between iterations. Each time you iterate on your loader the internal RandomSampler creates a new random order. One way to get a stable shuffled DataLoader is to create a Subset dataset using a shuffled set of indices. shuffled...
https://stackoverflow.com/questions/59314174/
install conda on windows with conda or pip
I am trying to install pytorch on my window. First, I get command conda install pytorch torchvision cpuonly -c pytorchfrom here (PyTorch Build:Stable(1.3);Your OS:Windows;Package:Conda;Language:Python3.6;CUDA:None), there are some problems described as followings: **(python36) C:\Users\li_dan0109>conda install pytor...
It looks as though you may have the 32-bit installation of Python, in which case you're issue is this: #16633. Just be aware, that pyTorch doesn't work on 32-bit systems. Please use Windows and Python 64-bit version.
https://stackoverflow.com/questions/59315344/
Pytorch Deep Learning - Class Model() and training function
I am new to Pytorch and I am going through this tutorial to figure out how to do deep learning with this library. I have problem figuring out part of the code. There is a class called Net and an object called model instantiated from it. Then there is the training function called train(epoch). In the next line in the...
train vs model.train The def train(epochs): ... is the method to train the model and is not an attribute of Net class. model is an object of Net class, that inherits from nn.Module. In PyTorch, all layers inherit from nn.Module and that gives them a lot of common functionality like model.children() or layer.children(),...
https://stackoverflow.com/questions/59320800/
Using pretrained models in Pytorch for Semantic Segmentation, then training only the fully connected layers with our own dataset
I am learning Pytorch and trying to understand how the library works for semantic segmentation. What I've understood so far is that we can use a pre-trained model in pytorch. I've found an article which was using this model in the .eval() mode but I have not been able to find any tutorial on using such a model for tra...
Assume you start with a pretrained model called model. All of this occurs before you pass the model any data. You want to find the layers you want to train by looking at all of them and then indexing them using model.children(). Running this command will show you all of the blocks and layers. list(model.children()) ...
https://stackoverflow.com/questions/59321942/
Custom backward/optimization steps in pytorch-lightning
I would like to implement the training loop below in pytorch-lightning (to be read as pseudo-code). The peculiarity is that the backward and optimization steps are not performed for every batch. (Background: I am trying to implement a few-shots learning algorithm; although I need to make predictions at every step -- f...
This is a good way to do it! that's what the hooks are for. There is a new Callbacks module that might also be helpful: https://pytorch-lightning.readthedocs.io/en/0.7.1/callbacks.html
https://stackoverflow.com/questions/59327048/
RuntimeError: cuda runtime error (710) : device-side assert triggered at
Traning the image classification with pytorch got following error messageK RuntimeError Traceback (most recent call last) in 29 print(len(train_loader.dataset),len(valid_loader.dataset)) 30 #break ---> 31 train_loss, train_acc ,model=...
What was your loss function? I got this error too. My problem was a multi-class classification and I was using a crossEntropy loss. As it say in the documentations, labels should be in the range [0, C-1] where C is number of classes. But my labels were not in the range and when I used proper values for labels, Everythi...
https://stackoverflow.com/questions/59331326/
Why Keras behave better than Pytorch under the same network configuration?
Recently, I have compared unet++ implementation of Keras version and Pytorch version on the same dataset. However, with Keras the loss decrease continuously and the accuracy is higher after 10 epochs, while with Pytorch the loss decrease unevenly and the accuracy is lower after 10 epochs. Anyone has met such problems...
Well, it's pretty hard to say without any code snippets. that being said, in general, initialization is way more important than you might think. I'm sure that the default initialization of pytorch is different from keras and I had similar issues in the past. Another thing to check is the optimizer parameters, make sur...
https://stackoverflow.com/questions/59344571/
Is there any diffrence between index_select and tensor[sequence] in PyTorch?
everyone. I'm new to PyTorch. Now I'm learning the indexing of a tensor. I notice that we can indexing a tensor by tensor.index_select() and tensor[sequence]. In [1]: x = torch.randn(3, 4) In [2]: indices = torch.tensor([0, 2]) In [3]: x.index_select(0, indices) Out[3]: tensor([[ 0.2760, -0.9543, -1.0499, 0.7828]...
This looks like a remnant of old (slower) indexing. See this pull request. I also think you used to not be able to do binary logical indexing on tensors. a = torch.randn((1,3,4,4)) dim = 2 indices = [0,1] %timeit a.index_select(dim, torch.tensor(indices)) 12.7 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 1...
https://stackoverflow.com/questions/59344751/
Pytorch RuntimeError: Expected object of device type cuda but got device type cpu for argument #1 'self' in call to _th_index_select
I am training a model that takes tokenized strings which are then passed through an embedding layer and an LSTM thereafter. However, there seems to be an error in the input, as it does not pass through the embedding layer. class DrugModel(nn.Module): def __init__(self, input_dim, output_dim, hidden_dim, drug_embed...
setting model.device to cuda does not change your inner module devices, so self.lstm, self.char_embed, and self.dist_fc are all still on cpu. correct way of doing it is by using DrugModel().to(device) in general, it's better not to feed a device to your model and write it in a device-agnostic way. to make your init_ls...
https://stackoverflow.com/questions/59347111/
Cannot convert Pandas Dataframe columns to float
I am using Pandas to read a CSV file containing several columns that must be converted to floats: df = pd.read_csv(r'dataset.csv', low_memory=False, sep = ',') df.head(2) Coal Flow 01 Air Flow 01 Outlet Temp 01 Inlet Temp 01 Bowl DP 01 Current 01 Vibration 01 0 51.454407 101.432340 64.9...
Why not just use astype: df = pd.read_csv(r'dataset.csv', low_memory=False, sep = ',') df[features] = df[features].apply(lambda x: x.apply(lambda x: x[0]).astype(float))
https://stackoverflow.com/questions/59350190/
Pytorch is installed but is not working on ubuntu 18.04
I am trying to install Pytorch via pip on ubuntu 18.04.I have python 3.6 and my laptop is HP-Pavilion notebook 15 The installation seems to be right because i get the message: Installing collected packages: torch, torchvision Successfully installed torch-1.3.1+cpu torchvision-0.4.2+cpu i run the verification c...
How are you executing the python script? Which python are you using? Maybe you installed the package in a different python version? Try to set alias to the python you want to use: alias python=/usr/local/bin/python3.6 Then pip install the package with that python alias you will always be using. python pip install ...
https://stackoverflow.com/questions/59358141/
Is there a way to write a custom BCE loss in pytorch?
I am writing a custom BCE in pytorch but in some cases it returns -inf and nan most cases. Which is due to the log function. bce_loss=y_true*torch.log2(y_pred) +(one_torch-y_true)*torch.log2(one_torch-y_pred) Is there a way to rewrite this? Note y_pred is a sigmoid output which is between 0 and 1.
You can clamp the preds to stop from log error. y_pred = torch.clamp(y_pred, 1e-7, 1 - 1e-7)
https://stackoverflow.com/questions/59366048/
Use skimage feature extractors in PyTorch Transforms
I want to apply skimage’s Local Binary Pattern feature extraction on my data, and was wondering if there was any possibility of doing this inside my torch’s Transforms, which right now is the following: data_transforms = { 'train': transforms.Compose([ transforms.CenterCrop(178), transforms.RandomH...
You can implement the Transform using the lamdba funtion. As @dhananjay correctly pointed out. Building on that comment, the implementation would be as follows: def lbp(x): radius = 2 n_points = 8 * radius METHOD = 'uniform' lbp = local_binary_pattern(x, n_points, radius, METHOD) return lbp data...
https://stackoverflow.com/questions/59376332/
pytorch: RuntimeError: bool value of Tensor with more than one value is ambiguous
it works with x[x >= 0.2] = 1 x[x < 0.2] = 0 x is a tensor here. but when i am trying to use x[x > 0 and x < 1] = 1 it reports: RuntimeError: bool value of Tensor with more than one value is ambiguous ? dose anyone know why?
Just a syntax thing. x = torch.randn((1,3,20,20)) x[(x > 0) & (x < 1)] = 1
https://stackoverflow.com/questions/59381021/
Construct a rotation matrix in Pytorch
I want to construct a rotation matrix, which have unknown Eular angles. I want to build some regression solution to find the value of Eular angles. My code is here. roll = yaw = pitch = torch.randn(1,requires_grad=True) RX = torch.tensor([ [1, 0, 0], [0, cos(roll), -sin(roll)], ...
torch.tensor is viewed as an operation and that is not able to do backpropgation. A dirty way to fix your code: roll = torch.randn(1,requires_grad=True) yaw = torch.randn(1,requires_grad=True) pitch = torch.randn(1,requires_grad=True) tensor_0 = torch.zeros(1) tensor_1 = torch.ones(1) RX = torch.stack([ ...
https://stackoverflow.com/questions/59387182/
RuntimeError: Error(s) in loading state_dict for Generator: size mismatch for weights and biases using Pytorch
I'm training a 3D-GAN to generate MRI volumes. I defined my model as follows: ###### Definition of the generator ###### class Generator(nn.Module): def __init__(self, ngpu): #super() makes Generator a subclass of nn.Module, so that it inherites all the methods of nn.Module super(Generator, self).__init__() ...
The model you loaded and the target model is not identical, so the error raise to inform about mismatches of size, layers, check again your code, or your saved model may not be saved properly
https://stackoverflow.com/questions/59390160/
What is the fastest Mask R-CNN implementation available
I'm running a Mask R-CNN model on an edge device (with an NVIDIA GTX 1080). I am currently using the Detectron2 Mask R-CNN implementation and I archieve an inference speed of around 5 FPS. To speed this up I looked at other inference engines and model implementations. For example ONNX, but I'm not able to gain a faste...
It's almost impossible to get higher inference speed for Mask R-CNN on GTX 1080. You may check detectron2 by Facebook AI Research. Otherwise, I'd suggest to use YOLACT - (You Only Look At CoefficienTs), it can achieve real-time instance segmentation. On the other hand, if you don't need instance segmentation, you can ...
https://stackoverflow.com/questions/59394530/
RuntimeError: Given input size: (10x7x7). Calculated output size: (10x0x0). Output size is too small
Trying to train the mnist 28x28x1 images my model is def __init__(self): super(CNN_mnist, self).__init__() self.conv = nn.Sequential( # 3 x 128 x 128 nn.Conv2d(1, 32, 3, 1, 1), nn.BatchNorm2d(32), nn.LeakyReLU(0.2), # 32 x 128 x 128 ...
Your [avg_pool] layer expects its input size to be (at least) 32x32, as the kernel size defined for this layer is 32. However, given the size of the input, the feature map this pooling layer gets is only 7x7 in size. This is too small for kernel size of 32. You should either increase the input size, or define a smalle...
https://stackoverflow.com/questions/59405042/
how to adjust dataloader and make a new dataloader?
let say I have a data loader of cifar10 if I want to remove some value from the dataloader and make a new dataloader how should I do it? def load_data_cifar10(batch_size=128,test=False): if not test: train_dset = torchvision.datasets.CIFAR10(root='/mnt/3CE35B99003D727B/input/pytorch/data', train=True, ...
You can use the Subset dataset. This takes another dataset as input as well as a list of indices to construct a new dataset. Say you want the first 1000 entries, then you could do subset_train_dset = torch.utils.data.Subset(train_dset, range(1000)) You can also construct datasets composed of multiple datasets using ...
https://stackoverflow.com/questions/59412287/
loop through the batch image loader pytorch
Let say I have batch with imgs = torch.Size([128, 1, 28, 28]) if I want to loop through the each image for img in imgs: print(img.shpae) -> torch.Size([1, 28, 28]) if I want to get a torch.Size([1,1, 28, 28]) for each image what should I do?
unsqueeze Just pass dim, In which position you want to add one extra singleton dimension. imgs = torch.zeros([128, 1, 28, 28]) # dim (int) – the index at which to insert the singleton dimension imgs.unsqueeze_(dim = 1) imgs.shape >>> torch.Size([128, 1, 1, 28, 28])
https://stackoverflow.com/questions/59419648/
how to import coco_utils and coco_eval?
To get a PyTorch script to work, I need to be able to do: import coco_utils import coco_eval I'm using Ubuntu 18.04 with Python 3. Based on this post: How to install COCO PythonAPI in python3 I've done the following so far: cd ~ git clone https://github.com/cocodataset/cocoapi.git cd cocoapi/PythonAPI # open ...
coco_utils.py and coco_eval.py must be the name of the files that should be in the repository you're trying to use. Possibly you're looking for the object detection reference training scripts provided in the detection (vision/references/detection/) module of torchvision.
https://stackoverflow.com/questions/59433282/
RuntimeError: Only Tensors of floating point dtype can require gradients
RuntimeError: Only Tensors of floating point dtype can require gradients got following error from input = Variable(preprocessed_img, requires_grad = True) img=train_loader.dataset.data[0] print(type(img)) img_tensor = torch.tensor(img) preprocess_image(img) > def preprocess_image(img): means=[0.485, 0.45...
Use torch.Tensor(img) instead of torch.tensor(img). This should probably solve your issue.
https://stackoverflow.com/questions/59433832/
How do I make a minimal and reproducible example for neural networks?
I would like to know how to make a minimal and reproducible deep learning example for Stack Overflow. I want to make sure that people have enough information to pinpoint the exact problem with my code. Is it enough to just provide the traceback? c:\users\samuel\appdata\local\programs\python\python35\lib\site-packa...
Here are a few tips to make a reproducible, minimal deep learning Example. It's good advice whether it be for Keras, Pytorch, or Tensorflow. We can't use your data, but in most cases, it doesn't matter. All we need is the right shape. Use randomly generated numbers of the right shape. E.g., np.random.randint(0...
https://stackoverflow.com/questions/59437658/
How to use trained deep learning model to predict in excel?
After we trained my neural network and saved my model with tensorflow, we can load the model and predict result like following: from keras.models import load_model model = load_model('my_model.h5') result = model.predict(test_input) Is there any way we can use the trained model in excel to do the similar job? I ass...
My solution is to use xlwings (https://www.xlwings.org/) to call python code.
https://stackoverflow.com/questions/59449308/
How can we convert a .pth model into .pb file?
I have already got the complete model by using pytorch, however I wanna convert the .pth file into .pb, which could be used in Tensorflow. Does anyone have some ideas?
You can use ONNX: Open Neural Network Exchange Format To convert .pth file to .pb First, you need to export a model defined in PyTorch to ONNX and then import the ONNX model into Tensorflow (PyTorch => ONNX => Tensorflow) This is an example of MNISTModel to Convert a PyTorch model to Tensorflow using ONNX from on...
https://stackoverflow.com/questions/59450262/
Local fully connected layer - Pytorch
Assume we have a feature representation with kN neurons before the classification layer. Now, the classification layer produces an output layer of size N with only local connections. That is, the kth neuron at the output is computed using input neurons at locations from kN to kN+N. Hence, every N locations in the inp...
This is currently triaged on the PyTorch issue tracker, in the mean time you can get a similar behavious using fold and unfold. See this answer: https://github.com/pytorch/pytorch/issues/499#issuecomment-503962218 class LocalLinear(nn.Module): def __init__(self,in_features,local_features,kernel_size,padding=0,str...
https://stackoverflow.com/questions/59455386/
How to get top k accuracy in semantic segmentation using PyTorch?
How do you compute the top k accuracy in semantic segmentation? In classification, we might compute the topk accuracy as: correct = output.eq(gt.view(1, -1).expand_as(output))
You are looking for torch.topk function that computes the top k values along a dimension. The second output of torch.topk is the "arg top k": the k indices of the top values. Here's how this can be used in the context of semantic segmentation: Suppose you have the ground truth prediction tensor y of shape b-h...
https://stackoverflow.com/questions/59474987/
How to run lua ML model from Google Colab
I am trying to run this neural style transfer model from Github but on Google Colab because my computer doesn't have enough memory/CPU/anything. I have mounted my google drive to my notebook, cloned the repo onto my drive by following this tutorial downloaded the models to my drive folder, and just to test that it wor...
First: %cd /content/ !git clone https://github.com/nagadomi/distro.git torch --recursive import os os.chdir('./torch/') !bash install-deps !./install.sh !. ./install/bin/torch-activate Now it should work using absolute path to th: !/content/torch/install/bin/th neural_style.lua -style_image examples/inputs/picasso_sel...
https://stackoverflow.com/questions/59478109/
PureFrameworkTensorFoundError, Runtime error -FedeartedLearning
I am trying a Linear Regression algorithm with Federated learning using Pytorch and I face the following error. I am implementing it on Colab. According to me this error might be due to some code line in the train() function. Kindly help is you have worked with Pysyft and have faced such error before. RuntimeError: i...
you have a typo here: data_alice = x_data[2:0] target_alice = y_data[2:0] Should be [2:] Because data_alice is failing, you had this error.
https://stackoverflow.com/questions/59484278/
azure ml & Pytorch: sample conda-dependencies.yml and docker?
Could you please point me to the documentation sample showcasing how to put together pytorch dependencies for training on AzureML? Few related questions to the scenario of running pytorch training workloads on AzureML: How can I set cuda version to 10.1? Could you please point to sample demonstrating how to use “of...
Install Pytorch with CUDA Version 10.1 with the following command on windows pip3 install torch===1.3.1 torchvision===0.4.2 -f https://download.pytorch.org/whl/torch_stable.htm. From .yml file: https://github.com/Azure/MachineLearningNotebooks/blob/master/how-to-use-azureml/ml-frameworks/pytorch/deployment/train-hyp...
https://stackoverflow.com/questions/59492635/
PyTorch regression is producing the same numbers as prediction
I have applied a simple NN for regression to the traditional boston housing price dataset. The problem I’m getting is, when I make predictions using the trained model it always predicts the same numbers. Here is my code: import numpy as np import pandas as pd from sklearn import datasets data = datasets.load_boston()...
It seems to me that the model does not fit to your dataset well. After inspecting your code, I think I could guess where went wrong. The way you perform gradient descent is somehow incorrect to me. Bear in mind that we are optimizing on a non-convex function. So pack the whole train dataset in a batch would not work, ...
https://stackoverflow.com/questions/59506405/
Can't use GPU with Pytorch
I keep getting this error when trying to use Pytorch. RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU. I installed Pytorch u...
You can fix this error by installing CUDA 10.2 (The Latest Version) and, additionally re-install Pytorch with this command: conda install pytorch torchvision cudatoolkit=10.2 -c pytorch
https://stackoverflow.com/questions/59506935/