instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
How do I add an image title to tensorboardX?
I am currently using tensorboardX to visualize input images while training a ResNet image classifier. Is there a way to add the image title along with the added image? I would like to have the image name (as stored in the dataset) displayed below the image in the tensorboard display. So far I have tried passing a comm...
there is no way of doing it directly with tensorboard, instead you have to create images with titles using matplotlib and then supply them to tensorboard. Here is a sample code from the tensorboard documentation: def plot_to_image(figure): """Converts the matplotlib plot specified by 'figure' to a PNG ...
https://stackoverflow.com/questions/60907358/
Why PyTorch nn.Module.cuda() not moving Module tensor but only parameters and buffers to GPU?
nn.Module.cuda() moves all model parameters and buffers to the GPU. But why not the model member tensor? class ToyModule(torch.nn.Module): def __init__(self) -> None: super(ToyModule, self).__init__() self.layer = torch.nn.Linear(2, 2) self.expected_moved_cuda_tensor = torch.tensor([0, ...
If you define a tensor inside the module it needs to be registered as either a parameter or a buffer so that the module is aware of it. Parameters are tensors that are to be trained and will be returned by model.parameters(). They are easy to register, all you need to do is wrap the tensor in the nn.Parameter type a...
https://stackoverflow.com/questions/60908827/
Error trying to convert simple convolutional model to CoreML
I'm trying to convert a simple GAN generator (from ClusterGAN): self.name = 'generator' self.latent_dim = latent_dim self.n_c = n_c self.x_shape = x_shape self.ishape = (128, 7, 7) self.iels = int(np.prod(self.ishape)) self.verbose = verbose self.model = nn.Sequential( # Fully connected layers torch.nn.Linear...
Core ML does not have 1-dimensional batch norm. The tensor must have at least rank 3. If you want to convert this model, you should fold the batch norm weights into those of the preceding layer and remove the batch norm layer. (I don't think PyTorch has a way to automatically do this for you.)
https://stackoverflow.com/questions/60917399/
Pytorch cuda get_device_name and current_device() hang and are killed?
I've just installed a new GPU (RTX 2070) in my machine alongside the old GPU. I wanted to see if PyTorch picked up it, so following the instructions here: How to check if pytorch is using the GPU?, I ran the following commands (Python3.6.9, Linux Mint Tricia 19.3) >>> import torch >>> torch.cuda.is_a...
If I understand correctly, you would like to list the available cuda devices. This can be done via nvidia-smi (not a PyTorch function), and both your old GPU and the RTX 2070 should show up, as devices 0 and 1. In PyTorch, if you want to pass data to one specific device, you can do device = torch.device("cuda:0") for G...
https://stackoverflow.com/questions/60917618/
KeyError: 'answers' error when using BioASQ dataset using Huggingface Transformers
I am using run_squad.py https://github.com/huggingface/transformers/blob/master/examples/run_squad.py from Huggingface Transformers for fine-tuning on BioASQ Question Answering dataset. I have converted the tensorflow weights provided by the authors of BioBERT https://github.com/dmis-lab/bioasq-biobert to Pytorch as d...
The BioASQ evaluation files are test files that don't contain answers, only used for predictions. for evaluation during training you can use a portion of the training files
https://stackoverflow.com/questions/60942088/
BERT training with character embeddings
Does it make sense to change the tokenization paradigm in the BERT model, to something else? Maybe just a simple word tokenization or character level tokenization?
That is one motivation behind the paper "CharacterBERT: Reconciling ELMo and BERT for Word-Level Open-Vocabulary Representations From Characters" where BERT's wordpiece system is discarded and replaced with a CharacterCNN (just like in ELMo). This way, a word-level tokenization can be used without any OOV iss...
https://stackoverflow.com/questions/60942550/
How to install torch 0.4.1 on Windows 10?
I have windows 10 on a Lenovo Thinkpad P72 with a Nvidia Quadro P5200, and I absolutely need to install (py)torch v0.4.1 to use a 3D Mask R-CNN. So I tried the following link: https://github.com/pytorch/pytorch/issues/19457 However, when I finish with "python setup.py install", I obtain: C:\Users\...\pytorch-0.4.1\bu...
for pip pip install torch===0.4.1 torchvision===0.5.0 -f https://download.pytorch.org/whl/torch_stable.html
https://stackoverflow.com/questions/60944201/
Use a generator to perform operation on a matrix in Python
I have a similarity matrix (torch tensor) which is a cosine similarity matrix between two matrix (source and target). From the matrix I need to obtain the sum of the distance between the top nearest neighbor of each source and target. Then fillup two defaultdicts using the computed values above as shown in the code ...
I don't think it's necessary to save memory here. Let's say the shape of matx is [n x m], then the nearestSrc/Tgt and sumDistSource/Target tensors will contain no more than 2 * (n + m), memory consumption of which is almost ignorable compared to matx. Besides, I don't think PyTorch provides an API to generate top-k ele...
https://stackoverflow.com/questions/60949990/
Tensorflow and PyTorch hang on initializing with CUDA
When I try to run a very minimal Tensorflow example: import tensorflow as tf c = tf.constant([1,2,3]) The system hangs forever (at least for ten minutes) with no sign of what it is doing. It uses 100% of one virtual CPU core when in this state. When run in a Juypter notebook the kernel outputs this to the console: ...
My issue was caused by a ulimit I had set on the amount of virtual memory the Python process was aloud to consume (with ulimit -Sv 12000000 in zsh). I don't know why that would cause it to hang, but if anyone else encounters a similar issue, make sure you aren't limiting virtual memory.
https://stackoverflow.com/questions/60954107/
Pytorch: multi-target error with CrossEntropyLoss
So I was training a Conv. Neural Network. Following are the essential details: original label dim = torch.Size([64, 1]) output from the net dim = torch.Size([64, 2]) loss type = nn.CrossEntropyLoss() error = RuntimeError: multi-target not supported at /pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:15 WHERE ...
The problem is that your target tensor is 2-dimensional ([64,1] instead of [64]), which makes PyTorch think that you have more than 1 ground truth label per data. This is easily fixed via loss_func(output, y.flatten().to(device)). Hope this helps!
https://stackoverflow.com/questions/60961466/
Importance weighted autoencoder doing worse than VAE
I've been implementing VAE and IWAE models on the caltech silhouettes dataset and am having an issue where the VAE outperforms IWAE by a modest margin (test LL ~120 for VAE, ~133 for IWAE!). I don't believe this should be the case, according to both theory and experiments produced here. I'm hoping someone can find som...
The K-sample importance weighted ELBO is $$ \textrm{IW-ELBO}(x,K) = \log \sum_{k=1}^K \frac{p(x \vert z_k) p(z_k)}{q(z_k;x)}$$ For the IWAE there are K samples originating from each datapoint x, so you want to have the same latent statistics mu_z, Sigma_z obtained through the amortized inference network, but sample mul...
https://stackoverflow.com/questions/60974047/
optimized_execution() takes 1 positional argument but 2 were given
I'm following the pytorch sagemaker docs here and I'm stuck on this line torch.jit.optimized_execution(True, {'target_device': 'eia:device ordinal'}) When I run it, I get the error optimized_execution() takes 1 positional argument but 2 were given. I'm using pytorch 1.3.1, but I tried with 1.4.0 and was running into ...
(I'll refer to the Elastic Inference enabled PyTorch framework as "PyTorch-EI" for convenience) Are you using SageMaker through notebook or hosting? SageMaker notebook support is not currently released, so there's no official notebook kernel / Conda environment that you can activate that will have the Elastic Inferenc...
https://stackoverflow.com/questions/60981262/
Reading h5py files into tensors
So I have a training set and a test set both in h5py format. I also have a data_load function that loads the files and returns NumPy arrays. The main problem is I don't need NumPy as I am working with Tensors. I am expecting to have an x&y tensor of size N(batch size) and D_in(input size for each image) and D_out(O...
Because you did not convert train_set_x_orig to a torch tensor before returning. Either use torch.from_numpy() on train_set_x_orig before returning as you do with train_set_y_orig or cast it to a tensor before assigning to x. However, y should be of type torch.tensor. Below is a demonstration that explains the issu...
https://stackoverflow.com/questions/60993802/
How to optimize pip imports for Dockerfile layers caching
I have a Dockerfile for ML/DL stack that needs a lot of requirements that could be logically split into python standard libraries and python ml libraries at least: Python libraries (requirements.txt): Cython python-dateutil==2.8.0 setuptools>=41.0.0 progressbar2 argparse smart_open backoff boto3 botocore google pr...
You're going to want pip install --no-cache-dir, so it doesn't keep copies of the downloads around. You don't want to keep the toolchain (compiler etc.) installed, but you need them to build the image. So what you do is, you use multi-stage builds: you use one image to build everything, and then a second image that ju...
https://stackoverflow.com/questions/60997203/
How to revert BERT/XLNet embeddings?
I've been experimenting with stacking language models recently and noticed something interesting: the output embeddings of BERT and XLNet are not the same as the input embeddings. For example, this code snippet: bert = transformers.BertForMaskedLM.from_pretrained("bert-base-cased") tok = transformers.BertTokenizer.fro...
Not sure if it's too late, but I've experimented a bit with your code and it can be reverted. :) bert = transformers.BertForMaskedLM.from_pretrained("bert-base-cased") tok = transformers.BertTokenizer.from_pretrained("bert-base-cased") sent = torch.tensor(tok.encode("I went to the store the ot...
https://stackoverflow.com/questions/60997438/
Google Colab become slower with the same code sometimes. What is the possible reasons?
I am training a CNN model with Google Colab's GPU through pytorch. My question is, even though running with the same code, it gets about three times slower sometimes(30s -> 90s in my case). I've tried restart runtime(it clears all local variable but keep files), it doesn't work I have seen this post, however, I'v...
Guys I think I found the possible answer here So it might be the limit of Google Colab itself. Due to their policy, sometimes you'll get fewer computation resources, which slower down the process even though no change in any code.
https://stackoverflow.com/questions/61016380/
Text classification using BERT - how to handle misspelled words
I am not sure if this is the best place to submit that kind of question, perhaps CrossValdation would be a better place. I am working on a text multiclass classification problem. I built a model based on BERT concept implemented in PyTorch (huggingface transformer library). The model performs pretty well, except when...
You can leverage BERT's power to rectify the misspelled word. The article linked below beautifully explains the process with code snippets https://web.archive.org/web/20220507023114/https://www.statestitle.com/resource/using-nlp-bert-to-improve-ocr-accuracy/ To summarize, you can identify misspelled words via a SpellCh...
https://stackoverflow.com/questions/61016422/
How to index a 3-d tensor with 2-d tensor in pytorch?
import torch a = torch.rand(5,256,120) min_values, indices = torch.min(a,dim=0) aa = torch.zeros(256,120) for i in range(256): for j in range(120): aa[i,j] = a[indices[i,j],i,j] print((aa==min_values).sum()==256*120) I want to know how to avoid to using the for-for loop to get the aa values? (I want to u...
You can use torch.gather aa = torch.gather(a, 0, indices.unsqueeze(0)) as explained here: Slicing a 4D tensor with a 3D tensor-index in PyTorch
https://stackoverflow.com/questions/61031110/
Pytorch - Indexing a range of multiple Indices?
Lets say I have a tensor of size [100, 100] and I have a set of start_indices and end_indices of size [100] I want to be able to do something like this: tensor[start_indices:end_indices, :] = 0 Unfortunately, I get an error saying TypeError: only integer tensors of a single element can be converted to an index So...
To the best of my knowledge this is not possible without some sort of loop or list comprehension. Below are some alternatives which may be useful depending on your use-case. Specifically if you are looking to reuse the same start_indices and end_indices for multiple assignments, or if you are looking have only one in-...
https://stackoverflow.com/questions/61034839/
Maxpool of an image in pytorch
I'm trying to just apply maxpool2d (from torch.nn) on a single image (not as a maxpool layer). Here is my code right now: name = 'astronaut' imshow(images[name], name) img = images[name] # pool of square window of size=3, stride=1 m = nn.MaxPool2d(3,stride = 1) img_transform = torch.Tensor(images[name]) plt.imshow(m(i...
Assuming your image is a numpy.array upon loading (please see comments for explanation of each step): import numpy as np import torch # Assuming you have 3 color channels in your image # Assuming your data is in Width, Height, Channels format numpy_img = np.random.randint(low=0, high=255, size=(512, 512, 3)) # Trans...
https://stackoverflow.com/questions/61049808/
why cannot cuda model be initialized under the __init__ method in a class that inherits multiprocessing.process?
Here is my code: from MyDetector import Helmet_Detector from multiprocessing import Process class Processor(Process): def __init__(self): super().__init__() self.helmet_detector = Helmet_Detector() def run(self): print(111) if __name__ == '__main__': p=Processor() ...
Error occurs because in python multiprocessing requires Process class objects to be pickelable so that data can be transferred to the process being created i.e. Serialisation and deserialization of the object. Suggestion to overcome the issue, lazy instantiate the Helmet_Detector object (hint: try property in python). ...
https://stackoverflow.com/questions/61052513/
how does the neural netwok definition in pytorch use pyton classes
in order to understand how this code works, I have written a small reproducer. How does the self.hidden variable use a variable x in the forward method? enter code class Network(nn.Module): def __init__(self): super().__init__() # Inputs to hidden layer linear transformation self.hidden = nn.Linear(784, 2...
You misunderstood what self.hidden = nn.Linear(784, 256) does. You wrote that: hidden is defined as a function but this is not true. self.hidden is an object of the class nn.Linear. And when you call self.hidden(...), you are not passing arguments to nn.Linear; you are passing arguments to __call__ (defined in th...
https://stackoverflow.com/questions/61068166/
Anaconda Integration with Cuda 9.0 shows Incompatible Package Error
I am trying to install CUDA 9.0 with NVIDIA-SMI: 445.75 in Windows 10. My Cuda 9.0 installation is successful, as shown from Command-prompt *(DL) C:\Users\User>nvcc --version nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2017 NVIDIA Corporation Built on Fri_Sep__1_21:08:32_Central_Dayli...
I got solved this issue as follows. Open Anaconda Powershell Prompt by searching it on the start menu. then run conda install -c anaconda tensorflow-gpu command. it may be asked to your acceptance. finally tensorflow-gpu listed on the installed list. Reference: https://anaconda.org/anaconda/tensorflow-gpu
https://stackoverflow.com/questions/61072464/
Pytorch "NCCL error": unhandled system error, NCCL version 2.4.8"
I use pytorch to distributed training my model.I have two nodes and two gpu for each node, and I run the code for one node: python train_net.py --config-file configs/InstanceSegmentation/pointrend_rcnn_R_50_FPN_1x_coco.yaml --num-gpu 2 --num-machines 2 --machine-rank 0 --dist-url tcp://192.168.**.***:8000 and the o...
A number of things can cause this issue, see for example 1, 2. Adding the line import os os.environ["NCCL_DEBUG"] = "INFO" to your script will log more specific debug info leading up to the error, giving you a more helpful error message to google.
https://stackoverflow.com/questions/61075390/
Kornia rotation not quite rotating as expected
I'm trying to use the kornia.geometry.transform.rotate function, in Python, to rotate a PyTorch tensor by arbitrary angles. However if I do a simple 90 degree rotation, the resulting tensor doesn't look like it's been fully rotated. Here's some sample code: import torch from kornia.geometry.transform import rotate i...
to use Kornia, you can use the Rotate class. Below is an example to rotating all tensors in a mini-batch by a fixed 45 degrees: import kornia as tgm # set the rotation angles - assume batch size is N; angle = torch.tensor([45]*N).cuda() # do the rotation: tensor_rotated = tgm.Rotate(angle)(tensor_input) The only ca...
https://stackoverflow.com/questions/61076613/
Image classification in Pytorch
I'm working on facenet-pytorch library in Pytorch, I want to know the data augmentation should be in train dataset or test data set? how many images should I put to test data set at least (I've used 2% of images in test data set) I have 21 classes(21 persons face) and with (vggface2 dataset ) with evaluation mode , ...
That's a lot of questions; you should probably split those up into multiple questions. In any case, I'll try answering some. Data augmentation should generally be done on the train dataset only. Typical augmentations include random rotation, resized crops, horizontal flips, cutout etc. All of these only go on the tra...
https://stackoverflow.com/questions/61101206/
pytorch element intersection
When I calculate the Hit Ratio, I need to calculate the number of elements of predict tensor in the target tensor, I wanna calculate the number of elements in their intersection. For example: [# of classes: 20, # of samples: 2] target: tensor([[14, 13, 8, 11, 18, 12, 5, 1, 0, 10], [ 8, 10, 2, 10, 7, 17...
Perhaps you could convert to numpy and then use its set operations. import torch import numpy as np target = torch.tensor([[14, 13, 8, 11, 18, 12, 5, 1, 0, 10], [ 8, 10, 2, 10, 7, 17, 6, 12, 13, 14]]) pred_idx = torch.tensor([[14, 11, 8, 19, 4], [ 6, 9, 8, 13, 18]]) Find elements of p@5 in target: [np.intersect1d(...
https://stackoverflow.com/questions/61108901/
Cannot improve model accuracy
I am building a general-purpose NN that would classify images (Dog/No Dog) and movie reviews(Good/Bad). I have to stick to a very specific architecture and loss function so changing these two seems out of the equation. My architecture is a two-layer network with relu followed by a sigmoid and a cross-entropy loss funct...
The issue you're facing is overfitting. With 100% accuracy on the training set, your model is effectively memorizing the training set, then failing to generalize to unseen samples. The good news is this is a very common major challenge! You need regularization. One method is dropout, whereby on different training epoc...
https://stackoverflow.com/questions/61110186/
PyTorch Model throwing error for list of layers
I have designed the following torch model with 2 conv2d layers. It works without any error. import torch.nn as nn from torchsummary import summary class mini_unet(nn.Module): def __init__(self): super(mini_unet, self).__init__() self.c1 = nn.Conv2d(1, 1, 3, padding = 1) self.r1 = nn.ReLU() ...
The error is maybe a little counter-intuitive but the error originates from you using python lists for the layers. From the documentation, you need to use torch.nn.ModuleList to contain the submodules, not a python list. So, just changing the list with nn.Modulelist(list) will solve the error. import torch.nn as nn ...
https://stackoverflow.com/questions/61116039/
Maybe I found something strange on pytorch, which result in property setter not working
Maybe I found something strange on pytorch, which result in property setter not working. Below is a minimal example that demonstrates this: import torch.nn as nn class A(nn.Module): def __init__(self): super(A, self).__init__() self.aa = 1 self.oobj = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] @pr...
It may not look obvious at first, but up until you set b.obj as a nn.Module object, you are defining a normal attribute; but once you set b.obj as a nn.Module object, then you can "only" replace b.obj with another nn.Module, because you registered it to _modules. Let me walk you through the code and you'll get it. nn....
https://stackoverflow.com/questions/61116433/
Differentiable image compression operations in PyTorch
During a CNN classification model training while calculating the loss I am applying the encoding jpeg compression on the image in PyTorch. While I call loss.backward() it must also backpropagate through encoding and compression operation performed on the images. Are those compression algorithms (e.g. encoding and JPE...
To start with, carefully consider whether you need to differentiate across the JPEG compression step. The vast majority of projects do not differentiate across this step, and if you're unsure if you need to, you probably don't. If you really need to differentiate across an image compressor, you might consider a code...
https://stackoverflow.com/questions/61132905/
Why doesn't nn.Sequential contain a softmax output layer in the example?
The example from PyTorch's official tutorial has the following ConvNet. My understanding is that the output layer uses a softmax to estimate the digit an image corresponds to. Why doesnt the code have a softmax layer or fully connected layer? model = nn.Sequential( nn.Conv2d(1, 16, kernel_size=3, stride=2, paddin...
This is a very good question! The reason why no fully-connected layer is used is because of a technique called Global Average Pooling, implemented via nn.AdaptiveAvgPool2d(1). The benefits of this operation over fc layers were introduced in this paper, including reducing the number of model parameters while preserving ...
https://stackoverflow.com/questions/61150929/
Creating a stack of convolutional layers using for loop in forward function of a pytoch class for Residual block
I'm defining a residual block in pytorch for ResNet in which you can input how many convolutional layers you want to have and not necessarily two. This is done through a parameter named nc (number of Convs). The first layer gets ni as the number of input nf number of filters. But from second layer on I put them in a fo...
Yeah, printing a nn.Module object is often misleading. When you print, you get: # for ni=3, nf=16 ResBlock( (conv1): Conv2d(3, 16, kernel_size=(3, 3), stride=(2, 2)) (conv2): Conv2d(16, 16, kernel_size=(3, 3), stride=(1, 1)) (conv1x1): Conv2d(3, 16, kernel_size=(1, 1), stride=(1, 1)) ) because these are the on...
https://stackoverflow.com/questions/61164539/
Predicting the next track using a vanilla RNN in PyTorch
For some context, I have a set of 37 playlists of 12 tracks long. Each track has been hand-selected in a certain way. Early songs in the playlist are generally more chilled and as the playlist progresses tracks begin to increase in tempo. I decided to commit to a project and build a deep playlist generator. I am imple...
Even though you want to run with a batch size of 1, your input (x) still needs a batch dimension. Try: output, hidden = model(x.unsqueeze(0), hidden)
https://stackoverflow.com/questions/61165591/
what is the difference between if-else statement and torch.where in pytorch?
See the code snippet: import torch x = torch.tensor([-1.], requires_grad=True) y = torch.where(x > 0., x, torch.tensor([2.], requires_grad=True)) y.backward() print(x.grad) The output is tensor([0.]), but import torch x = torch.tensor([-1.], requires_grad=True) if x > 0.: y = x else: y = torch.tensor...
Tracking based AD, like pytorch, works by tracking. You can't track through things that are not function calls intercepted by the library. By using an if statement like this, there's no connection between x and y, whereas with where, x and y are linked in the expression tree. Now, for the differences: In the first ...
https://stackoverflow.com/questions/61184437/
How to add pooling layer to BERT QA for large text
I'm trying to implement a Question answering system that deal with large input text: so the idea is to split the large input text into subsequences of 510 tokens, after I will generate the representation of each sequence independently and using a pooling layer to generate the final representation of the input sequence....
I'm pretty new to all of this myself, but maybe this could help you: def max_pooling(input_tensor, max_sequence_length): mxp = nn.MaxPool2d((max_sequence_length, 1),stride=1) return mxp(input_tensor)
https://stackoverflow.com/questions/61185592/
What does "conda install pytorch torchvision cudatoolkit=10.2 -c pytorch" install?
I tried installing PyTorch on my system with not just the pip install pytorch -c pytorch command but with conda install pytorch torchvision cudatoolkit=10.2 -c pytorch but I see a very long command prompt running since last 2 hours giving a very large outputs. Is the process going good? I've CUDA 10.2 installed and als...
The preferred way of installing PyTorch is through Anaconda, it has some of the common dependencies (packages) pre-installed and saves you a lot of time. Try a clean install of Conda and run: conda install pytorch torchvision cudatoolkit=10.1 -c pytorch The main difference between Anaconda and a vanilla Python insta...
https://stackoverflow.com/questions/61186333/
how does BatchNorm1d() method whithin the torch library work?
I'm learning pytorch, I don;t know if this question is stupid but I can't find the official web for explaining nn.batchnorm1d. I'm wondering how torch.nn.BatchNorm1d(d1) work? I know that batch norm is about making mean and variance of a batch of example to be 0 and 1 respectively. I'm wondering if there is nn.batchnor...
BatchNorm1d normalises data to 0 mean and unit variance for 2/3-dimensional data (N, C) or (N, C, L), computed over the channel dimension at each (N, L) or (N,) slice; while BatchNorm2d does the same thing for 4 dimensions (N, C, H, W), computed over the channel dimension at each (N, H, W) slice. Which one to use depe...
https://stackoverflow.com/questions/61193517/
Wrong Number of Init Arguments for Tanh in Pytorch
For a homework assignment, I am implementing a simple neural network in Python using Pytorch. Here is my network class: class Net(torch.nn.Module): def __init__(self, layer_dims, activation="sigmoid"): super(Net, self).__init__() layers = [] if activation == 'sigmoid': for i in ...
The error clearly says, Tanh only takes 1 argument, a tensor. From documentation, https://pytorch.org/docs/stable/nn.html Tanh class torch.nn.Tanh [source] Applies the element-wise function: Tanh(x)=tanh⁡(x)=ex−e−xex+e−x\text{Tanh}(x) = \tanh(x) = \frac{e^x - e^{-x}} {e^x + e^{-x}} Tanh(x)=tanh(x)=ex+e−xex−...
https://stackoverflow.com/questions/61193726/
Can't train ResNet using gpu with pytorch
I'm trying to use gpu to train a ResNet architecture on CIFAR10 dataset. Here's my code for ResNet : import torch import torch.nn as nn import torch.nn.functional as F class ResNetBlock(nn.Module): def __init__(self, in_planes, planes, stride=1): super(ResNetBlock, self).__init__() self.stride...
We would need a snippet of your training loop to better determine your error. I am asuming that somewhere on that loop you have some lines of code which do the following: for data, label in CifarDataLoader: data, label = data.to('cuda'), label.to('cuda') My first guess would be to add a line just before the fo...
https://stackoverflow.com/questions/61197394/
ValueError: Target and input must have the same number of elements. target nelement (50) != input nelement (100)
I'm new to Pytorch so I tried to learn it by creating simple dogs vs cats classification. The code: class DogCatClassifier(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 32, 5) self.conv2 = nn.Conv2d(32, 64, 5) self.conv3 = nn.Conv2d(64, 128, 5) ...
Your problem arises because you are using binary cross entropy instead of regular cross entropy. As the name implies, it checks weather the label is correct or not thus the shape of both tensors (preds and labels in your code) should be the same. As you are giving the confidence of both classes, the BCE loss function g...
https://stackoverflow.com/questions/61206312/
How can I load a partial pretrained pytorch model?
I'm trying to get a pytorch model running on a sentence classification task. As I am working with medical notes I am using ClinicalBert (https://github.com/kexinhuang12345/clinicalBERT) and would like to use its pre-trained weights. Unfortunately the ClinicalBert model only classifies text into 1 binary label while I h...
Removing the keys in the state dict before loading is a good start. Assuming you're using nn.Module.load_state_dict to load the pretrained weights then you'll also need to set the strict=False argument to avoid errors from unexpected or missing keys. This will ignore entries in the state_dict that aren't present in the...
https://stackoverflow.com/questions/61211685/
Loss Function in Multi-GPUs training (PyTorch)
I use Pytorch and BERT to traing a model. Everithing works great on one GPU, but when I try to use multi GPUs I am getting an error: ValueError Traceback (most recent call last) <ipython-input-168-507223f9879c> in <module>() 92 # single value; the `.item()` funct...
After loss loss = outputs[0] the loss is a multi-element tensor, the size is number of GPUs. You can use loss = outputs[0].mean() instead.
https://stackoverflow.com/questions/61214154/
PyTorch equivalent of numpy's np.random.RandomState
I'm looking for a way to create random objects without actually altering the pytorch global seed. i.e. an equivalent to numpy's: rand_gen = np.random.RandomState(seed) rand_gen.randint(0, 256, self.image_dim)) # for example
You could pass your torch.Generator manually to the random function. I think this code should work: gen0 = torch.Generator() gen1 = torch.Generator() gen0 = gen0.manual_seed(0) gen1 = gen1.manual_seed(1) torch.rand(5, generator=gen0) torch.rand(5, generator=gen0) torch.rand(5, generator=gen1) torch.rand(5, generator...
https://stackoverflow.com/questions/61224933/
How are contents of hidden_states tuple in BertModel in the transformers library arranged
model = BertModel.from_pretrained('bert-base-uncased', config=BertConfig.from_pretrained('bert-base-uncased',output_hidden_states=True)) outputs = model(input_ids) hidden_states = outputs[2] hidden_states is a tuple of 13 torch.FloatTensors. Each tensor is of size: (batch_size, sequence_length, hidden_size). Accordi...
Looking at the source-code for BertModel, it can be concluded that hidden_states[0] contains the outputs of the initial embedding layer, and the rest of the elements in tuples contain the hidden states in the increasing order of each layer. Simply put, hidden_states[1] contains the outputs of the first layer of BERT an...
https://stackoverflow.com/questions/61227950/
How to solve ' CUDA out of memory. Tried to allocate xxx MiB' in pytorch?
I am trying to train a CNN in pytorch,but I meet some problems. The RuntimeError: RuntimeError: CUDA out of memory. Tried to allocate 512.00 MiB (GPU 0; 2.00 GiB total capacity; 584.97 MiB already allocated; 13.81 MiB free; 590.00 MiB reserved in total by PyTorch) This is my code: import os import numpy as np ...
Before reducing the batch size check the status of GPU memory :slight_smile: nvidia-smi Then check which process is eating up the memory choose PID and kill :boom: that process with sudo kill -9 PID or sudo fuser -v /dev/nvidia* sudo kill -9 PID
https://stackoverflow.com/questions/61234957/
Pytorch - TypeError: ToTensor() takes no arguments using torchvision.transform
I’m trying to load in a dataset for super-resolution and I have set up two functions which use Compose to crop and resize the images. The function I have created for the input images works correctly and they are outputting as expected. The transform function for the target images is basically identical, just omitting ...
Problem solved! nothing to do with torchvision.transforms. I wasn't actually using the functions above, but inline declarations for compose which I had tried to use previously. My bad
https://stackoverflow.com/questions/61250268/
Can auto-encoder encode new vector without re-training afresh?
Here is a simple autoencoder to encode 3 vectors of dimension 1x3 : [1,2,3],[1,2,3],[100,200,500] to 1x1 : epochs = 1000 from pylab import plt plt.style.use('seaborn') import torch.utils.data as data_utils import torch import torchvision import torch.nn as nn from torch.autograd import Variable cuda = torch.cuda.is_...
Sorry but your code is a mess... And if it's just to showcase the autoencoder idea (here you just have X, Y, Z coordinates while you name it image) it's chosen pretty poorly. Out of the way: If it's an image you won't be able to encode it as a single pixel, this needs a little more sophistication. Source code Her...
https://stackoverflow.com/questions/61260489/
About using RNN in pytorch
I am trying to use RNN to do a binary classification. But when my model is training, it gets stuck at loss.backward(). Here is my model: class RNN2(nn.Module): def __init__(self, input_size, hidden_size, output_size=2, num_layers=1): super(RNN2, self).__init__() self.rnn = nn.RNN(input_size, hidden...
You have to know that in RRNs, computing the backward function for a sequence of length 420000 is extremely slow. If you run your code on a machine with a GPU (or google colab) and add the following lines before the for loop, your code finishes executing in less than two minutes. rnn = rnn.cuda() train_X = train_X.cu...
https://stackoverflow.com/questions/61260945/
TensorBoard: Tutorial Pytorch: module 'tensorflow._api.v2.io.gfile' has no attribute 'get_filesystem'
I am having issues running this tutorial about Pytorch and TensorBoard with Embeddings https://pytorch.org/tutorials/intermediate/tensorboard_tutorial.html I am having this message, AttributeError Traceback (most recent call last) <ipython-input-10-e0404d94b4cd> in <module>() ...
Try this import tensorflow as tf import tensorboard as tb tf.io.gfile = tb.compat.tensorflow_stub.io.gfile
https://stackoverflow.com/questions/61261451/
Is it possible to use LSTM predictions as inputs for next time steps?
I am working with LSTM (in PyTorch) for multivariate time series prediction. Let’s imagine the situation: I have 2 time series, A and B, and I want to predict t-value of B using previous values of A and B (before t). Such prediction works fine, my model gets good results. But what if (during testing, after training) I...
This is exactly what people do for machine translation and text generation in general. In this case, the LSTM predicts a distribution over a vocabulary, you select one word and use it as an input to the network in the next step. See PyTotrch tutorial on machine translation for more details. The important point is that...
https://stackoverflow.com/questions/61265768/
How to visualize a torch_geometric graph in Python?
Let's consider as an example that I have the following adjacence matrix in coordinate format: > edge_index.numpy() = array([[ 0, 1, 0, 3, 2], [ 1, 0, 3, 2, 1]], dtype=int64) which means that the node 0 is linked toward the node 1, and vice-versa, the nod...
import networkx as nx edge_index = torch.tensor([[0, 1, 1, 2], [1, 0, 2, 1]], dtype=torch.long) x = torch.tensor([[-1], [0], [1]], dtype=torch.float) data = torch_geometric.data.Data(x=x, edge_index=edge_index) g = torch_geometric.utils.to_networkx(data, to_undirected=True) nx.draw(g)
https://stackoverflow.com/questions/61274847/
BERT token importance measuring issue. Grad is none
I am trying to measure token importance for BERT via comparing token embedding grad value. So, to get the grad, I've copied the 2.8.0 forward of BertModel and changed it a bit: huggingface transformers 2.8.0 BERT https://github.com/huggingface/transformers/blob/11c3257a18c4b5e1a3c1746eefd96f180358397b/src/transformer...
I needed to add this line: embedding_output = torch.tensor(embedding_output, requires_grad=True) It seems, that I used .requires_grad_ method incorrectly.
https://stackoverflow.com/questions/61286574/
Why not super().__init__(Model,self) in Pytorch
For torch.nn.Module() According to the official documentation: Base class for all neural network modules. Your models should also subclass this class. Modules can also contain other Modules, allowing to nest them in a tree structure. You can assign the submodules as regular attributes. import torch.nn as nn import ...
This construct: super().__init__(self) is valid only in Python 3.x whereas the following construct, super(Model, self).__init__() works both in Python 2.x and Python 3.x. So, the PyTorch developers didn't want to break all the code that's written in Python 2.x by enforcing the Python 3.x syntax of super() since both ...
https://stackoverflow.com/questions/61288224/
Finding memory leak in python by tracemalloc module
I have a python script which uses an opensource pytorch model and this code has a memory leak. I am running this with memory_profiler mprof run --include-children python my_sctipt.py and get the following image: I am trying to search for the reason of the leak by the system python module tracemalloc: tracemalloc.sta...
Given that your guess is that the problem is in the C extension, but that you want to make sure this is true, I would suggest that you do so using a tool that is less python-specific like https://github.com/vmware/chap or at least if you are able to run your program on Linux. What you will need to do is run your scri...
https://stackoverflow.com/questions/61288749/
PyTorch: why the difference between dir(nn.Module()) and dir(nn.Module)
Tried e = dir(nn.Module()) f = dir(nn.Module) print([item for item in e if item not in f]) It gives ['_backward_hooks', '_buffers', '_forward_hooks', '_forward_pre_hooks', '_load_state_dict_pre_hooks', '_modules', '_parameters', '_state_dict_hooks', 'training'] why these are only available for the object not cl...
It's the other way around, those attributes are only available on the object (e in your case), but not on the class. The reason is simple, those are the attributes that are created in the constructor, hence they don't exist on the class and are only created when the object is created. From the nn.Module implementatio...
https://stackoverflow.com/questions/61290416/
The Batch Size of batch normalisation and gradient descent
We need to choose a batch size for GD as well as the normalization, they both called batch size, but in actual implementation, do they need to be the same? Or otherwise how the framework handle them? In Pytorch for example, one batch size is defined in dataloader, e.g. torch.utils.data.DataLoader(image_datasets[x]...
No, batch_size is only defined in the data loader, not in the model. The BatchNorm2d has a num_features parameter, and it depends on the number of channels and not the batch size, as you can see in the docs. They are completely unrelated. BatchNorm2d torch.nn.BatchNorm2d(num_features, eps=1e-05, momentum=0.1...
https://stackoverflow.com/questions/61293098/
pytorch geometric "Detected that PyTorch and torch_sparse were compiled with different CUDA versions" on google colab
I'm new to pytorch geometric, tried to install it to my computer but failed, so I'm trying to run the code on Google Colab instead. According to this previous question (which didn't help me and I'mnot sure its the same issue): PyTorch Geometric CUDA installation issues on Google Colab I did: !pip install --upgrade ...
I came up with the following snippet that should work on Colab to install PyTorch Geometric and its dependencies: https://gist.github.com/ameya98/b193856171d11d37ada46458f60e73e7 # Add this in a Google Colab cell to install the correct version of Pytorch Geometric. import torch def format_pytorch_version(version): r...
https://stackoverflow.com/questions/61297150/
From Coco annotation json to semantic segmentation image like VOC's .png in pytorch
I am trying to use COCO 2014 data for semantic segmentation training in PyTorch. I have a PSPNet model with a Cross Entropy loss function that worked perfectly on PASCAL VOC dataset from 2012. Now I am trying to use a portion of COCO pictures to do the same process. But Coco has json data instead of .png images for a...
I have worked on creating a Data Generator for the COCO dataset with PyCOCO and I think my experience can help you out. My post on medium documents the entire process from start to finish, including the creation of masks. However, point to note, I was working with Tensorflow Keras and not pytorch. But the logic flow s...
https://stackoverflow.com/questions/61318213/
How to understand hidden_states of the returns in BertModel?(huggingface-transformers)
Returns last_hidden_state (torch.FloatTensor of shape (batch_size, sequence_length, hidden_size)): Sequence of hidden-states at the output of the last layer of the model. pooler_output (torch.FloatTensor: of shape (batch_size, hidden_size)): Last layer hidden-state of the first token of the sequence (cl...
hidden_states (tuple(torch.FloatTensor), optional, returned when config.output_hidden_states=True): Tuple of torch.FloatTensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size). Hidden-states of the model at the output of each layer plus the...
https://stackoverflow.com/questions/61323621/
IndexError: Target -1 is out of bounds error in tabular learner fatai2
Getting the below error when trying to fit a tabular_learner from fastai2 library. used data loaders learn = tabular_learner(dls, layers=[1000,500], metrics=accuracy) learn.fit(30,1e-2) IndexError Traceback (most recent call last) <ipython-input-35-f0c57ab3748f> in <module...
Finally got figured this out, this happened because my validation set accidentally had more dependent variable classes than in my training set (or may be it was the other way around)......To fix this I had to ensure that my class size of training set and validation set are the same i:e make sure you do this check l...
https://stackoverflow.com/questions/61347613/
Need help understanding this Python list syntax
I'm having trouble understanding what this syntax means in Python: out = out[lengths - 1, range(len(lengths))] Why is there a range inside a list? How does that work? For context, I'm training a machine learning model in PyTorch. lengths is a list of the lengths of the input.
I assume lengths is an array of integers. (probably a Numpy array) The first index lengths - 1 will give a list of indices that is subtracted by -1. The second index range(len(lengths)) will give a list of numbers from 0 to the size of lengths. I don't know what the specific logic is in your code, but in general, yo...
https://stackoverflow.com/questions/61356477/
PyTorch - sparse tensors do not have strides
I am building my first sentiment analysis model for a small dataset of 1000 reviews using TF-IDF approach along with LSTM using the below code. I am preparing the train data by preprocessing it and feeding to the Vectorizer as below def tfidf_features(X_train, X_val, X_test): tfidf_vectorizer = TfidfVectorizer(analyze...
Pytorch does not support sparse (S) to sparse matrix multiplication. Let us consider : torch.sparse.mm(c1,c2), where c1 and c2 are sparse_coo_tensor matrices. case1: If we try c1 and c2 to be S --> It gives the erros RuntimeError: sparse tensors do not have strides. case2: If c1 is dense (D) and c2 is S --> It g...
https://stackoverflow.com/questions/61364160/
Making transformers BertForSequenceClassification initial layers non-trainable for pytorch training
I'm trying to do a transfer learning with BertForSequenceClassification https://huggingface.co/transformers/model_doc/bert.html#bertforsequenceclassification This is my simple NN model for classification. from transformers import BertTokenizer, BertForSequenceClassification class NN(nn.Module): def __init__(self)...
As the documentation says, class transformers.BertForSequenceClassification(config)[source] Bert Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks. This model is a PyTorch torch.nn.Module sub-class. Use it as a regular PyTorch ...
https://stackoverflow.com/questions/61374361/
How to initialize empty tensor with certain dimension and append to it through a loop without CUDA out of memory?
I am trying to append tensors (t) generated in a for-loop to a list [T] that accumulates all these tensors. Next, the list [T] requires to be converted into a tensor and needs to be loaded onto GPU. b_output = [] for eachInputId, eachMask in zip(b_input_ids, b_input_mask): # unrolled into...
Try using torch.cat instead of torch.tensor. You are currently trying to allocate memory for you new tensor while all the other tensors are still stored, which might be the cause of the out of memory error. Change : t_b_output = torch.tensor( b_output ) with: t_b_output = torch.cat( b_output ) Hope this help
https://stackoverflow.com/questions/61390323/
Libtorch:how to create tensor from tensorRT fp16 half type pointer?
how to create tensor from tensorRT fp16 half type pointer in libtorch? I am working on a detection model. I change the backbone of it to tensorRT to do FP16 inference, and the detection code such as decode boxes and nms is done in libtorch and torchvisoin, so how to create fp16 tensor from tensorRT half type pointers? ...
I have to do backbone inference in TensorRT, but the post process is using libtorch for convenience.And now I figure it out by using the following code: out = torch::from_blob(outputs[i], {1, num, dim, dim}, torch::kFloat16).to(device_used);
https://stackoverflow.com/questions/61400032/
Pytorch: Weight in cross entropy loss
I was trying to understand how weight is in CrossEntropyLoss works by a practical example. So I first run as standard PyTorch code and then manually both. But the losses are not the same. from torch import nn import torch softmax=nn.Softmax() sc=torch.tensor([0.4,0.36]) loss = nn.CrossEntropyLoss(weight=sc) input = to...
To compute class weight of your classes use sklearn.utils.class_weight.compute_class_weight(class_weight, *, classes, y) read it here This will return you an array i.e weight. eg . x = torch.randn(20, 5) y = torch.randint(0, 5, (20,)) # classes class_weights=class_weight.compute_class_weight('balanced',np.unique(y),y...
https://stackoverflow.com/questions/61414065/
Installing Pytorch Transformers in AWS Sagemaker
I'm trying to install the pytorch transformers package for my AWS Sagemaker notebook instance. However, it keeps giving me error of "No Module Found" for the package when i run my entry point script. I saw in an example for TensorFlowModel which requires to set up env but for Pytorch it is not the case (How do I load...
although you may be running that command from a SageMaker notebook, the training job you launch with the PyTorch estimator does not run on the notebook. It runs on remote, ephemeral infrastructure. You need to install your package on that remote machine. You need to add in the srcsource directory a requirements.txt fil...
https://stackoverflow.com/questions/61415420/
ResNet model of pytorch and tensorflow give different results when stride=2
class BasicBlock(nn.Module): def __init__(self, in_planes, out_planes, stride, dropRate=0.0): super(BasicBlock, self).__init__() self.bn1 = nn.BatchNorm2d(in_planes) self.relu1 = nn.ReLU(inplace=True) self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, ...
I finally found that the problem was the "padding". Tensorflow's "SAME" padding zero-pads assymmetrically (left=0, right=1, top=0, bottom=1) when symmetric padding results in odd number... While, pytorch do not support assymmetric padding in nn.conv2d, so it zero-pads symmetrically (left=1, right=1, top=1, bottom=1).. ...
https://stackoverflow.com/questions/61422046/
Loss not Converging for CNN Model
Image Transformation and Batch transform = transforms.Compose([ transforms.Resize((100,100)), transforms.ToTensor(), transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0.225]) ]) data...
The problem with your network is that you are applying softmax() twice - once at fc4() layer and once more while using nn.CrossEntropyLoss(). According to the official documentation, Pytorch takes care of softmax() while applying nn.CrossEntropyLoss(). So in your code, please change this line x = F.log_softmax(self...
https://stackoverflow.com/questions/61426911/
XLNetForSequenceClassification Pretrained model unable to load
I tried loading the XLNet pretrained but this occurred. I've tried this before and it worked, however, now it doesn't. Any suggestion on how to fix this problem? model = XLNetForSequenceClassification.from_pretrained("xlnet-large-cased", num_labels = 2) model.to(device) ----------------------------------------------...
You should import XLNetForSequenceClassification from transformers and not from pytorch-transformers. First, make sure transformers is installed: > pip install transformers Then, in your code: from transformers import XLNetForSequenceClassification model = XLNetForSequenceClassification.from_pretrained("xlnet-...
https://stackoverflow.com/questions/61431500/
Get the input channels for the conv2d from previous layer?
I was wondering if there are many convolutional layers (conv1 --> conv2 ). How can we get the input channels parameter for the conv2 from the conv1 output channel? class MyModel(nn.Module): def __init__(self, in_ch, num_features, out_ch2): super(MyModel, self).__init__() self.conv1 = nn.Conv2D(in_channels,nu...
Second parameter of nn.Conv2D constructor is number of output channels: self.conv1 = nn.Conv2D(in_channels,conv1_out_channels) self.conv2 = nn.Conv2D(conv1_out_channels,out_ch2) as described in the docs Also it available as a property: self.conv1.out_channels
https://stackoverflow.com/questions/61441174/
PyTorch Dataset and Conv1d using a ton of memory
I am trying to write a convolutional neural network in pytorch. I'm very new to machine learning and PyTorch, so I'm not very familiar with the package. I have written a custom dataset and it has loaded my data from a csv file properly. However, when I load it into a data loader, my system monitor shows python using a...
You are storing all datapoints in list(i.e. in memory) so it kinda deafeats the purpose of custom dataset/dataloader. you should just keep the reference of dataframe in your dataset class and for each index return the correct data something like def __init__(self, csv_file, train): self.train = train self.df_...
https://stackoverflow.com/questions/61452287/
Unable to find a valid cuDNN algorithm to run convolution
I just got this message when trying to run a feed forward torch.nn.Conv2d, getting the following stacktrace: --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-26-04bd4a00565d> in <module> ...
According to this answer for similar issue with tensorflow, it could occur because the VRAM memory limit was hit (which is rather non-intuitive from the error message). For my case with PyTorch model training, decreasing batch size helped. You could try this or maybe decrease your model size to consume less VRAM.
https://stackoverflow.com/questions/61467751/
Stacking binary mask frames in pytorch?
I am using Pytorch to attempt to create a 4-dimensional tensor (binary mask) using a "stack" of three-dimensional tensors that each hold binary masks. The three-dimensional tensors have n instances of some segmented object in a binary mask that is 704 wide and 1080 high. Lets lets say I have three of these 3-dimensio...
You can't. All tensor dimensions except first must be the same. Only way to do this, append dummy rows to first and third tensor to make them the same size (12,704,1280) Or you can stack it in one 3 -dim tensor.
https://stackoverflow.com/questions/61468368/
pytorch+tensorboard error " AttributeError: 'Tensor' object has no attribute 'items' "
Good afternoon. I want to log the loss of the train using the tensorboard in pytorch. I got an error there. AttributeError: 'Tensor' object has no attribute 'items' I want to solve this error and check the log using tensorboard. Here I show my code. l_mse = mseloss(img,decoder_out) writer.add_scalars("MSE",l_mse,n_...
You are calling for writer.add_scalars with a s. From Pytorch Tensorboardx documentation you can see that this function expects a dictionary as input. add_scalars(main_tag, tag_scalar_dict, global_step=None, walltime=None) tag_scalar_dict (dict) – Key-value pair storing the tag and corresponding values writer = ...
https://stackoverflow.com/questions/61471370/
CUDA error: CUBLAS_STATUS_ALLOC_FAILED when calling `cublasCreate(handle)`
I got the following error when I ran my pytorch deep learning model in colab /usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in linear(input, weight, bias) 1370 ret = torch.addmm(bias, input, weight.t()) 1371 else: -> 1372 output = input.matmul(weight.t()) 1373 if ...
No, batch size does not matter in this case The most likely reason is that there is an inconsistency between number of labels and number of output units. Try printing the size of the final output in the forward pass and check the size of the output print(model.fc1(x).size()) Here fc1 would be replaced by the name of...
https://stackoverflow.com/questions/61473330/
How calculate the dice coefficient for multi-class segmentation task using Python?
I am wondering how can I calculate the dice coefficient for multi-class segmentation. Here is the script that would calculate the dice coefficient for the binary segmentation task. How can I loop over each class and calculate the dice for each class? Thank you in advance import numpy def dice_coeff(im1, im2, e...
You can use dice_score for binary classes and then use binary maps for all the classes repeatedly to get a multiclass dice score. I'm assuming your images/segmentation maps are in the format (batch/index of image, height, width, class_map). import numpy as np import matplotlib.pyplot as plt def dice_coef(y_true, y_p...
https://stackoverflow.com/questions/61488732/
Cannot import Pytorch [WinError 126] The specified module could not be found
I'm trying to do a basic install and import of Pytorch/Torchvision on Windows 10. I installed a Anaconda and created a new virtual environment named photo. I opened Anaconda prompt, activated the environment, and I ran: (photo) C:\Users\<user>\anaconda3\envs>conda install pytorch torchvision cudatoolkit=10.2 ...
Refer to below link: https://discuss.pytorch.org/t/cannot-import-torch-on-jupyter-notebook/79334 This is most probably because you are using a CUDA variant of PyTorch on a system that doesn’t have GPU driver installed. That is to say, if you don’t have a Nvidia GPU card, please install the cpu-only package according t...
https://stackoverflow.com/questions/61488902/
Resuming pytorch model training raises error “CUDA out of memory”
My goal is to save the model at every epoch as I have to stop the training during the night and I don't want to lose progress. After I trained my model for 1 epoch I interrupted the process via terminal with CTRL+Z. When I tried to resume the training I got this error THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch...
Although this question has been posted 5 months ago, in case if anyone else comes across a similar issue, here is a simple solution. As explained in Pytorch FAQ, tensors defining the loss is accumulating history across the training loop because loss is a differentiable variable here. One simple solution is to typecast ...
https://stackoverflow.com/questions/61509872/
Cannot import torch - Image not found
I'm trying to import torch but failed because of Image not Found error. Here is the error when I entered import torch: --------------------------------------------------------------------------- ImportError Traceback (most recent call last) in ----> 1 import torch /Library/Framewor...
I solved this by doing this way, suppose you are using the virtual environment. Replace YOUR_PATH_TO_PYTHON_ENV with your python environment path. install_name_tool -add_rpath /usr/lib YOUR_PATH_TO_PYTHON_ENV/venv/lib/python3.8/site-packages/torch/_C.cpython-38-darwin.so If you are using your local python, maybe it ...
https://stackoverflow.com/questions/61525299/
How to save custom embedding matrix to .txt file format?
I have made a dictionary which contains word and its corresponding word vector in the following format: {'word1': array([ 4.530e-02, -1.170e-02, -1.201e-01, 2.439e-01, 4.670e-02d], type=float32), 'word2': array([ 4.530e-02, -1.170e-02, -1.201e-01, 2.439e-01, 4.670e-02d], type=float32)} I would like to save this ...
Python's .items() call is an elegant way to loop over all the words in your dictionary. This will save the output as lines of a text file: txt_filename = 'output.txt' with open(txt_filename, 'w') as f: for word, vec in my_wordvec_dict.items(): f.write('{} {}\n'.format(word, ' '.join(['{:e}'.format(item) f...
https://stackoverflow.com/questions/61530603/
Why do we need state_dict = state_dict.copy()
I want to load the weights of a pre-trained model on my local model. I don’t understand why state_dict = state_dict.copy() is necessary if the two networks have the same name state_dict. # copy state_dict so _load_from_state_dict can modify it metadata = getattr(state_dict, '_metadata', None) state_dict = state_dict.c...
state_dict = state_dict.copy() does exactly what you tell him to do: it copies in place the state_dict. State dict are all the parameters of your model, and copying it allows to make them independant. One should be careful whether you need a copy or a deepcopy though !
https://stackoverflow.com/questions/61531864/
Can conditionality be added inside Pytorch nn.Sequential()
Is there a way to add conditional statements inside the nn.Sequential(). Something similar to the code below. import torch class Building_Blocks(torch.nn.Module): def conv_block (self, in_features, out_features, kernal_size, upsample=False): block = torch.nn.Sequential( torch.nn.Conv2d(in_features, out...
No, but in your case it's easy to take if out of nn.Sequential: class Building_Blocks(torch.nn.Module): def conv_block(self, in_features, out_features, kernal_size, upsample=False): layers = [ torch.nn.Conv2d(in_features, out_features, kernal_size), torch.nn.ReLU(inplace=True), ...
https://stackoverflow.com/questions/61545224/
CNN vs SVM for smile intensity detection training?
I have a dataset made up of images of faces, with the corresponding landmarks that make up the mouth. These landmarks are sets of 2D points (x,y pixel position). Each image-landmark set data pair is tagged as either a smile, or neutral. What i would like to do is train a deep learning model to return a smile intensity...
It's hard to tell without looking into the dataset and experimenting. But hopefully, the following research materials will guide you in the right direction. Machine learning-based approach: https://www.researchgate.net/publication/266672947_Estimating_smile_intensity_A_better_way Deep learning (CNN): https://arxiv.or...
https://stackoverflow.com/questions/61549401/
pytorch: How to do layer wise multiplication?
I have a tensor containing five 2x2 matrices - shape (1,5,2,2), and a tensor containing 5 elements - shape ([5]). I want to multiply each 2x2 matrix(in the former tensor) with the corresponding value (in the latter tensor). The resultant tensor should be of shape (1,5,2,2). How to do that? Getting the following erro...
You can use either a * b or torch.mul(a, b) but you must use permute() before and after you multiply, in order to have the compatible shape: import torch a = torch.ones(1,5,2,2) b = torch.rand(5) a.shape # torch.Size([1, 5, 2, 2]) b.shape # torch.Size([5]) c = (a.permute(0,2,3,1) * b).permute(0,3,1,2) c.shape # torch...
https://stackoverflow.com/questions/61555342/
RuntimeError: stack expects each tensor to be equal size, but got [32, 1] at entry 0 and [32, 0] at entry 1
I have a very large tensor of shape (512,3,224,224). I input it to model in batches of 32 and I then save the scores corresponding to the target label which is 2. in each iteration, after every slice, the shape of scores changes. Which leads to the following error. What am I doing wrong and how to fix it. label = torch...
I don't know what happen to your code but you shouldn't do the batching like that honestly. Please use Dataset: import torch class MyDataloader(torch.utils.data.Dataset): def __init__(self): self.images = torch.Tensor(512, 3, 224, 224) def __len__(self): return 512 def __getitem__(self, ...
https://stackoverflow.com/questions/61558291/
Problem with Dataloader object not subscriptable
I am now running a Python program using Pytorch. I use my own dataset, not torch.data.dataset. I download data from a pickle file extracted from feature extraction. But the following errors appear: Traceback (most recent call last): File "C:\Users\hp\Downloads\efficient_densenet_pytorch-master\demo-emotion.py", line...
It is not the line giving you an error as it's the very last train function you are not showing. You are confusing two things: torch.utils.data.Dataset object is indexable (dataset[5] works fine for example). It is a simple object which defines how to get a single (usually single) sample of data. torch.utils.data.Da...
https://stackoverflow.com/questions/61562456/
Why pandas.core.series.Series sometimes cannot convert to torch tensor in Python?
I have a dataframe in which I pick two columns: X_train, X_test, y_train, y_test = train_test_split(df["EnergyFront"], df["particle"], test_size=0.2) the type of both X_train and X_test is pandas.core.series.Series, the results are quite similar: IMAGE I can transform X_train to torch tensor: X_train = torch.Ten...
This issue is described here: https://github.com/pytorch/pytorch/pull/7583 In order to determine the shape of the series, they try to access the element with index 0. If that element is not found, this error occurs. In your case, presumably this happens because your X_test doesn't contain the first element of the whole...
https://stackoverflow.com/questions/61565156/
Can not import fastai [WinError 126] The specified module could not be foun
Firstly I run the following command: conda install -c pytorch -c fastai fastai. After finishing install. I import this: from fastai.imports import * I got an error like this: Traceback (most recent call last): File "C:\Users\acer\Desktop\Reddit Bot\demo.py", line 70, in <module> from fastai.imports imp...
This probably happened if you, like me - are using a machine without a NVIDIA GPU card. conda install -c pytorch -c fastai fastai will install a version that uses the GPU. To resolve this, I uninstalled pytorch and then conda installed the CPU version using conda install pytorch torchvision cpuonly -c pytorch. It wor...
https://stackoverflow.com/questions/61569612/
An out of bounds index error when using Pytorch gather
I have Two Tensors I am trying to gather one from each row with the column being specified by these indices. So I am trying to get: [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1] This is my code for this: self.manDistMat.gather(1, state.unsqueeze(-1))) self.manDistMat being the 16x16 matrix and state.unsqueeze(-1) being the ...
I encountered the similar problem. It appears to be a bug in pytorch.
https://stackoverflow.com/questions/61572694/
Pytorch: Memory Efficient weighted sum with weights shared along channels
Inputs: 1) I = Tensor of dim (N, C, X) (Input) 2) W = Tensor of dim (N, X, Y) (Weight) Output: 1) O = Tensor of dim (N, C, Y) (Output) I want to compute: I = I.view(N, C, X, 1) W = W.view(N, 1, X, Y) PROD = I*W O = PROD.sum(dim=2) return O without incurring N * C * X * Y memory overhead. Basically ...
You can use torch.bmm (https://pytorch.org/docs/stable/torch.html#torch.bmm). Just do torch.bmm(I,W) To verify the results : import torch N, C, X, Y= 100, 10, 9, 8 i = torch.rand(N,C,X) w = torch.rand(N,X,Y) o = torch.bmm(i,w) # desired result code I = i.view(N, C, X, 1) W = w.view(N, 1, X, Y) PROD = I*W O = PRO...
https://stackoverflow.com/questions/61582511/
Pytorch | I don't know why it is throwing an error? (Beginner)
import torch.nn as nn import torch.nn.functional as F ## TODO: Define the NN architecture class Net(nn.Module): def __init__(self): super(Net, self).__init__() # linear layer (784 -> 1 hidden node) self.fc1 = nn.Linear(28 * 28, 512) self.fc2 = nn.Linear(512 * 512) self.fc...
This error is because you have not provided the output size of the fully connected layer in your fc2 and fc3. Below is the modified code. I added the output size, I am not sure if this is the output size architecture you want. But for the demonstration, I put the output size. Please edit the code and add the output siz...
https://stackoverflow.com/questions/61587563/
Pytorch squeeze and unsqueeze
I don't understand what squeeze and unsqueeze do to a tensor, even after looking at the docs and related questions. I tried to understand it by exploring it myself in python. I first created a random tensor with x = torch.rand(3,2,dtype=torch.float) >>> x tensor([[0.3703, 0.9588], [0.8064, 0.9716], ...
Here is a visual representation of what squeeze/unsqueeze do for an effectively 2d matrix: When you are unsqueezing a tensor, it is ambiguous which dimension you wish to 'unsqueeze' it across (as a row or column etc). The dim argument dictates this - i.e. position of the new dimension to be added. Hence the resulting ...
https://stackoverflow.com/questions/61598771/
Is there any difference between tensor2tensor and pytorch in view of memory?
I'm trying to train seq2seq model(transformer) with pytorch and tensor2tensor. When using tensor2tensor, the batch size can be like 1024, while pytorch model shows CUDA out of memory error with 8 batch size. Is there any technique used in tensor2tensor to make best use of memory. If anyone know this, please tell me. ...
In Tensor2Tensor by default, the batch size is specified in the number of tokens (subwords) per single GPU. This allows to use a higher number of short sequences (sentences) in one batch or a smaller number of long sequences. Most other toolkits use a fixed batch size specified in the number of sequences. Either way, i...
https://stackoverflow.com/questions/61607629/
How to split a dataset into a custom training set and a custom validation set with pytorch?
I'm using a non-torchvision dataset and I have extracted it with the ImageFolder method. I'm trying to split the dataset into 20% validation set and 80% training set. I can only find this method (random_split) from PyTorch library which allows splitting dataset. However, this is random every time. I'm wondering is ther...
If you look "under the hood" of random_split you'll see it uses torch.utils.data.Subset to do the actual splitting. You can do so yourself with fixed indices: import random indices = list(range(len(TrafficSignSet)) random.seed(310) # fix the seed so the shuffle will be the same everytime random.shuffle(indices) trai...
https://stackoverflow.com/questions/61623709/
Pytorch equivalent features in tensorflow?
I recently was reading a Pytorch code and came across loss.backward() and optimizer.step() functions, are there any equivalent of these using tensorflow/keras?
loss.backward() equivalent in tensorflow is tf.GradientTape(). TensorFlow provides the tf.GradientTape API for automatic differentiation - computing the gradient of computation with respect to its input variables. Tensorflow "records" all operations executed inside the context of a tf.GradientTape onto a &quo...
https://stackoverflow.com/questions/61623722/
PyTorch nn.Transformer learns to copy target
I’m trying to train a Transformer Seq2Seq model using nn.Transformer class. I believe I am implementing it wrong, since when I train it, it seems to fit too fast, and during inference it repeats itself often. This seems like a masking issue in the decoder, and when I remove the target mask, the training performance is ...
For those having the same problem, my issue was that I wasn't properly adding the SOS token to the target I was feeding the model, and the EOS token to the target I was using in the loss function. For reference: The target fed to the model should be: [SOS] .... And the target used for the loss should be: .... [EOS]
https://stackoverflow.com/questions/61626779/
Unable to install fastai on Jupyter Notebook
I'm currently trying to get fastai installed on a conda environment using the command conda install -c fastai fastai as shown in the installation guide. This is what appears when that command is ran: (fastai) C:\>conda install -v -c fastai fastai Collecting package metadata (current_repodata.json): ...working... Un...
Try downgrading from python3.8 to python 3.7, it works for me.
https://stackoverflow.com/questions/61627669/
Logloss metric in Fastai
i'm doing a competition in zindi plateform which they are using The evaluation metric for this challenge as Log Loss. so i'm working with fastai library and i want the metric log loss .. i didn't find LogLoss as metric in this library ! i tried some codes like the function provided by sklearn from sklearn.metrics imp...
if needed as a metric (typically mostly used as a loss) you should be able to use cross_entropy function from pytorch: import torch.nn.functional as F metrics=[F.cross_entropy,(plus other metrics if needed)] model= cnn_learner(data, model, metrics=metrics,...)
https://stackoverflow.com/questions/61627797/