instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
DistributedSampler — Expected a ‘cuda’ device type for generator when generating indices
Performing distributed training, I have the following code like this: training_sampler = DistributedSampler(training_set, num_replicas=2, rank=0) training_generator = data.DataLoader(training_set, **params, sampler=training_sampler) for x, y, z in training_generator: # Error occurs here. ... Overall, I get the fo...
I just met the same problem using dataloader and I found the following helps without removing torch.set_default_tensor_type('torch.cuda.FloatTensor') data.DataLoader(..., generator=torch.Generator(device='cuda')) since I don't want to manually add .to('cuda') for tons of tensors in my code
https://stackoverflow.com/questions/64940953/
Installing Python dependencies in Heroku
I wanted to make an Ai chatbot hosted on Heroku, but there are some problems with installing the requirements. The chatbot needs the following packages: discord pytorch spaCy I already figured out putting discord into the requirements.txt, but I got no clue on how to do the other two dependencies. The problem with th...
You can use the following to create a requirements.txt file having all the dependency installed in your current environment. This will install pip freeze > requirements.txt To download the Spacy Models, you can add this in the requirements.txt https://github.com/explosion/spacy-models/releases/download/en_core_web_...
https://stackoverflow.com/questions/64943891/
Pytorch - AttributeError: 'tuple' object has no attribute 'dim'
I am trying to use this architecture: class Net(BaseFeaturesExtractor): def __init__(self, observation_space: gym.spaces.Box, features_dim: int = 512): super(Net, self).__init__(observation_space, features_dim) self.conv1 = nn.Conv2d(1, 64, 3, stride=1, padding=1) self.conv2 = nn.Conv2d(64...
I tried to reproduce a small working code based on the class definitions given by you and I was able to get the outputs from the model. Here is the following code: # BaseFeaturesExtractor class import gym import torch as th from torch import nn class BaseFeaturesExtractor(nn.Module): """ Base cl...
https://stackoverflow.com/questions/64950464/
Image augmentation in Pytorch
I like to augment image alternately. I have pytorch transform code as follows. import torchvision.transforms as tt from torchvision.datasets import ImageFolder #Data transform (normalization & data augmentation) stats = ((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)) train_tfms = tt.Compose([tt.RandomCrop(32, ...
From a single dataset you can create two datasets one with augmentation and the other without, and then concatenate them. The order is going to be kept since we are using the subdataset pytorch class which will handle this for us. train_ds_no_aug = ImageFolder('content/train') train_ds_aug = ImageFolder('content/train'...
https://stackoverflow.com/questions/64952519/
Multiplying two 3D Pytorch tensors iteratively
I have two 3 dimensional Pytorch tensors, one of dimension (8, 1, 1024) and the other has dimension (8, 59, 77). I wish to multiply these two tnesors. I know they cannot be multiplied in their current state, so I want to multiply them iteratively and append into a single tensor. The second tensor can be represented as ...
If I didn't mess up the computation, it would be equivalent to: import torch x = torch.rand(8, 1, 1024) y = torch.rand(8, 59, 77) torch.matmul( y.unsqueeze(-1), # shape = (8, 59, 77, 1) x.unsqueeze(1) # shape = (8, 1, 1, 1024) ).permute(0, 1, 3, 2) # output shape = (8, 59, 1024, 77) Note that, in this...
https://stackoverflow.com/questions/64952700/
LSTM to Predict Pattern 010101... Understanding Hidden State
I did a quick experiment to see if I could understand what the hidden state in an LSTM does... I tried to make an LSTM predict a sequence of [1,0,1,0,1...] based off an input sequence of X with X[0] = 1 and the remainder as random noise. X = [1, randFloat, randFloat, randFloat...] label = [1, 0, 1, 0...] In my head, ...
I would say it's not meant to work. The model would always try to make sense and find patterns in the data it's trained on i.e sequence_1 and to "verify" that it has "found" them, it uses labels_1. Since the data is random the model fails to find the pattern. The pattern the model tries to find is n...
https://stackoverflow.com/questions/64960794/
How to create and use PyTorch learnable scalar variables outside of nn.Module?
I am working on a multi-objective problem where I have multiple losses that I need to compute, and the total loss is just the sum of the losses. I want to have PyTorch learnable floating-point parameters alpha, and beta that act as coefficients to the individual losses. Note that the summation of losses occurs outside ...
You can put them into a list and add them to an optimizer, for example, optimizer_for_my_params = torch.Adam([alpha, beta], lr=1e-3) or separately, optimizer_alpha = torch.Adam([alpha], lr=1e-3) optimizer_beta = torch.Adam([beta], lr=1e-3) and at each step, call zero_grad and step on all optimizers. Or you can put th...
https://stackoverflow.com/questions/64963125/
Pytorch CNN:RuntimeError: Given groups=1, weight of size [16, 16, 3], expected input[500, 1, 19357] to have 16 channels, but got 1 channels instead
class ConvolutionalNetwork(nn.Module): def __init__(self, in_features, trial): super().__init__() self.in_features = in_features self.trial = trial # this computes num features outputted from the two conv layers c1 = int(((self.in_features - 2)) / 64) # this is to account fo...
Well, just after entering in the forward method you are reshaping your input array so it has only a single channel: x = x.view(-1, 1, self.in_features) And at the same time at the model constructor you are specifying that conv1 has 16 channels as input: self.conv1 = nn.Conv1d(16, 16, 3, 1) Thus the error of expecting...
https://stackoverflow.com/questions/64963473/
How to get number of classes from .pth file without any model information in Python?
I have a .pth file and there is no model information available. How can I know the number of final output classes in .pth file. For visualization, I can use Netron to see the number of classes. But, how can I get the same output number in Python.
You can load the checkpoint and inspect the shape of the weights of the last layer. Depending if the last layer has two weights (kernel and bias), you will have to inspect both. I provide you with an example on how to inspect the last weight. import torch checkpoint = torch.load('_.pt') last_key = list(checkpoint)[-1...
https://stackoverflow.com/questions/64964239/
EasyOCR used under Python / Torch Multiprocessing is defaulting to CPU
I am using EasyOCR for text extraction from images. It uses PyTorch. There are multiple images in different folders and the sequence in which these folders are read isn't consequential. When run in sequence, EasyOCR is by default using GPU and is faster compared to when run on CPU. But when Python / Torch Multiprocessi...
If torch.cuda.is_available returns False, Verify your device has a GPU. Verify that the installed version of CUDA is supported on your GPU. Verify that you have installed torch with CUDA support. Check this question for additional details: Why `torch.cuda.is_available()` returns False even after installing pytorch wi...
https://stackoverflow.com/questions/64967770/
"Didn't find engine for operation quantized" error while using dynamic quantization with Huggingface transformer
I am trying to do dynamic quantization(quantizes the weights and the activations) on a pytorch pre-trained model from huggingface library. I have referred this link and found dynamic quantization the most suitable. I will be using the quantized model on a CPU. Link to hugginface model here. torch version: 1.6.0 (instal...
Is qnnpack in the list when you run print(torch.backends.quantized.supported_engines)? Does torch.backends.quantized.engine = 'qnnpack' work for you?
https://stackoverflow.com/questions/64968060/
pipenv install pytorch cpu + specific version
I ned to install a specific version of pytorch cpu mode. With pip I would do it like this: pip install torch==1.2.0+cpu torchvision==0.4.0+cpu -f https://download.pytorch.org/whl/torch_stable.html --trusted-host download.pytorch.org How can I achieve the same using Pipenv? I tried having the following Pipfile: [[source...
You can do: $ PIP_FIND_LINKS="https://download.pytorch.org/whl/torch_stable.html" pipenv install torch==1.2.0+cpu torchvision==0.4.0+cpu But, you'll have to ensure that you add PIP_FIND_LINKS for any consecutive pipenv sync, pipenv lock, etc. UPD: You may also add PIP_FIND_LINKS="https://download.pytorc...
https://stackoverflow.com/questions/64974877/
PyTorch installation fails Could not find a version that satisfies the requirement
I'm trying to install PyTorch with PyCharm Community Edition 2020.2.3 x64 and Python 3.9.0 on Windows 10 pro 64-bit OS PC machine I've tried: pip install torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html and: python -m pip install torch==1.7.0 -f https://d...
I tried with Python 3.8.0, Python 3.8.5, Python 3.8.6 and Python 3.9.0. It seems to work only with 3.8.6 version.
https://stackoverflow.com/questions/64975755/
PyTorch how to compute second order Jacobian?
I have a neural network that's computing a vector quantity u. I'd like to compute first and second-order jacobians with respect to the input x, a single element. Would anybody know how to do that in PyTorch? Below, the code snippet from my project: import torch import torch.nn as nn class PINN(torch.nn.Module): ...
So as @jodag mentioned in his comment, ReLU being null or linear, its gradient is constant (except on 0, which is a rare event), so its second-order derivative is zero. I changed the activation function to Tanh, which finally allows me to compute the jacobian twice. Final code is import torch import torch.nn as nn cla...
https://stackoverflow.com/questions/64978232/
DenseNet, Sizes of tensors must match
would you know how I can adapt this code so that sizes of tensors must match because I have this error: x = torch.cat([x1,x2],1) RuntimeError: Sizes of tensors must match except in dimension 0. Got 32 and 1 (The offending index is 0). My images are size 416x416. Thank you in advance for your help, num_classes = 20 clas...
The shapes of the two tensors are very different and that's why the torch.cat() fails. I tried to run your code with the following example: def forward(self, x): x1 = self.SiLU(self.dens121(x)) x1 = x1.view(-1, 2048) x2 = self.inc(x).view(-1, 2048) print(x1.shape, x2.shape) x = torch.cat([x...
https://stackoverflow.com/questions/64984301/
The definition of "heads" in MultiheadAttention in Pytorch Transformer module
I am a bit confused about the definition of Multihead. Are [1] and [2] below the same? [1] My understanding about multiplhead is the multiple attention patterns as below. "multiple sets of Query/Key/Value weight matrices (the Transformer uses eight attention heads, so we end up with eight sets for each encoder/dec...
As per your understanding, multi-head attention is multiple times attention over some data. But on contrast, it isn't implemented by multiplying the set of weights into number of required attention. Instead, you rearrange the weight matrices corresponding to the number of attentions, that is reshape to the weight-matri...
https://stackoverflow.com/questions/64984627/
"RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn " error BertFoeSequenceClassification
I am trying to build Bert model for Arabic Text classification task using pretrained model from https://github.com/alisafaya/Arabic-BERT i want to know the exact difference between the two statement: model_name = 'kuisailab/albert-large-arabic' model = AutoModel.from_pretrained(model_name) model = BertForSequenceClass...
BertForSequenceClassification is the class which extends the BertModel, i.e, BertForSequenceClassification defines a logistic regression layer, for the task of classificiation, with cross-entropy loss, to be jointly fine-tuned or trained on the existing Bert Model. AutoModel, is a class provided in the library that all...
https://stackoverflow.com/questions/64985740/
How to compute Hessian of the loss w.r.t. the parameters in PyTorch using autograd.grad
I know there is quite a bit of content out there about "computing the Hessian" in pytorch, but as far as I've seen I haven't found anything working for me. So to try to be most precise, the Hessian that I want is the Jacobian of the gradient of the loss with respect to the network parameters. Also called the ...
PyTorch recently-ish added a functional higher level API to torch.autograd which provides torch.autograd.functional.hessian(func, inputs,...) to directly evaluate the hessian of the scalar function func with respect to its arguments at a location specified by inputs, a tuple of tensors corresponding to the arguments of...
https://stackoverflow.com/questions/64997817/
Triton inference server serving TorchScript model
I am trying to serve a TorchScript model with the triton (tensorRT) inference server. But every time I start the server it throws the following error: PytorchStreamReader failed reading zip archive: failed finding central directory My folder structure is : <model_repository> <model_name> config.pbtxt...
I found the solution. It was a silly mistake on my part. The .pt torchscript file was not loaded properly.
https://stackoverflow.com/questions/65010792/
Run validation on 1 GPU while Train on multi-GPU Pytorch Lightning
Is there any way I can execute validation_step method on single GPU while training_step with multiple GPU using DDP. The reason I want to do is because there are several metrics which I want to implement which requires complete access to the data, and running on single GPU will ensure that. I have tried validation_step...
I am afraid that this is not possible. But there is the TorchMetrics package which has been developed with multi-GPU support in mind so when your custom metric is derived from TM you shall be able to get running even on your multi-GPU setting.
https://stackoverflow.com/questions/65013992/
How to use a learnable parameter in pytorch, constrained between 0 and 1?
I want to use a learnable parameter that only takes values between 0 and 1. How can I do this in pytorch? Currently I am using: self.beta = Parameter(torch.Tensor(1)) #initialize zeros(self.beta) But I am getting zeros and NaN for this parameter, as I train.
You can have a "raw" parameter taking any values, and then pass it through a sigmoid function to get a values in range (0, 1) to be used by your function. For example: class MyZeroOneLayer(nn.Module): def __init__(self): self.raw_beta = nn.Parameter(data=torch.Tensor(1), requires_grad=True) def forwa...
https://stackoverflow.com/questions/65022269/
How to randomly mix two PyTorch tensors
I have two same-shaped PyTorch tensors A and B, and I'd like to create a same-shape "randomly mixed" tensor C where C[i,...] = A[i,...] with probability alpha or B[i,...] with probability 1-alpha. Is there some Pythonic way to do this compactly?
consider using torch.bernoulli to create a mask tensor: import torch prob = 0.8 x = torch.full((2, 6, 3), 10.2, dtype=torch.float) y = torch.full((2, 6, 3), -1.6, dtype=torch.float) mask = torch.bernoulli(torch.full(x.shape, prob)).int() reverse_mask = torch.ones(x.shape).int() - mask result = x * mask + y * reverse...
https://stackoverflow.com/questions/65027847/
RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.cuda.HalfTensor) should be the same
I just start to learn about the YOLO v5 PyTorch version and I was able to build a model, so then I tried to implement a flask application for real-time prediction using this trained model. class for load model and predict class Model(object): def __init__(self, model): self.device = torch_utils.select_dev...
this error means: the input type is float32, the weight type(of your model) is float16. for exsample, this code below runned: model.half() # so the weight type is float16 but this code below not runned: img = img.half() # so the input type is float32 please check your code. for more information about 'half', you can ...
https://stackoverflow.com/questions/65029217/
How to "cut" a tensor into half in Pytorch?
I have a tensor with shape [1, 2, 96, 96] and would like two tensors with the shape [1, 1, 96, 96], is there a quick way of doing this? Thanks in advance
a, b = tensor.split(1, dim=1) should do the job. By specifying 1 you specify how many elements should be in each split e.g. [1,2,3,4,5,6].split(2) -> [1,2] [3,4] [5,6]. Then dim just specifies which dimension to split over which in your case would be one. EDIT: if you wanted to cut it in half more generally use tens...
https://stackoverflow.com/questions/65033693/
What is the function of FrozenBatchNorm2d in “maskrcnn_benchmark”?
"maskrcnn_benchmark"s github Here is the source code for "FrozenBatchNorm2d" import torch from torch import nn class FrozenBatchNorm2d(nn.Module): def __init__(self, n): super(FrozenBatchNorm2d, self).__init__() self.register_buffer("weight", torch.ones(n)) self...
"register_buffer" means open an RAM for some parameters which couldn't be optimized or changed during the tranning process, in another word, the "weight","bias","running_mean","running_var" are consistent values. Hence, that is the reason why this rebuild batchnorm met...
https://stackoverflow.com/questions/65034269/
Remove downloaded tensorflow and pytorch(Hugging face) models
I would like to remove tensorflow and hugging face models from my laptop. I did find one link https://github.com/huggingface/transformers/issues/861 but is there not command that can remove them because as mentioned in the link manually deleting can cause problems because we don't know which other files are linked to t...
The transformers library will store the downloaded files in your cache. As far as I know, there is no built-in method to remove certain models from the cache. But you can code something by yourself. The files are stored with a cryptical name alongside two additional files that have .json (.h5.json in case of Tensorflow...
https://stackoverflow.com/questions/65037368/
How to get indices of top-K values from a numpy array
Let suppose I have probabilities from a Pytorch or Keras predictions and result is with the softmax function from scipy.special import softmax probs = softmax(np.random.randn(20,10),1) # 20 instances and 10 class probabilities probs I want to find top-5 indices from this numpy array. All I want to do is to run a loop ...
A little more expensive, but argsort would do: idx = np.argsort(probs, axis=1)[:,-5:] If we are talking about pytorch: probs = torch.from_numpy(softmax(np.random.randn(20,10),1)) values, idx = torch.topk(probs, k=5, axis=-1)
https://stackoverflow.com/questions/65038206/
Incompletable PyTorch with any CUDA version (module 'torch' has no attribute 'cuda')
I have NVidia 1080TI, Ubuntu x64, and Python 3.6.9 installed. I was trying to launch PyTorch with command import torch print(torch.cuda.is_available) and expected to see 'True' but met the error: AttributeError: module 'torch' has no attribute 'cuda' I tried to update PyTorch and install the last version 1.7.0 with C...
As a result, I had a file named torch.py in my home directory. After the renaming problem was solved. Thanks. Maybe my answer will be helpful to someone.
https://stackoverflow.com/questions/65045558/
Debugging pytorch code in pycharm (Feasibility)
I am trying to run a code in written in python (pytorch code) which when passed as an arguments options trains the Neural network. if __name__ == "__main__": args = docopt(__doc__) myparams = args["options"] .... /* do work */ Now if we have to run this code, I need to call it from ...
Look at menu bar,Run->Edit Configurations->(Chose One Configuration)Parameters
https://stackoverflow.com/questions/65049919/
PyTorch error in trying to backward through the graph a second time
I'm trying to run this code: https://github.com/aitorzip/PyTorch-CycleGAN I modified only the dataloader and transforms to be compatible with my data. When trying to run it I get this error: Traceback (most recent call last): File "models/CycleGANs/train", line 150, in loss_D_A.backward() File "/opt/co...
loss_G.backward() should be loss_G.backward(retain_graph=True) this is because when you use backward normally it doesn't record the operations it performs in the backward pass, retain_graph=True is telling to do so.
https://stackoverflow.com/questions/65050791/
pytorch: how to apply function over all cells of 4-d tensor
I'm trying to apply a function over a 4-D tensor (I think about it as a 2-D matrix with a 2-D matrix in each cell) with the following dimensions: [N x N x N x N]. The apply function returns [1 x N] tensor, so after the apply function I'm expecting a tensor of the following dimensions: [N x N x 1 x N]. Example: let's de...
Let's try: new_shape=(-1,)+tensor_4d.shape[2:] out = (torch.stack([apply_function(t) for t in tensor_4d.view(new_shape)], axis=-1) .reshape(new_shape) )
https://stackoverflow.com/questions/65051014/
What could be reason of "ValueError: axes don't match array error" for Pytorch U-net segmentation model?
I'm trying to implement a segmentation model (which i used for another dataset succesfully before) for kaggle dataset called "Carvana Image Masking Challange". I searched a lot, but still could not figured out what is the reason i am getting this error. There were some suggestion to check image dimension whic...
There were 2 problem on the above code; Mask image size was wrong, expected as (x,y,1) but it was (x,y,3) Model expect equal size of rows and columns. After above changes code works well properly.
https://stackoverflow.com/questions/65055133/
Validation loss is neither increasing or decreasing
Usually when a model overfits, validation loss goes up and training loss goes down from the point of overfitting. But for my case, training loss still goes down but validation loss stays at same level. Hence validation accuracy also stays at same level but training accuracy goes up. I am trying to reconstruct a 2D imag...
The trends show that your model is overfitting. Ways to overcome overfitting include: Use data augmentation Use more data Use Dropout Use regularization Try slowing down your learning rate!
https://stackoverflow.com/questions/65057340/
Pytorch multiprocessing with shared memory causes matmul to be 30x slower (with only two processes)
I am trying to improve the speed of my reinforcement learning algorithm by using multiprocessing to have multiple workers generating experience at the same time. Each process just runs the forward pass of my neural net, no gradient computation is needed. As I understand it, when passing Tensors and nn.Modules across p...
It seems like this was caused by a bad interaction of OpenMP (used by pytorch by default) and multiprocessing. This is a known issue in pytorch (https://github.com/pytorch/pytorch/issues/17199) and I was even hitting deadlocks in certain configurations I used to debug. Turning off OpenMP using torch.set_num_threads(1...
https://stackoverflow.com/questions/65057388/
Pytorch - (Categorical) Cross Entropy Loss using one hot encoding and softmax
I'm looking for a cross entropy loss function in Pytorch that is like the CategoricalCrossEntropyLoss in Tensorflow. My labels are one hot encoded and the predictions are the outputs of a softmax layer. For example (every sample belongs to one class): targets = [0, 0, 1] predictions = [0.1, 0.2, 0.7] I want to compute...
I thought Tensorflow's CategoricalCrossEntropyLoss was equivalent to PyTorch's CrossEntropyLoss but it seems not. The former takes OHEs while the latter takes labels as well. It seems, however, that the difference is: torch.nn.CrossEntropyLoss is a combination of torch.nn.LogSoftmax and torch.nn.NLLLoss(): tf.keras...
https://stackoverflow.com/questions/65059829/
How to call a network in tf.keras.Sequential()?
If I use pytorch, I could use [index] to loop the layers: layers = nn.ModuleList() q = nn.ModuleList() for _ in range(10): layers.append(attn) q.append(nn.Linear(dim1, dim2)) list = [] for index, layer in enumerate(self.layers): Q = q[index](inputTensor) list.append(layer(attn)) so when...
Yes - it is possible: model = tf.keras.Sequential([ tf.keras.layers.Dense(128), tf.keras.layers.Dense(1) ]) for layer in model.layers: Q = layer
https://stackoverflow.com/questions/65061871/
How to convert yolov4 weights.wt to pytorch weights .pt?
I was trying out the yolov4 from https://github.com/theAIGuysCode/YOLOv4-Cloud-Tutorial and I wanted to convert the weights from .wt files to .pt files for pytorch Is there a way I can do that?
Pytorch YOLOv4 (I am biased as I am a maintainer) has the ability to do this with darknet2pytorch. The following is an example snippet from tool.darknet2pytorch import Darknet WEIGHTS = Darknet(cfgfile) WEIGHTS.load_weights(weightfile) Where cfgfile is your darknet config.cfg file, and weightfile is your darknet .wt w...
https://stackoverflow.com/questions/65067023/
Implementing a simple optimization algorithm in PyTorch
I'm currently learning PyTorch in order to utilize its open source autograd feature, and as an exercise for myself, I want to implement a simple optimization algorithm that I've already implemented in MATLAB. As a simple example, say I'm trying to solve the problem min_x 1/2 x'Ax - b'x, i.e. find the vector x which min...
Basically you need to use the autograd in pytorch. Not a complete program but it'll look something like this along the lines: In each iteration do the following: Specify x.requires_grad=True because you need its gradient. Then compute your objective function: x.requires_grad = True obj_function = torch.matmul(x.t(),t...
https://stackoverflow.com/questions/65081845/
dropout(): argument 'input' (position 1) must be Tensor, not str when using Bert with Huggingface
My code was working fine and when I tried to run it today without changing anything I got the following error: dropout(): argument 'input' (position 1) must be Tensor, not str Would appreciate if help could be provided. Could be an issue with the data loader?
if you use HuggingFace, this information could be useful. I have same error and fix it with adding parameter return_dict=False in model class before dropout: outputs = model(**inputs, return_dict=False)
https://stackoverflow.com/questions/65082243/
PyTorch's DataParallel is only using one GPU
I'm trying to use two GPU's for training a model in PyTorch. I'm using torch.nn.DataParallel but for some reason nvidia-smi is saying that I'm only using one GPU. The code is something along the lines of: >>> import torch.nn as nn >>> model = SomeModel() >>> model = nn.DataParallel(model) &g...
You should be using nn.DataParallel(model, [0,1]) in order to use GPU #0 and GPU #1. The call model.to('cuda') afterwards is not necessary. You may be tempted to use nn.DataParallel(model.to('cuda'), [0,1]), but this appears unnecessary as well.
https://stackoverflow.com/questions/65084728/
Run Pytorch stacked model on Colab TPU
I am trying to run this my model on Colab Multi core TPU but I really don't know how to do it. I tried this tutorial notebook but I got some error and I can't fix it but I think there is maybe simpler wait for to do it. About my model: class BERTModel(nn.Module): def __init__(self,...): super().__init__() ...
I would work off the examples here: https://github.com/pytorch/xla/tree/master/contrib/colab Maybe start with a simpler model like this: https://github.com/pytorch/xla/blob/master/contrib/colab/mnist-training.ipynb In the pseudocode you shared, there is no reference to the torch_xla library, which is required to use Py...
https://stackoverflow.com/questions/65117817/
Does pytorch have function to calculate correlation coefficient matrix like numpy.corrcoef ()
Does pytorch have function to calculate correlation coefficient matrix like numpy.corrcoef ()
fastai (implemented heavily in pytorch) provides a suite of correlation coefficients including Pearson, Spearman, and Matthews (which probably is not what you want). fastai's documentation lists all of the stored commands here. You can use them via hooks during Pytorch training.
https://stackoverflow.com/questions/65120345/
The difference of loading model parameters between load_state_dict and nn.Parameter in pytorch
When I wanna assign part of pre-trained model parameters to another module defined in a new model of PyTorch, I got two different outputs using two different methods. The Network is defined as follows: class Net: def __init__(self): super(Net, self).__init__() self.resnet = torch.hub.load('pytorch/...
Finally, I find out where is the problem. During the pre-trained process, buffer parameters in BatchNorm2d Layer of ResNet18 model were changed even if we set require_grad of parameters False. Buffer parameters were calculated by the input data after model.train() was processed, and unchanged after model.eval(). There ...
https://stackoverflow.com/questions/65127800/
PyTorch mutiprocessing: Do I need to use Lock() when accessing a shared model?
I have some questions about using the torch.multiprocessing module. Let’s say I have a torch.nn.Module called model and I call model.share_memory() on it. What happens if two threads call the forward(), i.e. model(input) at the same time? Is it safe? Or should I use Lock mechanisms to be sure that model is not accessed...
It doesn't have to be safe, since they are running asynchronously not in parallel. Quoting from the docs, Using torch.multiprocessing, it is possible to train a model asynchronously, with parameters either shared all the time, or being periodically synchronized. In the first case, we recommend sending over the whole m...
https://stackoverflow.com/questions/65132527/
PyTorch's torch.nn.functional.interpolate behaving strangely
I'm having issues with PyTorch's tensor-resizing options. In the following code, x is a dataset of 888 64x64 RGB images of pokemon. xs is to be a dictionary of the same dataset at different resolutions. def load_data(): pokemon = [] for png in os.listdir("pokemon"): pokemon.append(imageio.imre...
I have solved my problem. I was unused to transitioning images from (Batch, Height, Width, Channels) to (Batch, Channels, Height, Width) for PyTorch. Replacing the reshape lines with np.moveaxis fixed the issue. Thanks, everyone, for your help.
https://stackoverflow.com/questions/65136845/
Should a data batch be moved to CPU and converted (from torch Tensor) to a numpy array when doing evaluation w.r.t. a metric during the training?
I am going through Andrew Ng’s tutorial from the CS230 Stanford course, and in every epoch of the training, evaluation is performed by calculating the metrics. But before calculating the metrics, they are sending the batches to CPU and converting them to numpy arrays (code here). # extract data from torch Variable, mov...
Correct me if I'm wrong. Sending back the data to the CPU allows to reduce the GPU load even though memory is replaced when entering the following loop cycle. Futhermore, I believe converting to numpy has the advantage of freeing memory since you are detaching your data from the calculation graph. You end up manipulati...
https://stackoverflow.com/questions/65179954/
How to Create Class Label for Mosaic Augmentation in Image Classification?
To create a class label in CutMix or MixUp type augmentation, we can use beta such as np.random.beta or scipy.stats.beta and do as follows for two labels: label = label_one*beta + (1-beta)*label_two But what if we've more than two images? In YoLo4, they've tried an interesting augmentation called Mosaic Augmentation f...
We already know that, in CutMix, λ is a float number from the beta distribution Beta(α,α). We have seen, when α=1, it performs best. Now, If we grant α==1 always, we can say that λ is sampled from the uniform distribution.. Simply we can say λ is just a floating-point number which value will be 0 to 1. So, only for 2 i...
https://stackoverflow.com/questions/65181294/
How to process TransformerEncoderLayer output in pytorch
I am trying to use bio-bert sentence embeddings for text classification of longer pieces of text. As it currently stands I standardize the number of sentences in each piece of text (some sentences are only comprised of ("[PAD]") and run each sentence through biobert to get sentence vectors as they do here: ht...
So the input and output shape of the transformer-encoder is batch-size, sequence-length, embedding-size). There are three possibilities to process the output of the transformer encoder (when not using the decoder). you take the mean of the sequence-length dimension: x = self.transformer_encoder(x) x = x.reshape(batch...
https://stackoverflow.com/questions/65190217/
Diagonal embedding of a batch of matrices in pytorch?
If you are given a collection of n x n matrices say m of them, is there a predefined function in pytorch that performs a diagonal embedding on all of these into a larger matrix of dimension nm x nm? To be concrete, what I am looking for is say you have two 2 x 2 identity matrices, then their diagonal embedding into a 4...
Your question doesn't specify how you get your m tensors. Let's say you have # channel first tensors a = torch.ones(4,2,2) or # a list of tensors a = [torch.ones(2,2) for _ in range(4)] then you can unpack that in block_diag: >>> torch.block_diag(*a) tensor([[1., 1., 0., 0., 0., 0., 0., 0.], [1., 1....
https://stackoverflow.com/questions/65191270/
Convert a simple cnn from keras to pytorch
Can anyone please help me to convert this model to PyTorch? I already tried to convert from Keras to PyTorch like this How can I convert this keras cnn model to pytorch version but training results were different. Thank you. input_3d = (1, 64, 96, 96) pool_3d = (2, 2, 2) model = Sequential() model.add(Convolution3D(8, ...
Your PyTorch equivalent of the Keras model would look like this: class CNN(nn.Module): def __init__(self, ): super(CNN, self).__init__() self.maxpool = nn.MaxPool3d((2, 2, 2)) self.conv1 = nn.Conv3d(in_channels=1, out_channels=8, kernel_size=3) self.conv2 = nn....
https://stackoverflow.com/questions/65192453/
RuntimeError: Found dtype Long but expected Float: When using criterion
I realized this question has been asked many times but I cannot find any solution which fixes my issue. I found this code online and tried to run it to understand how it actually works. I found the error is RuntimeError: Found dtype Long but expected Float. It happens at errD_real = criterion(output, label). I tried to...
I think I just found the solution is to change from label = torch.full((b_size,), real_label, device=device) to label = torch.full((b_size,), real_label, device=device, dtype=torch.float)
https://stackoverflow.com/questions/65192811/
Decaying the learning rate from the 100th epoch
Knowing that learning_rate = 0.0004 optimizer = torch.optim.Adam( model.parameters(), lr=learning_rate, betas=(0.5, 0.999) ) is there a way of decaying the learning rate from the 100th epoch? Is this a good practice: decayRate = 0.96 my_lr_scheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer=my_optimiz...
from torch.optim.lr_scheduler import MultiStepLR # reduce the learning rate by 0.1 after epoch 100 scheduler = MultiStepLR(optimizer, milestones=[100,], gamma=0.1) Please refer: MultiStepLR for more information.
https://stackoverflow.com/questions/65200452/
How can i add a Bi-LSTM layer on top of bert model?
I'm using pytorch and I'm using the base pretrained bert to classify sentences for hate speech. I want to implement a Bi-LSTM layer that takes as an input all outputs of the latest transformer encoder from the bert model as a new model (class that implements nn.Module), and i got confused with the nn.LSTM parameters. I...
You can do it as follows: from transformers import BertModel class CustomBERTModel(nn.Module): def __init__(self): super(CustomBERTModel, self).__init__() self.bert = BertModel.from_pretrained("bert-base-uncased") ### New layers: self.lstm = nn.LSTM(768, 256, batch_...
https://stackoverflow.com/questions/65205582/
How can i get all outputs of the last transformer encoder in bert pretrained model and not just the cls token output?
I'm using pytorch and this is the model from huggingface transformers link: from transformers import BertTokenizerFast, BertForSequenceClassification bert = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=int(data['class'].nuni...
Ideally, if you want to look into the outputs of all the layer, you should use BertModel and not BertForSequenceClassification. Because, BertForSequenceClassification is inherited from BertModel and adds a linear layer on top of the BERT model. from transformers import BertModel my_bert_model = BertModel.from_pretraine...
https://stackoverflow.com/questions/65217033/
What does this code in PyTorch do? How can I express it with tensorflow
I found a code that would solve my problem that looks like this: (self.conv_diag(input_tensor.diagonal(dim1=2, dim2=3))).diag_embed(dim1=2, dim2=3) While self.conv_diag is a layer I have defined before. As far as I understood it extracts the diagonal of a subtensor in the second and third dimension puts it into the la...
This is maybe what you are looking for: tf.linalg.diag( diagonal, name='diag', k=0, num_rows=-1, num_cols=-1, padding_value=0, align='RIGHT_LEFT' )
https://stackoverflow.com/questions/65224911/
Load csv and Image dataset in pytorch
I am doing image classification with PyTorch. I have a separate Images folder and train and test csv file with images ids and labels . I don’t have any an idea about how to combine those images and ID and converting into tensors. train.csv : contains all ID of Image like 4325.jpg, 2345.jpg,…so on and contains Labels l...
You can create custom dataset class by inherting pytorch's torch.utils.data.Dataset. The assumption for the following custom dataset class is csv file format is filename label 4325.jpg cat 2345.jpg dog All images are inside images folder. class CustomDataset(torch.utils.data.Dataset): def __ini...
https://stackoverflow.com/questions/65231299/
How do I specify and install the latest version of PyTorch via Conda in AWS Sagemaker?
I'm attempting to use a recent version of PyTorch (1.7.0) in a Conda environment on Sagemaker by specifying the package version in an environment.yml file. However, I'm getting a ResolvePackageNotFound error. Note that I'm just working in a Jupyter notebook with a kernel corresponding to this Conda environment. I'm not...
Sagemaker instances do not always have support for latest packages. Check this link for the list of supported images in Sagemaker instances.
https://stackoverflow.com/questions/65243886/
Load trained model on another machine - fastai, torch, huggingface
I am using fastai with pytorch to fine tune XLMRoberta from huggingface. I've trained the model and everything is fine on the machine where I trained it. But when I try to load the model on another machine I get OSError - Not Found - No such file or directory pointing to .cache/torch/transformers/. The issue is the pat...
I faced the same error. I had fine tuned XLMRoberta on downstream classification task with fastai version = 1.0.61. I'm loading the model inside docker. I'm not sure about why the path is embedded, but I found a workaround. Posting for future readers who might be looking for workaround as retraining is usually not poss...
https://stackoverflow.com/questions/65249790/
I got this error when installing PyTorch in Pycharm. I installed torchvision and torch successfully but the problem is in PyTorch
I try to install PyTorch in cmd to import it in pycharm project. it gives me numerous errors after Running setup.py install for PyTorch ... error. ERROR: Command errored out with exit status 1: command: 'c:\users\sarah\appdata\local\programs\python\python38\python.exe' -u -c 'import sys, setuptools, tokenize; sys....
The best way to install PyTorch is using pip or conda, with the commands provided on their website: https://pytorch.org/ This way you can choose which OS you are using, which version of CUDA (or no CUDA), and whether you are using conda or pip. Please notice that as of today (12/14/20), I tried installing PyTorch in a ...
https://stackoverflow.com/questions/65282529/
How to solve the failure of getting a python file from cpp extension of pytorch using setuptools?
I wanted to try a github project named deformable kernels, and followed the steps described in the README.md file: conda env create -f environment.yml cd deformable_kernels/ops/deform_kernel; pip install -e .; The structure of deformable_kernel/ops/deform_kernel is showed here: . csrc filter_sample_depthwise_cud...
Check your pip version. I've had the same error (when installing other things in dev mode with pip) and downgrading to pip version 20.0.2 worked. Unsure why, but I've seen other folks on the internet solve the problem similarly.
https://stackoverflow.com/questions/65283131/
Efficient numpy broadcasting not found
It may be an easy problem but I could not find any practical solution. My code has following code segment involving 3 nested for loops. The target is to create a specialized intensity matrix for my algorithms for both prediction and ground_truth image matrix as follows: for i in range (batch): for j in range ...
first lets clean up some notation; [:] does nothing But first what's the dimensions, mostly 3d? for i in range (batch): for j in range (img_width): for k in range (img_height): tensor = prediction[i,j,:] - prediction[i,k,:] # looks like a prediction[:,:,None]-prediction[:,None,:]; ...
https://stackoverflow.com/questions/65284619/
CNN forward function , AutoTuning the number of layers
class ConvolutionalNetwork(nn.Module): def __init__(self, in_features, trial): # we optimize the number of layers, hidden units and dropout ratio in each layer. n_layers = self.trial.suggest_int("n_layers", 1, 5) p = self.trial.suggest_uniform("dropout_1{}".format(i), 0, ...
there are a bunch of errors that make it hard to understand what you intended to do : Why would you build a nn.Sequential model in the __init__and not use it ? What is this return instruction in __init__ ?? The successive convolution layers you create do not have matching channel sizes (in_channels is always 1). The o...
https://stackoverflow.com/questions/65300793/
how to calculate mahalanobis distance in pytorch?
What is the most efficient way to calculate the mahalanobis distance: in pytorch?
Based on SciPy's implementation of the mahalanobis distance, you would do this in PyTorch. Assuming u and v are 1D and cov is the 2D covariance matrix. def mahalanobis(u, v, cov): delta = u - v m = torch.dot(delta, torch.matmul(torch.inverse(cov), delta)) return torch.sqrt(m) Note: scipy.spatial.distance.m...
https://stackoverflow.com/questions/65328887/
Loss is “nan” when fine-tuning HuggingFace NLI model (both RoBERTa/BART)
I'm using HuggingFace's Transformer's library and I’m trying to fine-tune a pre-trained NLI model (ynie/roberta-large-snli_mnli_fever_anli_R1_R2_R3-nli) on a dataset of around 276.000 hypothesis-premise pairs. I’m following the instructions from the docs here and here. I have the impression that the fine-tuning works (...
I received a good answer from the HuggingFace team on github. The issue was the model.half(), which has the advantage of increasing speed and reducing memory usage, but it also changes the model in a way that it produces the error. removing the model.half() solved the issue for me. For details, see https://github.com/h...
https://stackoverflow.com/questions/65332165/
What memory does Transformer Decoder Only use?
I've been reading a lot about transformers and self attention and have seen both BERT and GPT-2 are a newer version that only use an encoder transformer (BERT) and decoder transformer (GPT-2). I've been trying to build a decoder only model for myself for next sequence prediction but am confused by one thing. I'm using ...
After further investigation I believe I can now answer this myself. A decoder only transformer doesn't actually use any memory as there is no encoder-decoder self attention in it like there is in a encoder-decoder transformer. A decoder only transformer looks a lot like an encoder transformer only instead it uses a mas...
https://stackoverflow.com/questions/65341363/
Adam optimizer with warmup on PyTorch
In the paper Attention is all you need, under section 5.3, the authors suggested to increase the learning rate linearly and then decrease proportionally to the inverse square root of steps. How do we implement this in PyTorch with Adam optimizer? Preferably without additional packages.
PyTorch provides learning-rate-schedulers for implementing various methods of adjusting the learning rate during the training process. Some simple LR-schedulers are are already implemented and can be found here: https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate In your special case you can - just l...
https://stackoverflow.com/questions/65343377/
How to store wrong predictions during evaluation on the CNN
During evaluation, I want to store unique ids that are wrongly predicted to do some more processing. It is a multiclass prediction problem Here is the code during the evaluation: outputs = model(imgs) loss = criterion(outputs, targets) # Prediction error val_loss += loss.item() predicted = torch.argmax(outputs, d...
The question contained a tensorflow tag, so I was preparing an answer. After completing my write up, I've found that this tag is removed. However, I believe my answer can give insight into this general question of whether they're using tf or pytorch. Data (x_train, y_train), (x_test, y_test) = tf.keras.datasets.cifar1...
https://stackoverflow.com/questions/65345897/
How to set hydra's parameter HYDRA_FULL_ERROR?
When I use hydra in a python pytorch project, the operation result prompt “Set the environment variable HYDRA_FULL_ERROR=1 for a complete stack trace.” But i don't konw how to set it.
You set an environment variable in the shell. For a specific run: $ HYDRA_FULL_ERROR=1 python foo.py Or for all runs in this shell session: $ export HYDRA_FULL_ERROR=1 $ python foo.py However, you shouldn't normally need to set it. This is more of a debugging backdoor in case of issues with Hydra itself. If you hit a...
https://stackoverflow.com/questions/65376556/
Torch gather middle dimension
Let a be a (n, d, l) tensor. Let indices be a (n, 1) tensor, containing indices. I want to gather from a in the middle dimension tensors from indices given by indices. The resulting tensor would therefore be of shape (n, l). n = 3 d = 2 l = 3 a = tensor([[[ 0, 1, 2], [ 3, 4, 5]], [[ 6, 7...
You can create the indices manually. The indices tensor has to be flattened if it has the shape of your example data. a[torch.arange(len(a)),indices.view(-1)] # equal to a[[0,1,2],[0,1,0]] Out: tensor([[ 0, 1, 2], [ 9, 10, 11], [12, 13, 14]])
https://stackoverflow.com/questions/65378968/
Why is my dynamic pytorch model definition not complete?
I tried to create a custom pytorch model class in a way that would allow variable number of hidden layers. Everything seems to "work" in the code, however even if I set 10 hidden layers, none of them show up in the print out of the model definition. I am wondering why this is happening? I can see obviously it...
PyTorch cannot see your list object. You need to use nn.ModuleList: self.hidden_layers = nn.ModuleList([nn.Linear(hidden_dim, hidden_dim).to(device) for _ in range(layer_dim)])
https://stackoverflow.com/questions/65380984/
How to convert a yolo darknet format into .csv file
I have a few annotations that is originally in YOLO format. I need to convert it into yolo csv format in order to train with my transformers model. Sample .csv file I need: Sample annotation file in CSV format The csv attributes include: image_id, width, height and coordinates of the image's bounding box. Any help woul...
first of all i should say there is no straight way to convert those format into csv. you should read files and parse their data. Step 1: import libraries we need to read txt files ( yolo labels ) from a directory and save them into csv. so we need these libraries : import os import glob import pandas as pd import numpy...
https://stackoverflow.com/questions/65381312/
"MisconfigurationError: No TPU devices were found" even when TPU is connected in PyTorch Lightning
Have been frustrated over the past few hours over a problem, though It's likely its a problem I started myself hah. I'm trying to connect to the TPU in Colab. I'm pretty sure I've gotten all the import stuff down. My code is here. I'm not completely set on everything, so the entire document isn't functional, but you sh...
I suffered the same problem, and these steps solved the problem. Follow the PyTorch-Lightning docs: TPU SUPPORT Add another notebook cell: %%capture !curl https://raw.githubusercontent.com/pytorch/xla/master/contrib/scripts/env-setup.py -o pytorch-xla-env-setup.py > /dev/null !python pytorch-xla-env-setup.py --ver...
https://stackoverflow.com/questions/65387967/
PyTorch LinearLayer+BatchNorm1d with a 3D input
I would like to apply a BatchNorm1d after a Linear. My input is a 3D multivariate time series of shape [batch_size, n_variables, timesteps]. The Linear performs the linear transformation on the third dimension so that the new shape is [batch_size, n_variables, LinearLayer_out_features]. My problem occurs with the Batch...
Why not transpose the input to BatchNorm1d and then transpose it back? m=Linear(.....) m=torch.transpose(BatchNorm1D(torch.transpose(m,1,2)),1,2) This doesn't create a copy of your tensor. https://pytorch.org/docs/stable/generated/torch.transpose.html
https://stackoverflow.com/questions/65398540/
Running two different independent PyTorch programs on a single GPU
I have a single NVIDIA GPU which has a memory of 16GB. I have to run two different (and independent; meaning, two different problems: one is a vision type task, another is NLP task) Python programs. The codes are written using PyTorch and both the codes can use GPU. I have tested that program 1 takes roughly 5GB of GPU...
I do not know the details of how this works, but I can tell from experience that both programs will run well (as long as they do not need more than 16GB of RAM when combined), and execution times should stay roughly the same. However, computer vision usually requires a lot of IO (mostly reading images), if the other ta...
https://stackoverflow.com/questions/65399566/
Tweak positional encodings shape (DETR model) to support batchsize > 1
Referencing from this notebook, and would like to scale this to support batch size > 1, as it state on in the comments Only batch size 1 supported.. I'm having trouble tweaking the pos statement inside the forward(). How to go about doing this? Any tips will be very helpful too. This is the original code taken from ...
Have a look at their code on github: https://github.com/facebookresearch/detr The code there allows for arbitrary batch sizes, see e.g. the Evaluation section in their Readme file.
https://stackoverflow.com/questions/65423938/
AssertionError: No inf checks were recorded for this optimizer in Pytorch's AutomaticMixedPrecision
I'm using AutomaticMixedPrecision feature of PyTorch to train a network with smaller footprint and precision. At a certain point some embeddings from the network have NaNs in their tensors, so I'd like to replace those with 0s in order to perform online hard negative samples mining. However, after replacing the NaNs in...
could you show us your full code. Generally it is advisable to just skip the step (batch) if it has NaNs. Also take a look at torch.nan_to_num.
https://stackoverflow.com/questions/65428216/
Replacing a max pooling layer with an average pooling layer on a VGG model
I'm following this article and I try to implement this function: def replace_max_pooling(model): ''' The function replaces max pooling layers with average pooling layers with the following properties: kernel_size=2, stride=2, padding=0. ''' for layer in model.layers: if layer is max pooling: replace ...
The VGG model provided by Torchvision contains three components: the features sub-module, avgpool (the adaptive average pool), and the classifier. You need to be looking into the head of the network, where the convolution and pool layers are located: features. You can loop over the layers of a nn.Module with named_chil...
https://stackoverflow.com/questions/65429057/
What is hp_metric in TensorBoard and how to get rid of it?
I am new to Tensorboard. I am using fairly simple code running an experiment, and this is the output: I don't remember asking for a hp_metric graph, yet here it is. What is it and how do I get rid of it? Full code to reproduce, using Pytorch Lightning (not that I think anyone should have to reproduce this to answer):...
It's the default setting of tensorboard in pytorch lightning. You can set default_hp_metric to false to get rid of this metric. TensorBoardLogger(save_dir='tb_logs', name='VAEFC', default_hp_metric=False) The hp_metric helps you track the model performance across different hyperparameters. You can check it at hparams ...
https://stackoverflow.com/questions/65450707/
How to draw a scatter plot in Tensorboard Pytorch?
Assuming I want a generic scatter plot drawn in TensorBoard that draws the 1st batch[:, 0], batch[:, 1] of every epoch. How can that be done in TensorBoard? An old similar question (2017 january) has a workaround, but I hope we now (2020 december) have the technology for a real solution. Not enough is my attempt: if se...
If I understand your question right, you could use add_images, add_figure to add image or figure to tensorboard(docs). Sample code: from torch.utils.tensorboard import SummaryWriter import numpy as np import matplotlib.pyplot as plt # create summary writer writer = SummaryWriter('lightning_logs') # write dummy image ...
https://stackoverflow.com/questions/65451949/
How to cache big data in memory (efficiently) in complex variables across executions of Python scripts?
I am trying to call (from Java Spring beans) Python Pytorch scripts that contains trained neural networks for the use: my Pytorch neural networks are neural functions that accepts state, encodes it and returns the action, decodes all this is according to learned/trained policy. So - each time when I am trying to invoke...
If I understand your use case correctly, what you need is a model server that keeps the model loaded and ideally also handles any exceptions from incorrect data. One rather straightforward way to transform your inference script into a tensorflow-serving-like callable service is the python library flask. Another way see...
https://stackoverflow.com/questions/65458445/
tensor type attributes in bert model returned as string
I am new to nlp and i want to build a bert model for sentiment Analysis so i am following this tuto https://curiousily.com/posts/sentiment-analysis-with-bert-and-hugging-face-using-pytorch-and-python/ but i am getting the error bellow bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME) last_hidden_state, po...
it seems there was A couple of changes were introduced when the switch from version 3 to version 4 was done in hugging face and can be solved like below bert_model = BertModel.from_pretrained(PRE_TRAINED_MODEL_NAME, return_dict=False)
https://stackoverflow.com/questions/65461593/
What are the numbers in torch.transforms.normalize and how to select them?
I am following some tutorials and I keep seeing different numbers that seem quite arbitrary to me in the transforms section namely, transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) or transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0....
Normalize in pytorch context subtracts from each instance (MNIST image in your case) the mean (the first number) and divides by the standard deviation (second number). This takes place for each channel separately, meaning in mnist you only need 2 numbers because images are grayscale, but on let's say cifar10 which has ...
https://stackoverflow.com/questions/65467621/
Convert image to tensor with range [0,255] instead of [0,1]?
I'm trying to use transforms.compose to convert my images into normalized images with a range of [0,255] instead of normalizing it as [0,1] for training my model. How do I make my code do this. Currently it normalizes the images from [0,1]. How would i just multiply this up to 255 to make it 0-255 or is it not that sim...
Ideally you would normalize values between [0, 1] then standardize by calculating the mean and std of your whole training set and apply it to all datasets (training, validation and test set). The following is essentially a x in [x_min, x_max] -> x' in [0, 1] mapping: x_min, x_max = x.min(), x.max() x = (x - x_min) /...
https://stackoverflow.com/questions/65469814/
How do I create a DataLoaders using rows of a DataFrame?
I am trying to create a model that will predict the next row of values. There are 7 columns, but I am only using the first 6. I figure that if I pass in the datetimes in column 7 to the model, that will guarantee overfitting. Here is a screenshot of the DataFrame: I am using an arbitrary number of rows, 100 in this ca...
Create your custom dataset like this: class TimeSeriesDataset: def __init__(self, df, input_features: list, output_features: list, lookback=99, lookahead=1): self.df = df self.lookback = lookback self.lookahead = lookahead def __len__(self): return len(self.df)...
https://stackoverflow.com/questions/65470428/
Calculate alpha values with torch mean?
I'm trying to calculate the alpha values as explained here. I have as argument a tensor with shape (1, 512, 14, 14). To calculate alpha values I need to calculate the average of all dimensions except the channel dimension, so the output will have the shape (1, k, 1, 1) which is essentialy (k,). How can I do this in PyT...
You could permute the first and second axis to keep the channel dimension on dim=0, then flatten all other dimensions, and lastly, take the mean on that new axis: x.permute(1, 0, 2, 3).flatten(start_dim=1).mean(dim=1) Here are the shapes, step by step: >>> x.permute(1, 0, 2, 3).shape (512, 1, 14, 14) >&gt...
https://stackoverflow.com/questions/65471913/
Pytorch tensor dimension multiplication
I'm trying to implement the grad-camm algorithm: https://arxiv.org/pdf/1610.02391.pdf My arguments are: activations: Tensor with shape torch.Size([1, 512, 14, 14]) alpha values : Tensor with shape torch.Size([512]) I want to multiply each activation (in dimension index 1 (sized 512)) in each corresponding alpha value: ...
Assuming the desired output is of shape (1, 512, 14, 14). You can achieve this with torch.einsum: torch.einsum('nchw,c->nchw', x, y) Or with a simple dot product, but you will first need to add a couple of additional dimensions on y: x*y[None, :, None, None] Here's an example with x.shape = (1, 4, 2, 2) and y = (...
https://stackoverflow.com/questions/65480530/
ImportError: cannot import name 'AdultDataset' from 'dataset'
Please I am working on AdultDataset for a classification task I found out: from dataset import AdultDataset is giving the error below: ImportError: cannot import name 'AdultDataset' from 'dataset' Import Relevant Libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.preprocessin...
I believe your problem can be fixed like this: from aif360.datasets import AdultDataset Maybe you are using an old guide?
https://stackoverflow.com/questions/65527107/
Pytorch torch.load ModuleNotFoundError: No module named 'utils'
I'm trying to load a pretrained model with torch.load. I get the following error: ModuleNotFoundError: No module named 'utils' I've checked that the path I am using is correct by opening it from the command line. What could be causing this? Here's my code: import torch import sys PATH = './gan.pth' model = torch.loa...
EDIT this answer doesn't provide the answer for the question but addresses another issue in the given code the .pth file just stores the parameters of a model, not the model itself. When you want to load a model you will need the .pt/-h file and the python code of your model class. Then you can load it like this: # yo...
https://stackoverflow.com/questions/65538179/
How do I use a .pickle file to predict an image?
I have trained a CNN model in PyTorch to detect skin diseases in 6 different classes. My model came out with an accuracy of 92% and I saved it in a .pickle file. I wish to use this model for predictions but I don't know how to do so. If anyone can aid me in the necessary steps, I will be grateful. I have tried using St...
I'll show you how to save and load pytorch model parameters properly (you should use the .pt extension): To save the model do this (once every epoch or after training): torch.save(model.state_dict(), "your/path/model_file.pt") All the model parameters are now loaded into "your/path/model_file.pt". ...
https://stackoverflow.com/questions/65540507/
Pytorch : RuntimeError: mat1 dim 1 must match mat2 dim 0
using resnet50 model. Customize the last layer and it showing runtime error..Im new to PyTorch and I keep getting the error mat1 dim1 must match mat1 dim0 this is my code for the network from torchvision import models model = models.resnet50(pretrained=True) for param in model.parameters(): param.requires_grad = F...
This error comes from the nn.Linear you changed. As you recall, nn.Linear computes a simple matrix dot product, and therefore the input dimension coming from the previous layer must equal the weight matrix shape (you set it to 2048). my guess is that since you removed the model.avgpool layer, you now have more than 204...
https://stackoverflow.com/questions/65543055/
create tensor in specific indexes without loops
I have a tensor t1 (with shape (2*n, 2*n), and I need to create tensor t2 (with shape (2*n)) with the values of t1 at [i,(i+n) mod 2n] for each row i. For example, given: t1 = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8], [9 ,10,11,12], [13,14,15,16]]) Here n=2. t2 ...
You could create the list of indices beforehand with a loop then pick the values from t1 with torch.gather without having to loop over them yourself: >>> index = torch.tensor([[(i+n)%(2*n)] for i in range(2*n)]) >>> torch.gather(t1, 1, index).flatten() tensor([ 3, 8, 9, 14]) Alternatively, you can...
https://stackoverflow.com/questions/65544574/
what does offsets mean in pytorch nn.EmbeddingBag?
I know offsets meaning when it has two numbers, but what does it mean when more than two numbers,for example: weight = torch.FloatTensor([[1, 2, 3], [4, 5, 6]]) embedding_sum = nn.EmbeddingBag.from_pretrained(weight, mode='sum') print(list(embedding_sum.parameters())) input = torch.LongTensor([0,1]) offsets = torch.Lon...
import torch import torch.nn as nn weight = torch.FloatTensor([[1, 2, 3], [4, 5, 6]]) embedding_sum = nn.EmbeddingBag.from_pretrained(weight, mode='sum') print(embedding_sum.weight) """ output Parameter containing: tensor([[1., 2., 3.], [4., 5., 6.]]) """ input = torch.LongTenso...
https://stackoverflow.com/questions/65547335/
How do I to average irregularly spaced x & y coordinate tensor into a grid with a specific cell size?
I have an algorithm that generates a tensor of irregularly spaced x and y coordinates (ex: torch.size([3600, 2])), and I need to average the points into grid cells of a specific size (ex: 8 by 8). The resulting grid needs to be either an array or tensor. It's not required, but I would also like to be able to determine ...
I think this code would give you a good starting point. def grid_torch(x_coords, y_coords, grid_size=(8,8), x_extent=(0., 1.), y_extent=(0., 1.)): # This part converts coordinates to bin numbers (like (2,5), (7,7) etc) x_bin = (((x_coords - x_extent[0]) / (x_extent[1] - x_extent[0])) * grid_size[0]).int() y...
https://stackoverflow.com/questions/65551875/
PyTorch mini batch, when to call optimizer.zero_grad()
When we use mini batch, should I call optimizer.zero_grad() before starting the iteration? Or inside the iteration? I think the second code is correct, but I'm not sure. nb_epochs = 20 for epoch in range(nb_epochs + 1): optimizer.zero_grad() # THIS PART!! for batch_idx, samples in enumerate(dataloader):...
Gradients accumulates by default everytime you call .backward() on the computational graph. On the first snippet, you are resetting the gradients once per epoch so all gradients will accumulate their values over time. With a total of len(dataloader) accumulated gradients, only resseting the gradients when the next epoc...
https://stackoverflow.com/questions/65570250/
Torch throws a RuntimeError: element 0 of tensors does not require grad... but can't find where computational graph is severed
I am getting the above error: RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn I looked this up and it looks like the computational graph is not connected for some reason. However, I cannot find the location where the graph is severed. My code is a reproduction of the arjovsky WGAN:...
You most certainly need to add require_grad=True on one. You could define it as: one = torch.tensor([1], dtype=torch.float16, requires_grad=True)
https://stackoverflow.com/questions/65570549/
Tensorboard: All experiments were written as one (without provided tags)
I wanted to compare several runs that I did in the loop creating new SummaryWriter instances like this: for experiment_name in experiments: logger = SummaryWriter(self._log_path, comment=experiment_name) ... for epoch in range(5): ... logger.add_scalar("Epoch Loss", loss, epoch) ...
The events files that I have in the one folder should be in the separate and the folder name will be displayed as an experiment name. Also found the important note in the SummaryWriter documentation: comment (string): Comment log_dir suffix appended to the default log_dir. If log_dir is assigned, this argument has no ...
https://stackoverflow.com/questions/65575183/
torchtext ImportError in colab
I am trying to run this tutorial in colab. However, when I try to import a bunch of modules: import io import torch from torchtext.utils import download_from_url from torchtext.data.utils import get_tokenizer from torchtext.vocab import build_vocab_from_iterator It gives me the errors for extract_archive and build_voc...
You need to upgrade torchtext first !pip install -U torchtext==0.8.0 Currently, version 0.8.0 works with torch 1.7.0 (no need to upgrade torch, torchvision) Update (sep 2021) Currently, torchtext is already 0.10.0 and you don't need to upgrade anything.
https://stackoverflow.com/questions/65575871/
Pytorch transformer forward function masks implementation for decoder forward function
I am trying to use and learn PyTorch Transformer with DeepMind math dataset. I have tokenized (char not word) sequence that is fed into model. Models forward function is doing once forward for encoder and multiple forwards for decoder (till all batch outputs reach token, this is still TODO). I am struggling with Trans...
It looks like I have messed dimensions order (as Transformer does not have batch first option). Corrected code is below: class MyTransformerModel(nn.Module): def __init__(self, d_model = 512, vocab_length = 30, sequence_length = 512, num_encoder_layers = 3, num_decoder_layers = 2, num_hidden_dimension = 256, feed_forwa...
https://stackoverflow.com/questions/65588829/
What should be output size of image classifier model?
I'm performing an image classification task . Images are labeled as 0 1 2. Should be the size of the last linear layer in the model output be 3 or 1 ? In general, for a 3-class operation, the output is set to 3, and as a result of these three, the maximum probability is returned. But I saw that the last layer is set as...
To perform classification into c classes (c = 3 in your example) you need to predict the probability of each class, therefore you need to output a c-dim output. Usually you do not explicitly apply softmax to the "raw predictions" (aka "logits") - the loss function usually does that for you in a more...
https://stackoverflow.com/questions/65592554/
Pytorch lightning Datamodule override warning: Signature of method '.setup()' does not match signature of base method in class 'LightningDataModule'
The following is a working Pytorch Lightning DataModule. import os from pytorch_lightning import LightningDataModule import torchvision.datasets as datasets from torchvision.transforms import transforms import torch from torch.utils.data import DataLoader from Testing.Research.config.paths import mnist_data_download_fo...
It seems that simple copy-paste the parent method signature solves this issue: def setup(self, stage: Optional[str] = None) -> None: ...
https://stackoverflow.com/questions/65594849/