instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Why does the CrossEntropy loss not go down during training of my network?
I am fairly new to Pytorch and I am currently trying to implement the network in this paper: https://arxiv.org/pdf/1811.06621.pdf?fbclid=IwAR3Ya9ZfBNN40UO0wct7dGupjlBFEpU47IRHK-wXmejI4U2UQGf03sXHMlw. I have provided the class for this network and some training code that uses dummy data. The code compiles and runs but ...
I think you want optimizer.step() instead of optimizer.step.
https://stackoverflow.com/questions/57081738/
Does Tensorflow or Pytorch work on RTX 20xx super series
I'm going to buy a new gpu to learn deep learning. The new Nvidia RTX 2060 Super seems to best fit my needs. But I wonder that is it compatible with CUDA and tensorflow or pytorch now?
I have bought same VGA a few days ago and using it. tested it, it works fine in Python (I used numby library) and used CUDA 10.1
https://stackoverflow.com/questions/57088166/
A strange behavior about pytorch tensor. Any one can explain it clear?
When I create a PyTorch tensor and tried to explore its type, I found this: >>> a = torch.rand(3,5) >>> a tensor([[0.3356, 0.0968, 0.2185, 0.9843, 0.7846], [0.8523, 0.3300, 0.7181, 0.2692, 0.6523], [0.0523, 0.9344, 0.3505, 0.8901, 0.6464]]) >>> type(a) <class 'torch.Tensor...
You got me digging there, but apparaently type() as built-in method does not work for type detection since 0.4.0 (see this comment and this point in migration guide). To get proper type, torch.Tensor classes have type() member, which can be simply used: import torch a = torch.rand(3, 5) print(a) print(a.type()) a = ...
https://stackoverflow.com/questions/57104935/
Why are the images generated by a GAN get darker as the network trains more?
I created a simple DCGAN with 6 layers and trained it on CelebA dataset (a portion of it containing 30K images). I noticed my network generated images are dimmed looking and as the network trains more, the bright colors fade into dim ones! here are some example: This is how CelebA images look like (real images used ...
I think that the problem lies rather in the architecture itself and I would first consider the overall quality of generated images rather than their brightness or darkness. The generations clearly get better as you train for more epochs. I agree that the images get darker but even in the early epochs, the generated ima...
https://stackoverflow.com/questions/57119171/
How do I compile a pytorch script into an exe file with small size?
I have a semantic segmentation model using PyTorch. In order to participate in a competition, I am compiling the test.py to an exe file with PyInstaller and UPX. Although the resulting executable file runs correctly, its size is nearly 800MB. How do I make it smaller? This is my test.py: from torch import nn from to...
pyinstaller is kind of cheated .exe. It does not compile the script, but bundles what's needed (including python interpreter) into one (or many) files. To really be Python agnostic you should convert your model using torchscript (read about it here). You will be able to run your module using C++ libtorch without Pyth...
https://stackoverflow.com/questions/57122734/
Undefined symbol on torchvision import
pip install torch==0.4.1 -f https://download.pytorch.org/whl/cu100/stable cat /usr/local/cuda/version.txt CUDA Version 10.1.168 python -V Python 3.5.2 python -c "import torch; print(torch.__version__)" 0.4.1 Get error on : python -c "import torchvision; print(torchvision.__version__)" ... from torchvisi...
Seems pip install torchvision==0.2.0 --no-deps --no-cache-dir helped.
https://stackoverflow.com/questions/57136161/
Extracting 3D patches from 3D images in both overlapping and nonoverlapping process and recovering the image back
I am working with 172x220x156 shaped 3D images. To feed the image into the network for output I need to extract patches of size 32x32x32 from the image and add those back to get the image again. Since my image dimension are not multiples of patch size thus I have to get overlapping patches. I want to know how to do t...
To extract (overlapping-) patches and to reconstruct the input shape we can use the torch.nn.functional.unfold and the inverse operation torch.nn.functional.fold. These methods only process 4D tensors or 2D images, however you can use these methods to process one dimension at a time. Few notes: This way requires fold/...
https://stackoverflow.com/questions/57137505/
How to delete permanently from mounted Drive folder?
I wrote a script to upload my models and training examples to Google Drive after every iteration in case of crashes or anything that stops the notebook from running, which looks something like this: drive_path = 'drive/My Drive/Colab Notebooks/models/' if path.exists(drive_path): shutil.rmtree(drive_path) shutil.c...
It is possible to perform this action inside Google Colab by using the pydrive module. I suggest that you first move your unwanted files and folders to Trash (by ordinarily removing them in your code), and then, anytime you think it's necessary (e.g. you want to free up some space for saving weights of a new DL project...
https://stackoverflow.com/questions/57151432/
How to get grads in pytorch after matrix multiplication?
I want to get the product of matrix multiplication in the latent space and optimize the weight matrix by the optimizer. I use different kinds of ways to do that. While, The value of 'pi_' in the below codes never changes. What should I do? I've tried different functions to get the product, like torch.mm(), torch.matua...
TL;DR You have too many parameters in your neural network, some of them becomes useless and therefore they are no longer being updated. Change your network architecture to reduce useless parameters. Full explanation: The weight matrix pi_ does change. You initialize pi_ as all 1, after running the first epochs, the w...
https://stackoverflow.com/questions/57155691/
PyTorch loss decreases even if requires_grad = False for all variables
When I create a neural network with PyTorch, using the torch.nn.Sequential method for defining layers, it seems that the parameters have requires_grad = False by default. However, when I train this network, the loss decreases. How is this possible if the layers are not being updated via gradients? For example, this is...
This is interesting -- there seems to be a difference between state_dict() and parameters(): class Network(torch.nn.Module): def __init__(self): super(Network, self).__init__() self.layers = torch.nn.Sequential( torch.nn.Linear(10, 5), torch.nn.Linear(5, 2) ) ...
https://stackoverflow.com/questions/57171426/
How to handle entrypoints nested in folders with amazon sagemaker pytorch estimator?
I am attempting to run a training job on amazon sagemaker using the python-sagemaker-sdk, estimator class. I have the following estimator = PyTorch(entry_point='training_scripts/train_MSCOCO.py', source_dir='./', role=#dummy_role, tra...
Either one of these will work: estimator = PyTorch(entry_point='training_scripts/train_MSCOCO.py', role=#dummy_role, ... estimator = PyTorch(entry_point='train_MSCOCO.py', source_dir='training_scripts', role=#dummy_role, ...
https://stackoverflow.com/questions/57187148/
Non-reproducible results in pytorch after saving and loading the model
I am unable to reproduce my results in PyTorch after saving and loading the model whereas the in-memory model works as expected. Just for context, I am seeding my libraries, using model.eval to turn off the dropouts but still, results are not reproducible. Any suggestions if I am missing something. Thanks in advance. ...
Since the date that Szymon Maszke posted his response above (2019), a new API has been added, torch.use_deterministic_algorithms(). This new function does everything that torch.backends.cudnn.deterministic did (namely, makes CuDNN convolution operations deterministic), plus much more (makes every known normally-nondete...
https://stackoverflow.com/questions/57195650/
What is pixel-wise softmax loss?
what is the pixel-wise softmax loss? In my understanding, it's just a cross-entropy loss, but I didn't find the formula. Can someone help me? It's better to have the pytorch code.
You can read here all about it (there's also a link to source code there). As you already observed the "softmax loss" is basically a cross entropy loss which computation combines the softmax function and the loss for numerical stability and efficiency. In your example, the loss is computed for a pixel-wise prediction ...
https://stackoverflow.com/questions/57199288/
How to implement my own ResNet with torch.nn.Sequential in Pytorch?
I want to implement a ResNet network (or rather, residual blocks) but I really want it to be in the sequential network form. What I mean by sequential network form is the following: ## mdl5, from cifar10 tutorial mdl5 = nn.Sequential(OrderedDict([ ('pool1', nn.MaxPool2d(2, 2)), ('relu1', nn.ReLU()), ('conv1...
You can't do it solely using torch.nn.Sequential as it requires operations to go, as the name suggests, sequentially, while yours are parallel. You could, in principle, construct your own block really easily like this: import torch class ResNet(torch.nn.Module): def __init__(self, module): super().__init__...
https://stackoverflow.com/questions/57229054/
How is it that torch is not installed by torchvision?
Somehow when I do the install it installs torchvision but not torch. Command I am running as dictated from the main website: conda install pytorch torchvision cudatoolkit=10.0 -c pytorch then I do conda list but look: $ conda list # packages in environment at /home/ubuntu/anaconda3/envs/pytorch_p36: # # Name ...
Your conda list command shows that it was run from the environment called automl: # packages in environment at /home/ubuntu/anaconda3/envs/automl: However, when you show the commands that you are trying to run, you are doing so from the (pytorch_p36) environment. You should run your conda install command while insi...
https://stackoverflow.com/questions/57233958/
What is the difference between .flatten() and .view(-1) in PyTorch?
Both .flatten() and .view(-1) flatten a tensor in PyTorch. What's the difference? Does .flatten() copy the data of the tensor? Is .view(-1) faster? Is there any situation that .flatten() doesn't work?
In addition to @adeelh's comment, there is another difference: torch.flatten() results in a .reshape(), and the differences between .reshape() and .view() are: [...] torch.reshape may return a copy or a view of the original tensor. You can not count on that to return a view or a copy. Another difference is that resh...
https://stackoverflow.com/questions/57234095/
saving and loading RNN hidden states in PyTorch
I am trying to use an RNN network in PyTorch for regression task. In the training phase the model is learned. I want to use the trained model in testing phase. For this purpose I have saved the learned model by: torch.save(learned_model, "model_path") Then I can load the model again by: loaded_model = torch.load("m...
Your question is a bit unclear. As far as I understand you want to know the weights of the last hidden layer in the trained model, i.e. loaded_model. In that case, you can simply use model's state_dict, which is basically a python dictionary object that maps each layer to its parameter tensor. Read more about it from h...
https://stackoverflow.com/questions/57238839/
Pytorch dataloader, too many threads, too much cpu memory allocation
I'm training a model using PyTorch. To load the data, I'm using torch.utils.data.DataLoader. The data loader is using a custom database I've implemented. A strange problem has occurred, every time the second for in the following code executes, the number of threads/processes increases and a huge amount of memory is all...
torch.utils.data.DataLoader prefetch 2*num_workers, so that you will always have data ready to send to the GPU/CPU, this could be the reason you see the memory increase https://pytorch.org/docs/stable/_modules/torch/utils/data/dataloader.html
https://stackoverflow.com/questions/57250275/
How can I use a PyTorch DataLoader for Reinforcement Learning?
I'm trying to set up a generalized Reinforcement Learning framework in PyTorch to take advantage of all the high-level utilities out there which leverage PyTorch DataSet and DataLoader, like Ignite or FastAI, but I've hit a blocker with the dynamic nature of Reinforcement Learning data: Data Items are generated from ...
Here is one PyTorch-based framework and here is something from Facebook. When it comes to your question (and noble quest, no doubt): You could easily create a torch.utils.data.Dataset dependent on anything, including the model, something like this (pardon weak abstraction, it's just to prove a point): import typing ...
https://stackoverflow.com/questions/57258323/
How to Build Simple LSTM Model for Anomally Detection
I want to create a LSTM model in PyTorch that will be used for anomally detection, but I'm having trouble understanding the details in doing so. Note, my training-data consists of sets with 16 features in 80 time-steps. Here is what I've written for the model below: class AutoEncoder(torch.nn.Module): def __init_...
If you check out the PyTorch LSTM documentation, you will see that the LSTM equations are applied to each timestep in your sequence. nn.LSTM will internally obtain the seq_len dimension and optimize from there, so you do not need to provide the number of time steps. At the moment, the line out = self.fc1(out[:, -1, :...
https://stackoverflow.com/questions/57258882/
Object Detection inference using multi-gpu & multi threading, Pytorch
I am trying to detect objects in a video using multiple GPUs. I want to distribute frames to GPUs for inference to increase total process time. I succeeded running inference in single gpu, but failed to run on multiple GPUs. I thought dividing frames per number of gpus and processing inference would decrease the time....
Pytorch provides DataParallel module to run a model on mutiple GPUs. Detailed documentation of DataParallel and toy example can be found here and here.
https://stackoverflow.com/questions/57264800/
Fine Tuning Pretrained Model MobileNet_V2 in Pytorch
I am new to pyTorch and I am trying to Create a Classifier where I have around 10 kinds of Images Folder Dataset, for this task I am using Pretrained model( MobileNet_v2 ) but the problem is I am not able to change the FC layer of it. There is not model.fc attribute. Can anyone help me to do this. Thanks
Do something like below: import torch model = torch.hub.load('pytorch/vision', 'mobilenet_v2', pretrained=True) print(model.classifier) model.classifier[1] = torch.nn.Linear(in_features=model.classifier[1].in_features, out_features=10) print(model.classifier) output: Sequential( (0): Dropout(p=0.2) (1): Linear...
https://stackoverflow.com/questions/57285224/
How the parenthesis are used right after the object's name?
I want to know about the parenthesis after the Object's name. I am learning AI and building the AI model, now in the Tutorial's code the author has written a line which is containing the Parenthesis right after the object's name which is : self.model(...) Where self.model is the Object of the Network class. How the ...
In python, everything is an object. The functions you create and call are also objects. Anything in python that can be called is a callable object. However, if you want a class object in python to be a callable object, the __call__ method must be defined inside the class. When the object is called, the __call__(self,...
https://stackoverflow.com/questions/57296738/
Pytorch Grayscale input to Vgg
I am new to pytorch and I want to use Vgg for transfer learning. I want to delete the fully connected layers and add some new fully connected layers. Also rather than RGB input I want to use grayscale input. For this I will add the weights of the input layer and get a single weight. So the three channel's weights will ...
In short: The Error is caused by Mismatch between pretrained model parameters and the vgg model Reason: You modified the parameters in pretrained model from [64,3,3,3] -> [64,1,3,3] by adding, but you didn't change the structure of VGG, which still needs a [64,3,3,3] shape of input. Resolution: Remove the first conv...
https://stackoverflow.com/questions/57296799/
Trouble Converting LSTM Pytorch Model to ONNX
I am trying to export my LSTM Anomally-Detection Pytorch model to ONNX, but I'm experiencing errors. Please take a look at my code below. Note: My data is shaped as [2685, 5, 6]. Here is where I define my model: class Model(torch.nn.Module): def __init__(self, input_dim, hidden_dim, layer_dim): super(Mode...
If you're coming here from Google the previous answers are no longer up to date. ONNX now supports an LSTM operator. Take care as exporting from PyTorch will fix the input sequence length by default unless you use the dynamic_axes parameter. Below is a minimal LSTM export example I adapted from the torch.onnx FAQ impor...
https://stackoverflow.com/questions/57299674/
Should the embedding layer be changed during training a neural network?
I'm a new one for the field of deep learning and Pytorch. Recently when I learn one of the pytorch tutorial example for NER task, I found the embedding of nn.Embedding changed during the training. So my question is should the embedding be changed during training the network? And if I want to load a pre-trained embed...
One can either learn embeddings during the task, finetune them for task at hand or leave as they are (provided they have been learned in some fashion before). In the last case, with standard embeddings like word2vec one eventually finetunes (using small learning rate), but uses vocabulary and embeddings provided. When...
https://stackoverflow.com/questions/57303955/
RuntimeError: size mismatch, m1: [192 x 68], m2: [1024 x 68] at /opt/conda/conda-bld/pytorch_/work/aten/src/THC/generic/THCTensorMathBlas.cu:268
I'm getting a size mismatch error that I can't understand. (Pdb) self.W_di Linear(in_features=68, out_features=1024, bias=True) (Pdb) indices.size() torch.Size([32, 6, 68]) (Pdb) self.W_di(indices) *** RuntimeError: size mismatch, m1: [192 x 68], m2: [1024 x 68] at /opt/conda/conda-bld/pytorch_1556653099582/work/aten/...
Check my answer in here in general you may set self.W_di = nn.Linear(mL_n * 2, 68) Or increase the in features.
https://stackoverflow.com/questions/57321704/
Assign Keras/TF/PyTorch layer to hardware type
Suppose we have the following architecture: Multiple CNN layers RNN layer (Time-distributed) Dense classification layer We want to train this architecture now. Our fancy GPU is very fast at solving the CNN layers. Although using a lower clockrate, it can perform many convolutions in parallel, thus the speed. Our fa...
Basically, in Pytorch you can control the device on which variables/parameters reside. AFAIK, it is your responsibility to make sure that for each operation all the arguments reside on the same device: i.e., you cannot conv(x, y) where x is on GPU and y is on CPU. This is done via pytorch's .to() method that moves a m...
https://stackoverflow.com/questions/57323465/
Translating Pytorch program into Keras: different results
I have translated a pytorch program into keras. A working Pytorch program: import numpy as np import cv2 import torch import torch.nn as nn from skimage import segmentation np.random.seed(1) torch.manual_seed(1) fi = "in.jpg" class MyNet(nn.Module): def __init__(self, n_inChannel, n_outChannel): supe...
Two major mistakes that I see (likely related): The last convolutional layer in the original model does not have an activation function, while your translation uses relu. The original model uses CrossEntropyLoss as loss function, while your model uses categorical_crossentropy with logits=False (a default argument). W...
https://stackoverflow.com/questions/57342987/
What's the difference between tf.nn.ctc_loss with pytorch.nn.CTCLoss
For the same input and label: the output of pytorch.nn.CTCLoss is 5.74, the output of tf.nn.ctc_loss is 129.69, but the output of math.log(tf ctc loss) is 4.86 So what's the difference between pytorch.nn.CTCLoss with tf.nn.ctc_loss? tf: 1.13.1 pytorch: 1.1.0 I had try to these: log_softmax the input, and the...
The automatic mean reduction of the CTCLoss of pytorch is not the same as computing all the individual losses, and then doing the mean (as you are doing in the Tensorflow implementation). Indeed from the doc of CTCLoss (pytorch): ``'mean'``: the output losses will be divided by the target lengths and then ...
https://stackoverflow.com/questions/57362240/
How to get the full Jacobian of a derivative in PyTorch?
Lets consider a simple tensor x and lets define another one which depends on x and have multiple dimension : y = (x, 2x, x^2). How can I have the full gradient dy/dx = (1,2,x) ? For example lets take the code : import torch from torch.autograd import grad x = 2 * torch.ones(1) x.requires_grad = True y = torch.cat(...
torch.autograd.grad in PyTorch is aggregated. To have a vector auto-differentiated with respect to the input, use torch.autograd.functional.jacobian.
https://stackoverflow.com/questions/57378143/
Why are Pytorch and Keras implementations giving vastly different results?
I am trying to train a 1-D ConvNet for time series classification as shown in this paper (refer to FCN om Fig. 1b) https://arxiv.org/pdf/1611.06455.pdf The Keras implementation is giving me vastly superior performance. Could someone explain why is that the case? The code for Pytorch is as follow: class Net(torch.n...
The reason of different results is due to different default parameters of layers and optimizer. For example in pytorch decay-rate of batch-norm is considered as 0.9, whereas in keras it is 0.99. Like that, there may be other variation in default parameters. If you use same parameters and fixed random seed for initiali...
https://stackoverflow.com/questions/57380020/
How can I compute the mean of values selected from a vector A from an indexing vector B?
I have a vector of values, for example: import torch v = torch.rand(6) tensor([0.0811, 0.9658, 0.1901, 0.0872, 0.8895, 0.9647]) and an index to select values from v: index = torch.tensor([0, 1, 0, 2, 0, 2]) I want to produce a vector mean which would compute the mean values of v grouped by indexes from index. ...
One possible solution using a combination of torch.bincount and Tensor.index_add(): v = torch.tensor([0.0811, 0.9658, 0.1901, 0.0872, 0.8895, 0.9647]) index = torch.tensor([0, 1, 0, 2, 0, 2]) bincount() gets the total for each index use in index: bincount = torch.bincount(index, minlength=6) # --> tensor([3, 1, ...
https://stackoverflow.com/questions/57386257/
How to get entire dataset from dataloader in PyTorch
How to load entire dataset from the DataLoader? I am getting only one batch of dataset. This is my code dataloader = torch.utils.data.DataLoader(dataset=dataset, batch_size=64) images, labels = next(iter(dataloader))
You can set batch_size=dataset.__len__() in case dataset is torch Dataset, else something like batch_szie=len(dataset) should work. Beware, this might require a lot of memory depending upon your dataset.
https://stackoverflow.com/questions/57386851/
How to fix the error "TypeError: forward()... - CUDA
For my bachelor thesis I need to train a network with some music similarity data using GPU and CUDA. Tried to fix the problem several times with different approaches, but none of them worked. use_cuda = torch.cuda.is_available() BSG_model = bayesian_skipgram(V, EMBEDDING_DIM) if use_cuda: BSG_model.cuda() opti...
The error message is quite self explanatory: TypeError: forward() got an unexpected keyword argument 'use_cuda' You call forward function like this oss = BSG_model.forward(main_word.cuda(), context_word.cuda(), use_cuda=True) with two positional arguments: (main_word.cuda(), context_word.cuda() and one keywo...
https://stackoverflow.com/questions/57389421/
How to rotate set of 3d points using angle axis to rotation matrix?
I am trying to rotate a set of 3d points and I am looking at this function from the kornia library. If I try to rotate a point around the z-axis by pi/2, my input(axis angle representation) should be [0, 0, pi/2]. When I use this as input into the function, it returns a 4x4 rotation matrix. However, I don't know how to...
if you look at their source, they are only updating 3 rows and 3 columns of torch.eye(4) tensor. So I think rotation_matrix[..., :3, :3] should provide you with the correct rotation matrix.
https://stackoverflow.com/questions/57396424/
How to define several layers via a loop in __init__ for Pytorch?
I am trying to define a multi-task model in Pytorch where I need a different set of layers for different tasks. I face problems in defining layers, especially if I use a for loop to store different layers in a list then I get an error from optimizer stating that model.parameters() is an empty list, which in fact it is....
you should use nn.ModuleList() to wrap the list. for example x_trains = nn.ModuleList(x_trains) see PyTorch : How to properly create a list of nn.Linear()
https://stackoverflow.com/questions/57396854/
Colab not recognizing local gpu
Im trying to train a Neural Network that I wrote, but it seems that colab is not recognizing the gtx 1050 on my laptop. I can't use their cloud GPU's for this task, because I run into memory constraints print(cuda.is_available()) is returning False
Indeed you gotta select the local runtime accelerator to use GPUs or TPUs, go to Runtime then Change runtime type like in the picture: And then change it to GPU (takes some secs):
https://stackoverflow.com/questions/57403572/
Best practices for generating a random seeds to seed Pytorch?
What I really want is to seed the dataset and dataloader. I am adapting code from: https://gist.github.com/kevinzakka/d33bf8d6c7f06a9d8c76d97a7879f5cb Anyone know how to seed this properly? What are the best practices for seeding things in Pytorch. Honestly, I have no idea if there is an algorithm specific way for G...
Have a look at https://pytorch.org/docs/stable/notes/randomness.html This is what I use def seed_everything(seed=42): random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False t...
https://stackoverflow.com/questions/57416925/
How to use non-square padding for deconvnet in PyTorch
Thank you for you attention. I hopes to use nn.ConvTranspose2d to expand dimension of a tensor in PyTorch.(from (N,C,4,4) to (N,C,8,8)) However, I find that if I want to keep the kernel size to 3 and stride to 2. I need to set the padding to [[0,0],[0,0],[0,1],[0,1]](only one side to H and W), which is not a square. ...
You can use F.pad from functional API. b= nn.ConvTranspose2d(80, 40, kernel_size=3, stride=2, padding=1)(a) c = F.pad(b, (0,1,0,1),"constant", 0)
https://stackoverflow.com/questions/57422132/
outputs are different between ONNX and pytorch
I try to convert my pytorch Resnet50 model to ONNX and do inference. The conversion procedural makes no errors, but the final result of onnx model from onnxruntime has large gaps with the result of origin model from pytorch. What is possible solution ? Version of ONNX: 1.5.0 Version of pytorch: 1.1.0 CUDA: 9.0 Syste...
Problem solve by adding model.eval() before running inference of pytorch model in test code. Solution is from the link model = models.__dict__["resnet50"]() checkpoint = torch.load(ckpt,map_location='cpu') best_prec1 = checkpoint['best_prec1'] model = import_sparse(model,checkpoint) model.eval() img_batch = torch.Floa...
https://stackoverflow.com/questions/57423150/
pytorch: inception v3 parameter empty error
I am using inception_v3 from torchvision.models as my base model and adding an FC layer at the end to get features. However, I am getting an empty parameter error. import torch import torch.nn as nn import torchvision.models as models class Baseline(nn.Module): def __init__(self, out_size): super().__init...
My understanding is that you are updating self.parameters with an empty nn.ParameterList which is not required here. self.parameters will already have all the parameters your Baseline class has, including those of inception_v3 and nn.Linear. When you are updating them at the end with an empty list, you are essential...
https://stackoverflow.com/questions/57423185/
How to get unique value along 1 dim of a 2d array in pytorch?
I have a 2d tensor now, which may have repeated elements along a dim, like tmp = torch.tensor([[1,2,3,2,4],[0,5,6,7,2],[3,4,5,3,5],[7,5,6,7,7]]) I hope to get unique elements along dim=1, the result should be like this result = [[1,2,3,4],[0,5,6,7,2],[3,4,5],[5,6,7]] Is there a way could get the result without us...
You cannot call unique on n-rank tensor when n>=2. This is because in PyTorch there are no jagged array tensors. tmp = torch.tensor([[1,2,3,2,4],[0,5,6,7,2],[3,4,5,3,5],[7,5,6,7,7]]) %timeit tmpt =torch.unbind(tmp); [torch.unique(t) for t in tmpt] This returned 39.3 µs, while your original loop took tmp = torch.te...
https://stackoverflow.com/questions/57425873/
Pytorch-Implement the same model in pytorch and keras but got different results
I am learning pytorch and want to practice it with an keras example (https://keras.io/examples/lstm_seq2seq/), this is a seq2seq 101 example which translate eng to fra on char-level features (no embedding). Keras code is below: from keras.models import Model from keras.layers import Input, LSTM, Dense import numpy a...
One way to look at the issue would be: Fixing seeds to the same value in both Pytorch and Keras, albeit it cannot really guarantee the same output. Weight initialization in Pytorch is different from Keras. Make sure they have the same weight initialization functions I've been using for a problem of mine and I can say ...
https://stackoverflow.com/questions/57438562/
One hot encoding a segmented image using pytorch
I have a segmented image as a tensor of size [1,1,256,256]. The image is a binary segmented image. I want to one hot encode it to get an image of size [1,2,256,256]. I tried torch.nn.functional.one_hot(img, 2). But it gave me an image of size [1,256,256,2]. How do I get the desired tensor?
Try to use transpose(): img_one_hot = torch.nn.functional.one_hot(img, 2).transpose(1, 4).squeeze(-1) transpose(1, 4) - swaps 1st and 4th dimension, returning the tensor of the shape of [1, 2, 256, 256, 1], squeeze(-1) removes the last dim resulting in [1 , 2, 256, 256] shaped tensor.
https://stackoverflow.com/questions/57448795/
How to run Tensorboard in parallel
https://github.com/NVIDIA/DeepRecommender According to the above page, I tried to run the NVIDIA's DeepRecommender program.After I activated the pytorch, I run the program as below but it failed. [I run this Command] $ python run.py --gpu_ids 0 \ --path_to_train_data Netflix/NF_TRAIN \ --path_to_eval_data Netflix/...
Try either installing tensorflow-gpu in your pytorch environment or pytorch in your tensorflow-gpu environemnt and use that environment to run your program.
https://stackoverflow.com/questions/57455390/
Matplotlib Pylot - Images are being displayed in low resolution (pixel to pixel)
When I display some samples photos from the dataset I use, the previews of images are displayed in low resolution (they look like very low-resolution photos). How I can I display the images without losing their resolutions? Here are my transformations which are used to move the data to the tensor and apply some transf...
What resolution are you expecting? One of the transformations you are applying is transforms.Resize((50, 50)) That is, you are reducing the input images resolution to 50 by 50 pixels. This is the resolution you are getting when you plot the images. In order to have a more graceful display of the low-res images y...
https://stackoverflow.com/questions/57472090/
Keyword arguments in torch.nn.Sequential (pytroch)
a question regarding keywords in torch.nn.Sequential, it is possible in some way to forward keywords to specific models in a sequence? model = torch.nn.Sequential(model_0, MaxPoolingChannel(1)) res = model(input_ids_2, keyword_test=mask) here, keyword_test should be forwarded only to the first model. Thank ...
No; you cannot. This is only possible if all models passed to the nn.Sequential expects the argument you are trying to pass in their forward method (at least at the time of writing this). Two workarounds could be (I'm not aware of the whole case, but anticipated from the question): If your value is static, why not ...
https://stackoverflow.com/questions/57481612/
Getting distributed package doesn't have mpi built in error
I have been trying to write a distributed application using pytorch. I have been following tutorial here. Over there, I am using the "MPI Backend" option. According to that, I need to follow the basic steps to install pytorch and then install openmpi as conda install -c conda-forge openmpi Unfortunately, whenever I tr...
From https://medium.com/@esaliya/pytorch-distributed-with-mpi-acb84b3ae5fd The MPI backend, though supported, is not available unless you compile PyTorch from its source This suggests you should first install your favorite MPI library, and possibly mpi4py built on top of it, and then build pytorch from sources at...
https://stackoverflow.com/questions/57483933/
How does one use 3D convolutions on standard 3 channel images?
I am trying to use 3d conv on cifar10 data set (just for fun). I see the docs that we usually have the input be 5d tensors (N,C,D,H,W). Am I really forced to pass 5 dimensional data necessarily? The reason I am skeptical is because 3D convolutions simply mean my conv moves across 3 dimensions/directions. So technicall...
Consider the following scenario. You have a 3 channel NxN image. This image will have size of 3xNxN in pytorch (ignoring the batch dimension for now). Say you pass this image to a 2D convolution layer with no bias, kernel size 5x5, padding of 2, and input/output channels of 3 and 10 respectively. What's actually happ...
https://stackoverflow.com/questions/57484508/
Why did I get 2 different results from two models with same parameters and inputs?
I loaded resnet18 into my two models (model1 and model2), with pretrained weights. I want to use them as feature extractors For model1: I freezed the parameters except the last linear layer model1.fc, then train it. After training, I set model1.fc into torch.nn.Identity() For model2: I directly set model2.fc into torc...
Have you taken into account changes that might occur to BatchNorm layers? Batch norm layers do not behave like normal layers - their internal parameters are modified by computing running mean and std of the data, and not by gradient descent. Try setting model1.eval() before the finetune and then check.
https://stackoverflow.com/questions/57486370/
Pyinstaller unable to find dlls for the project dependencies while creating exe
Pyinstaller failed to find certain dlls that are required for binding in dependencies into one exe. Please find the error logs below. We have tried installing these libraries: pip3 install intel-openmp mkl Tried adding --paths to the command, but as there are no dlls in the system, pyinstaller is unable to find t...
Your log of warnings is very similar to mine: PyInstaller .exe file terminates early without an error message I am therefore assuming, despite these warnings, PyInstaller still successfully builds your executable? These steps (as per above link) worked for me: Use PyInstaller to generate a one-folder bundle. From with...
https://stackoverflow.com/questions/57491610/
Pytorch: Visualize model while training
I am training a neural network by regression but it is predicting a constant value during testing. Which is why I want to visualize the weights of the neural network change during training and see the weights change dynamically in the jupyter notebook. Currently, my model looks like this: import torch from torch imp...
You can use model.state_dict() to see if your weights are updating across epochs: old_state_dict = {} for key in model.state_dict(): old_state_dict[key] = model.state_dict()[key].clone() output = model(input) new_state_dict = {} for key in model.state_dict(): new_state_dict[key] = model.state_dict()[key].clo...
https://stackoverflow.com/questions/57494217/
Why is the memory in GPU still in use after clearing the object?
Starting with zero usage: >>> import gc >>> import GPUtil >>> import torch >>> GPUtil.showUtilization() | ID | GPU | MEM | ------------------ | 0 | 0% | 0% | | 1 | 0% | 0% | | 2 | 0% | 0% | | 3 | 0% | 0% | Then I create a big enough tensor and hog the memory: >>...
It looks like PyTorch's caching allocator reserves some fixed amount of memory even if there are no tensors, and this allocation is triggered by the first CUDA memory access (torch.cuda.empty_cache() deletes unused tensor from the cache, but the cache itself still uses some memory). Even with a tiny 1-element tensor, ...
https://stackoverflow.com/questions/57496285/
How to customize pytorch data
I am trying to make a customized Dataloader using pytorch. I've seen some codes like (omitted the class sorry.) def __init__(self, data_root, transform=None, training=True, return_id=False): super().__init__() self.mode = 'train' if training else 'test' self.data_root = Path(data_root) csv_fname = 't...
First, you want to customize (overload) data.Dataset and not data.DataLoader which is perfectly fine for your use case. What you can do, instead of loading all data to RAM, is to read and store "meta data" on __init__ and read one relevant csv file whnever you need to __getitem__ a specific entry. A pseudo-code of you...
https://stackoverflow.com/questions/57504262/
How can I deploy my Pytorch model into IOS?
I have a deep learning neural network I built on Pytorch I am seeking to deploy onto IOS.
Native support doesn't exist still I think, but what some do is to export the ONNX model and then open this in Caffe2 which has the support for IOS device (also Androids) So use ONNX export tutorial and this mobile integration helper. There is also a path converting ONNX to CoreML but depending on your project it may...
https://stackoverflow.com/questions/57511185/
Pytorch custom dataset: ValueError: some of the strides of a given numpy array are negative
I wrote a custom pytorch dataset, but ran into an error thhat seems quite unintelligible. My custom dataset, class data_from_xlsx(Dataset): def __init__(self, xlsx_fp, path_col, class_cols_list): self.xlsx_file = pd.read_excel(xlsx_fp) self.path_col = path_col self.class_cols_list = class...
Thanks to the advice from @jodag and @UsmanAli, I sovled this by return torch.from_numpy(feature.copy()) and torch.tensor(label.astype(np.bool)) So the whole thing should be, class data_from_xlsx(Dataset): def __init__(self, xlsx_fp, path_col, class_cols_list): self.xlsx_file = pd.read_excel(xlsx_fp) ...
https://stackoverflow.com/questions/57517740/
constants in Pytorch Linear Module Class Definition
What is __constants__ in pytorch class Linear(Module): defined in https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html? What is its functionality and why is it used? I have been searching around, but did not find any documentation. Please note that this does not mean the __constants__ in torch scrip...
The __constants__ you're talking about is, in fact, the one related to TorchScript. You can confirm it by using git blame (when it was added and by who) on GitHub. For example, for torch/nn/modules/linear.py, check its git blame. TorchScript also provides a way to use constants that are defined in Python. These can be...
https://stackoverflow.com/questions/57522806/
What is the meaning of keep_vars in state_dict?
state_dict(destination=None, prefix='', keep_vars=False) what does changing keep_vars to True do?
In PyTorch >=0.4, it has no use. keep_vars was added in the commit: Add keep_vars parameter to state_dict stating that When keep_vars is true, it returns a Variable for each parameter (rather than a Tensor). In state_dict function, _save_to_state_dict is called internally, which contains the following...
https://stackoverflow.com/questions/57534801/
What is the difference between register_parameter and register_buffer in PyTorch?
Module's parameters get changed during training, that is, they are what is learnt during training of a neural network, but what is a buffer? and is it learnt during neural network training?
Pytorch doc for register_buffer() method reads This is typically used to register a buffer that should not to be considered a model parameter. For example, BatchNorm’s running_mean is not a parameter, but is part of the persistent state. As you already observed, model parameters are learned and updated using SGD ...
https://stackoverflow.com/questions/57540745/
Filter data in pytorch tensor
I have a tensor X like [0.1, 0.5, -1.0, 0, 1.2, 0], and I want to implement a function called filter_positive(), it can filter the positive data into a new tensor and return the index of the original tensor. For example: new_tensor, index = filter_positive(X) new_tensor = [0.1, 0.5, 1.2] index = [0, 1, 4] How can I...
Take a look at torch.nonzero which is roughly equivalent to np.where. It translates a binary mask to indices: >>> X = torch.tensor([0.1, 0.5, -1.0, 0, 1.2, 0]) >>> mask = X >= 0 >>> mask tensor([1, 1, 0, 1, 1, 1], dtype=torch.uint8) >>> indices = torch.nonzero(mask) >>> ...
https://stackoverflow.com/questions/57570043/
Difference in Model Performance when using Validation set/ Testing set
I have implemented a PyTorch NN code for classification and regression. Classification: a) Use stratifiedKfolds for cross-validation (K=10- means 10 fold-cross validation) I divided the data: as follows: Suppose I have 100 data: 10 for testing, 18 for validation, 72 for training. b) Loss function = CrossEntropy c) ...
You have a large gap between training and validation performance, and between validation and test performance. There are two issues to explore: Differences in the distribution. We assume that train / val / test sets are all drawn from the same distribution, and so have similar characteristics. A well trained model sh...
https://stackoverflow.com/questions/57581436/
ModuleNotFoundError: No module named 'past' when installing tensorboard with pytorch 1.2
I'm trying out tensorboard with pytorch by following this: https://pytorch.org/docs/stable/tensorboard.html I've installed tensorboard with pip install tb-nightly The command tensorboard --logdir=runs starts ok. But the line self.writer = SummaryWriter() Gives the following error: ModuleNotFoundError: No module na...
Following this issue: https://github.com/pytorch/pytorch/issues/22389, Adding future to the list of requirements solved the problem # requirements.txt: tb-nightly future pip install -r requirements.txt
https://stackoverflow.com/questions/57599555/
Difference between PyTorch, PyTorchModel in sagemaker.pytorch
I am trying to create a model using pytorch in sagemaker. I tried deploying using - PyTorch module in sagemaker.pytorch [from sagemaker.pytorch import PyTorch]. But, I want to understand what is PyTorchModel in sagemaker.pytorch [from sagemaker.pytorch import PyTorchModel]. They both have deploy() . And I followed the...
PyTorch class is inherited from the Framework class whereas PyTorchModel is inherited from the FrameworkModel class. The difference between these two is that: Framework is used to perform the end to end training and deployment of a model FrameworkModel is used to create an Estimator from a pretrained model and then u...
https://stackoverflow.com/questions/57604157/
pytorch TypeError: '<' not supported between instances of 'Example' and 'Example' when referring to iterator
I am trying to use my own dataset to classify text according to https://github.com/bentrevett/pytorch-sentiment-analysis/blob/master/5%20-%20Multi-class%20Sentiment%20Analysis.ipynb. My dataset is a csv of sentences and a class associated with it. there are 6 different classes: sent class 'the fox...
I faced a similar issue and got it resolved by using sort_key and sort_within_batch while creating iterators. train_iterator, valid_iterator = BucketIterator.splits( (train, valid), batch_size = BATCH_SIZE, sort_key = lambda x: len(x.sent), sort_within_batch=True, device = device)
https://stackoverflow.com/questions/57605217/
Taking a norm of matrix rows/cols in pytorch
The norm of a vector can be taken by torch.norm(vec) However, how to take a norm of a set of vectors grouped as a matrix (either as rows or columns)? For example, if a matrix size is (5,8), then the rows norms should return a vector of norms of size (5).
torch.norm without extra arguments performs what is called a Frobenius norm which is effectively reshaping the matrix into one long vector and returning the 2-norm of that. To take the norm along a particular dimension provide the optional dim argument. For example torch.norm(mat, dim=1) will compute the 2-norm along ...
https://stackoverflow.com/questions/57627833/
PyTorch not downloading
I go to the PyTorch website and select the following options PyTorch Build: Stable (1.2) Your OS: Windows Package: pip Language: Python 3.7 CUDA: None (All of these are correct) Than it displays a command to run pip3 install torch==1.2.0+cpu torchvision==0.4.0+cpu -f https://download.pytorch.org/whl/torch_stabl...
I've been in same situation. My prob was, the python version... I mean, in the 'bit' way. It was 32 bit that the python I'd installed. You should check which bit of python you installed. you can check in the app in setting, search python, then you will see the which bit you've installed. After I installed the 64 b...
https://stackoverflow.com/questions/57642019/
How to set the output size of an RNN?
I want to have an RNN with input size 7, hidden size 10 and output size 2. So for an input of, say, shape 99x1x7 I expect an output of shape 99x1x2. For an RNN alone, I get: model = nn.RNN(input_size=7, hidden_size=10, num_layers=1) output,hn=model(torch.rand(99,1,7)) print(output.shape) #torch.Size([99, 1, 10]) pri...
From the pytorch doc https://pytorch.org/docs/stable/nn.html?highlight=rnn#torch.nn.RNN the output is of shape seq_len, batch, num_directions * hidden_size So depending on what you want you might add a fc layer to get an output of size 2. Basically, a Sequential will apply each model on top of the output of the next_...
https://stackoverflow.com/questions/57642161/
What is the difference between these two neural network structures?
first using nn.Parameter class ModelOne(nn.Module): def __init__(self): super().__init__() self.weights = nn.Parameter(torch.randn(300, 10)) self.bias = nn.Parameter(torch.zeros(10)) def forward(self, x): return x @ self.weights + self.bias when I do mo = ModelOne() [len(param) for param in mo.p...
The difference lies in how nn.Linear initializes weights and bias: class Linear(Module): def __init__(self, in_features, out_features, bias=True): super(Linear, self).__init__() self.in_features = in_features self.out_features = out_features self.weight = Parameter(torch.Tensor(out...
https://stackoverflow.com/questions/57660053/
DataLoader crashes when shuffling
I'm using DataLoader to read from a custom Dataset object based on numpy memmap. As long as I read the data without shuffling everything works fine but, as I set shuffle=True, the runtime crash. I tried implementing the shuffling mechanism in the Dataset class by using a permutation vector and setting shuffle=False in...
RuntimeError: DataLoader worker (pid(s) 3978) exited unexpectedly This error is because, In data.DataLoader(dataset, batch_size=32, shuffle=False, num_workers=1) make num_workers=0 , its saying there are no subprocesses in your cpu
https://stackoverflow.com/questions/57664289/
What is the difference between feature and classifier?
I saw code like this self.feature = model_func() if loss_type == 'softmax': self.classifier = nn.Linear(self.feature.final_feat_dim, num_class) self.classifier.bias.data.fill_(0) elif loss_type == 'dist': #Baseline ++ self.classifier = backbone.distLinear(self.feature.final_feat_dim, num_class) where mod...
I find the question a little messy, but I'll give my best from what I understand you're asking. What here is classifier? The classifier would be the model itself. The model is the one who will, after being trained, be able to classify new data. Is feature same as activation I don't know what kind of featur...
https://stackoverflow.com/questions/57667304/
Not able to load the saved graph using torch.utils.tensorboard.SummaryWriter.add_graph method
I am saving the scalar summary along with model graph using add_scalar and add_graph methods from torch.utils.tensorboard.SummaryWriter. While running tensorboard on the summary file, it doesnt show the model graph. Just 2 small rectangle at the bottom right, However, it is able to show the scalar variable and image...
I had the same problem. Check out this thread: https://github.com/pytorch/pytorch/issues/24157 TLDR: Update PyTorch to PyTorch-nightly and the problem should be solved. https://pytorch.org/get-started/locally/
https://stackoverflow.com/questions/57706256/
How can I find a solution for the "FileNotFoundError"
I'm currently working on an image classifier project. During the testing of the predict function, I receive the error: FileNotFoundError: [Errno 2] No such file or directory: 'flowers/test/1/image_06760' the path of the file is correct. You can find the whole notebook here: https://github.com/MartinTschendel/image-cl...
These are the images you have You should have it as image_name = data_dir + '/test' + '/1/' + 'image_06760.jpg' for it to work as you were not specifying the image extension.
https://stackoverflow.com/questions/57710920/
Getting truth value of array with more than one element in ambigous for albuementation transform
I am using albumentations for applying transform to a Pytorch model but getting this error and I m not getting any clue of what this error is about. Only thing I know is this is occuring due to transform which is being applied but not sure what is wrong with that. ValueError: Traceback (most recent call last): File ...
From official albumentation documentation, you can apply transformation to image from PIL import Image import cv2 import numpy as np from torch.utils.data import Dataset from torchvision import transforms from albumentations import Compose, RandomCrop, Normalize, HorizontalFlip, Resize from albumentations.pytorch imp...
https://stackoverflow.com/questions/57718447/
TypeError although same shape: if not (target.size() == input.size()): 'int' object is not callable
This is the error message I get. In the first line, I output the shapes of predicted and target. From my understanding, the error arises from those shapes not being the same but here they clearly are. torch.Size([6890, 3]) torch.Size([6890, 3]) Traceback (most recent call last): File "train.py", line 251, in &lt;m...
A little bit late but maybe it will help someone else. Just solved the same problem for myself. As Alpha said in his answer we cannot call .size() for a numpy array. But we can call .size() for a tensor. Therefore, we need to make our target a tensor. You can do it like this: target = torch.from_numpy(target) I'm u...
https://stackoverflow.com/questions/57724134/
Binary cross entropy Vs categorical cross entropy with 2 classes
When considering the problem of classifying an input to one of 2 classes, 99% of the examples I saw used a NN with a single output and sigmoid as their activation followed by a binary cross-entropy loss. Another option that I thought of is having the last layer produce 2 outputs and use a categorical cross-entropy wit...
If you are using softmax on top of the two output network you get an output that is mathematically equivalent to using a single output with sigmoid on top. Do the math and you'll see. In practice, from my experience, if you look at the raw "logits" of the two outputs net (before softmax) you'll see that one is exactly...
https://stackoverflow.com/questions/57726064/
torch.cat but create a new dimension
I would like to concatenate tensors, not along a dimension, but by creating a new dimension. For example: x = torch.randn(2, 3) x.shape # (2, 3) torch.cat([x,x,x,x], 0).shape # (8, 3) # This concats along dim 0, not what I want torch.cat([x,x,x,x], -1).shape # (2, 10) # This concats along dim 1, not what I want to...
Just use torch.stack: torch.stack([x,x,x,x]).shape # (4, 2, 3)
https://stackoverflow.com/questions/57727618/
How to ensure that a batch contains samples from all workers with PyTorch's DataLoader?
I want to know how to use torch.utils.data.DataLoader in PyTorch, especially in a multi-worker case. I found that one batch output from DataLoader always comes from a single worker. I expected that there is a queue in the DataLoader which stores data from all of the workers and DataLoader shuffles them in the queue t...
I've implemented something simple to solve a similar problem, where I have large video files as training data and each worker is responsible for loading and preprocessing a single file and then yielding samples from it. Problem is that as OP describes, with Pytorch's default data loading mechanism, each batch contains ...
https://stackoverflow.com/questions/57729279/
Can't import torch in jupyter notebook
System: macOS 10.13.6 Python: 3.7 Anaconda3 I have trouble when import torch in jupyter notebook. ModuleNotFoundError: No module named 'torch' Here is how I install pytorch: conda install pytorch torchvision -c pytorch I've checked PyTorch is installed in my anaconda environment: When I command python3 in my termina...
You have to install jupyter in addition to pytorch inside your activated conda env. Here is installation steps: 1. Create conda env for example: pytorch_p37 with python 3.7: user@pc:~$ conda create -n pytorch_p37 python=3.7 2. Activate it user@pc:~$ conda activate pytorch_p37 Or with (for older conda versions):...
https://stackoverflow.com/questions/57735701/
What does the `model.parameters()` include?
In Pytorch, What will be registered into the model.parameters(). As far as now, what I know are as belows: 1. Conv layer: weight bias 2. BN layers: weight(gamma) bias(beta) 3. nn.Parameter() such as: self.alpha = nn.Parameter(torch.rand(10)) defined in the model. My question is: And are there some par...
Like you wrote there, model.parameters() stores the weight and bias (if set to true) values of the model. It is given as an argument to an optimizer to update the weight and bias values of the model with one line of code optimizer.step(), which you then use when next you go over your dataset.
https://stackoverflow.com/questions/57738199/
Data Normalization using Pytorch
I'm starting to work on the classification of images dataset, as many tutorials I followed; it starts by normalizing the data (train and test data) My question is: if I want to normalize the data by shifting and scaling it with a factor of 0.5 What does this mean 'the factor of something x'? I know that it will be u...
Shifting and scaling refers to the color space. What you do is you subtract the mean (shifting to the mean of the pixel values of the whole dataset to 0) and divide by the standard deviation (scaling the pixel values to [0, 1]. It has nothing to do with modifying the size of the image or the like. In numy you would ...
https://stackoverflow.com/questions/57744270/
Multiple outputs in Pytorch, Keras style
How could you implement these 2 Keras models (inspired by the Datacamp course 'Advanced Deep Learning with Keras in Python') in Pytorch: Classification with 1 input, 2 outputs: from keras.layers import Input, Concatenate, Dense from keras.models import Model input_tensor = Input(shape=(1,)) output_tensor = Dense(2)(...
This ressource was particularly helpful. Basically, the idea is that, contrary to Keras, you have to explicitly say where you're going to compute each output in your forward function and how the global loss is gonna be computed from them. For example, regarding the 1st example: def __init__(self, ...): ... # def...
https://stackoverflow.com/questions/57753687/
TypeError: hook() takes 2 positional arguments but 3 were given
I'm new to pytorch and I'm trying to use hook() and register_forward_pre_hook in my project What I've tried is def get_features_hook(module,input): print(input) handle_feat = alexnet.features[0].register_forward_pre_hook(get_features_hook) a = alexnet(input_data) And I got belows error at a = alexnet(input_...
If get_features_hook is defined inside your torch.nn.Module, it should be annotated as @staticmethod, otherwise self is implicitly passed to it
https://stackoverflow.com/questions/57765751/
Specify network to not backpropagate the gradients in a given function
In my neural network, in order to compute the loss, I need to do some intermediate computations during training to first obtain some transformations rv. rv = factor.ransac(source, target, prob, device) predicted = factor.predict(source, rv, outputs, device) loss = criterion(predicted, target) I want to backpropagate...
You can use detach(). rv = factor.ransac(source, target, prob, device).detach() That way, gradients on rv will be discarded.
https://stackoverflow.com/questions/57774456/
Is indexing with a bool array or index array faster in numpy/pytorch?
I can index my numpy array / pytorch tensor with a boolean array/tensor of the same shape or an array/tensor containing integer indexes of the elements I'm after. Which is faster?
The following tests indicate that it's generally 3x to 20x faster with an index array in both numpy and pytorch: In [1]: a = torch.arange(int(1e5)) idxs = torch.randint(len(a), (int(1e4),)) ind = torch.zeros_like(a, dtype=torch.uint8) ind[idxs] = 1 ac, idxsc, indc = a.cuda(), idxs.cuda(), ind.cuda() In [2]: %timeit a...
https://stackoverflow.com/questions/57783029/
mask first k elements in a 3D tensor in PyTorch (different k for each row)
I have a tensor M of dimensions [NxQxD] and a 1d tensor of indices idx (of size N). I want to efficiently create a tensor mask of dimensions [NxQxD] such that mask[i,j,k] = 1 iff j &lt;= idx[i], i.e. I want to keep only the idx[i] first dimensions out of Q in the second dimension (dim=1) of M, for every row i. Thanks...
It turns out this can be done via a broadcasting trick: mask_2d = torch.arange(Q)[None, :] &lt; idx[:, None] #(N,Q) mask_3d = mask[..., None] #(N,Q,1) masked = mask.float() * data
https://stackoverflow.com/questions/57788412/
torch.utils.data.random_split() is not splitting the data
I’m not getting split when I use torch.utils.data.random_split. I get correct numbers for train_size and val_size, but when I do random_split, both train_data and val_data get full_data. There is no split happening. Please help me with this issue. class DeviceLoader(Dataset): def __init__(self, root_dir, train=True...
From the image below you could see, it actually makes a subset of data but the original dataset is still there. This might be confusing. I did the following on mnist dataset train, validate, test = data.random_split(training_set, [50000, 10000, 10000]) print(len(train)) print(len(validate)) print(len(test)) output: 50...
https://stackoverflow.com/questions/57789645/
Pytorch : how to run code on several machines in cluster
I am using a cluster to train a recurrent neural network developed using PyTorch. PyTorch automatically threads, which allows to use all the cores of a machine in parallel without having to explicitly program for it. This is great ! Now when I try to use several nodes at the same time using a script like this one : #...
tl;dr There is no easy solution. There are two ways how you can parallelize training of a deep learning model. The most commonly used is data parallelism (as opposed to model parallelism). In that case, you have a copy of the model on each device, run the model and back-propagation on each device independently and get...
https://stackoverflow.com/questions/57803005/
"AssertionError: Torch not compiled with CUDA enabled" in spite upgrading to CUDA version
I figured out this is a popular question, but still I couldn't find a solution for that. I'm trying to run a simple repo Here which uses PyTorch. Although I just upgraded my Pytorch to the latest CUDA version from pytorch.org (1.2.0), it still throws the same error. I'm on Windows 10 and use conda with python 3.7. ...
you dont have to install it via anaconda, you could install cuda from their website. after install ends open a new terminal and check your cuda version with: &gt;&gt;&gt; nvcc --version nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2021 NVIDIA Corporation Built on Thu_Nov_18_09:52:33_Pacific_Standard_Time_20...
https://stackoverflow.com/questions/57814535/
pytorch collate_fn reject sample and yield another
I have built a Dataset, where I'm doing various checks on the images I'm loading. I'm then passing this DataSet to a DataLoader. In my DataSet class I'm returning the sample as None if a picture fails my checks and i have a custom collate_fn function which removes all Nones from the retrieved batch and returns the rem...
There are 2 hacks that can be used to sort out the problem, choose one way: By using the original batch sample Fast option: def my_collate(batch): len_batch = len(batch) # original batch length batch = list(filter (lambda x:x is not None, batch)) # filter out all the Nones if len_batch &gt; len(batch): # ...
https://stackoverflow.com/questions/57815001/
how to install pytorch in python2.7?
i am using python2.7 in virtual environment. i tried to install pytorch in python2.7 but i got error belows: UnsatisfiableError: The following specifications were found to be incompatible with the existing python installation in your environment: - pytorch-cpu -&gt; python[version='3.5.*|3.6.*'] - pytorch...
Here's the link to the PyTorch official download page From here, you can choose the python version (2.7) and CUDA (None) and other relevant details based on your environment and OS. Other helpful links: windows windows mac ubuntu all
https://stackoverflow.com/questions/57835948/
TypeError: 'int' object is not callable in loss.backward()
While trying to set up a pytorch model, I am getting the error that the loss object is not callable when trying to do Pytorch autograd. (Relevant code shown below) optimizer = torch.optim.Adam(model.parameters(), lr=lr, betas(0.0,0.9)) def train(epoch, shuffle, wisdom_model, optim, loss): print('train') ac...
The problem is in this line: loss = nn.CrossEntropyLoss()(result, batch[1].long()) Check out the nn.CrossEntropyLoss. Should not look like this: nn.CrossEntropyLoss()() Should look like this: nn.CrossEntropyLoss()
https://stackoverflow.com/questions/57838192/
Cleaner way to use "with torch.no_grad()" conditioned on an expression
My code looks like: if no_grad_condition: with torch.no_grad(): out=network(input) else: out=network(input) Is there a cleaner way to do it, without duplicating the line out=network(input)? I am looking for something in the spirit of: with torch.no_grad(no_grad_condition): out=network(input)
OP here: By writing down the question, I understood where to look for the answer. According to pytorch docs, we can use set_grad_enabled: with torch.set_grad_enabled(not no_grad_condition): out=network(input)
https://stackoverflow.com/questions/57852236/
I have a trouble after trying to parallelize data using nn.Dataparallel
I didn't have any probelm without data parallelization, but after I put JUST A ONE LINE "model = nn.DataParallel(model)" the error message "TypeError: 'list' object is not callable" comes. If I push out that damn line the source works clean. plz help me I can't do anything but just mad. I search that google and there ...
I met the same problem, because I've set moules = [list]. I changed my code like this: def __init__(self, embedding_size, activation_function='relu'): super().__init__() self.act_fn = getattr(F, activation_function) self.embedding_size = embedding_size self.conv1 = nn.Conv2d(3, 32, 4, stride=2) self...
https://stackoverflow.com/questions/57857939/
How to clear GPU memory after PyTorch model training without restarting kernel
I am training PyTorch deep learning models on a Jupyter-Lab notebook, using CUDA on a Tesla K80 GPU to train. While doing training iterations, the 12 GB of GPU memory are used. I finish training by saving the model checkpoint, but want to continue using the notebook for further analysis (analyze intermediate results, e...
The answers so far are correct for the Cuda side of things, but there's also an issue on the ipython side of things. When you have an error in a notebook environment, the ipython shell stores the traceback of the exception so you can access the error state with %debug. The issue is that this requires holding all varia...
https://stackoverflow.com/questions/57858433/
PyTorch equivalent of `numpy.unpackbits`?
I am training a neural net on GPU. It uses a lot of binary input features. Since moving data to/from GPU is expensive, I am looking for ways to make the initial representation more compact. Now, I encode my features as int8, move them over to GPU and then expand as float32: # create int8 features = torch.zeros(*dims,...
There is no similar functions at the time of writing this answer. However, a workaround is using torch.from_numpy as in: In[2]: import numpy as np In[3]: a = np.array([[2], [7], [23]], dtype=np.uint8) In[4]: b = np.unpackbits(a, axis=1) In[5]: b Out[5]: array([[0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1...
https://stackoverflow.com/questions/57871287/
Unable to Install Torch or torch vision in pycharm I am running python 3.6
Installing torch from PyCharm interpreter but error occurs. Python 3.6 Collecting torch==0.4.1.post2 Could not find a version that satisfies the requirement torch==0.4.1.post2 (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2) No matching distribution found for torch==0.4.1.post2
Try installing lower version of torch, go to: File->Setting->Project[project_name]-> Project Interpreter -> + -> search for torch, in right lower corner is check box 'Specify version' check it and try sevral starting from top. From what i see current is 1.2.0
https://stackoverflow.com/questions/57896633/
ImportError: cannot import name 'parameter_parser' from 'parser' (unknown location)
I am trying to Import Parameter_parser from Parser. but it is showing the error below: ImportError: cannot import name 'parameter_parser' from 'parser' In the line below that I also get: ModuleNotFoundError: No module named 'load_data' This is my code: import matplotlib matplotlib.use('agg') import...
When I try the same thing in my python console I get this: &gt;&gt;&gt; from parser import parameter_parser File "&lt;stdin&gt;", line 1 from parser import parameter_parser ^ IndentationError: unexpected indent &gt;&gt;&gt; from parser import parameter_parser Traceback (most recent call last): File "&lt;s...
https://stackoverflow.com/questions/57905600/
Interpret GAN loss
I am currently training the standard DCGAN network on my dataset. After 40 epochs, the loss of both generator and discriminator is 45-50. Can someone please explain the reason and possible solution for this?
This interpretation may be added to unsolved problems. You cannot interpret the loss of generator and discriminator. Since when one improves it will be harder for the other. When generator improves it will be harder for the critic. When critic improves it will be harder for the generator. The values totally depend on...
https://stackoverflow.com/questions/57919973/
DataLoader messing up transformed data
I am testing the MNIST dataset in Pytorch, and after I apply a transformation to the X data, it seems the DataLoader puts all values out of the original order, potentially messing up the training step. My transformation is to divide all values by 255. One should notice that the transformation itself does not change po...
So... I posted this same question at Pytorch's GitHub page, and they answered the following: It's unrelated to data loader. You are messing with an attribute of the particular dataset object, however, the actual __getitem__ of that object does much more: https://github.com/pytorch/vision/blob/6de158c473b83cf4...
https://stackoverflow.com/questions/57924724/