instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Saving a trained Detectron2 model and making predictions on a single image
I am new to detectron2 and this is my first project. After reading the docs and using the tutorials as a guide, I trained my model on the custom dataset and performed the evaluation. I would now like to make predictions on images I receive via an API by loading this saved model. I could not find any reading materials t...
for a single image, create a list of data. Put image path in the file_name as below: test_data = [{'file_name': '.../image_1jpg', 'image_id': 10}] Then do run the following: from detectron2.config import get_cfg from detectron2.engine import DefaultPredictor from detectron2.data import MetadataCatalog fr...
https://stackoverflow.com/questions/68343961/
module 'torch' has no attribute 'nan_to_num'
I am using 1.7.1 version of Pytorch on Ubuntu, and I try to do the following : x = torch.tensor([float('nan'), float('inf'), -float('inf'), 3.14]) torch.nan_to_num(x) but I am getting this error : AttributeError: module 'torch' has no attribute 'nan_to_num' But it does exist in the documentation since I just copied th...
nan_to_num was introduced in PyTorch 1.8. You will need to update your torch package to access it: pip install --upgrade torch
https://stackoverflow.com/questions/68359151/
pytorch loss function for regression model with a vector of values
I'm training a CNN architecture to solve a regression problem using PyTorch where my output is a tensor of 25 values. The input/target tensor could be either all zeros or a gaussian distribution with a sigma value of 2. An example of a 4-sample batch is as this one: [[0.13534, 0.32465, 0.60653, 0.8825, 1.0000, 0.88250,...
Your values do not seem widely different in scale so an MSELoss seems like it would work fine. Your model could be collapsing because of the many zeros in your target. You can always try torch.nn.L1Loss() (but I do not expect it to be much better than torch.nn.MSELoss()) I suggest that you instead try to predict the ga...
https://stackoverflow.com/questions/68370248/
First argument error in pytorch.loads() function when working with Emotic demo
Basically, I'm creating an emotion recognition application, and I'm using Emotic's image dataset. They have their own premade program and trained model for a demo (The colab link below) but for some reason the third cell under I. Prepare places pretrained model is encountering the error: the first argument must be cal...
I am the author of this repository. I had fixed this issue back in August 2021. The issue is caused due to some changes in the Python Pickle module in the python 3.7 version. The code used to work properly in the Python 3.6 version. You can try the Colab_train_emotic.ipynb file.
https://stackoverflow.com/questions/68370899/
Facing issue: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 918: ordinal not in range(128) while trying to load a Pytorch model
I am trying to load a pre-trained Pytorch model but getting an error as shown below: model = torch.load('a.pth') File "/home/ubuntu/env/lib/python3.6/site-packages/torch/serialization.py", line 267, in load return _load(f, map_location, pickle_module) File "/home/ubuntu/env/lib/python3.6/site-pac...
From documentation: By default, we decode byte strings as utf-8. This is to avoid a common error case UnicodeDecodeError: 'ascii' codec can't decode byte 0x... when loading files saved by Python 2 in Python 3. If this default is incorrect, you may use an extra encoding keyword argument to specify how these objects sho...
https://stackoverflow.com/questions/68372576/
Are there any difference between Y and *Y, where Y is a list used as input argument?
I was using the torch.tensor.repeat() x = torch.tensor([[1, 2, 3], [4, 5, 6]]) period = x.size(1) repeats = [1,2] result = x.repeat(*repeats) the result is tensor([[1, 2, 3, 1, 2, 3], [4, 5, 6, 4, 5, 6]]) if I get result as follows result = x.repeat(repeats) the result is the same tensor([[1, 2, 3, 1, 2, 3], ...
Kinda. If repeats is a (list or tuple) of ints, then it is equivalent. But in general the rule appears to be: If the first argument is a list or tuple, take that as repeats. Ignore all other arguments. Otherwise, take the full *args as repeats So if your repeats is something weird like repeats=((1,2),(3,4)), then a.r...
https://stackoverflow.com/questions/68387274/
Plot loss and accuracy over each epoch for both training and test datasets
I am training that model to classify 3 classes (0,1,2). I am using cross validation for 2 fold, I am using pytorch, I would like to plot the accuracy and loss function for training and test dataset over the number epochs on the same plot. I do know how to do that . especially I just evaluate the test once I finish trai...
You could use Tensorboard that is built especially for that, here is the doc for pytorch : https://pytorch.org/docs/stable/tensorboard.html So in your case when you are printing the result, you can just do a writer.add_scalar('accuracy/train', torch.sum(outputs == targets) / float(outputs.shape[0]), n_iter) EDIT : ad...
https://stackoverflow.com/questions/68389962/
FileNotFoundError: [Errno 2] No such file or directory: '.data/multi30k/train.fr'
I'm trying to load Multi30k torchtext dataset using google colab. When I load the .de it works fine, but as soon as I changed from .de I get this error: FileNotFoundError: [Errno 2] No such file or directory: '.data/multi30k/train.fr' This is how I loaded the .de and it worked: train_data, valid_data, test_data = data...
It's because there is no train.fr file in the dataset itself. If you list down what pytorch downloaded, $ !ls -al .data/multi30k total 5.4M drwxr-xr-x 2 root root 4.0K Jul 15 14:26 . drwxr-xr-x 3 root root 4.0K Jul 15 14:26 .. -rw-r--r-- 1 root root 65K Jul 15 14:26 mmt_task1_test2016.tar.gz -rw-rw-r-- 1 1000 1000 69...
https://stackoverflow.com/questions/68391900/
"ValueError: Incompatible Language version 13. Must not be between 9 and 12" with Google Colab
I am trying to build a deep learning model with transformer model architecture. In that case when I am trying to cleaning the dataset following error occurred. I am using Pytorch and google colab for that case & trying to clean Java methods and comment dataset. Tested Code import re from fast_trees.cor...
The fast-trees library uses the tree-sitter library and since they recommended using the 0.2.0 version of tree-sitter in order to use fast-trees. Although downgrade the tree-sitter to the 0.2.0 version will not be resolved your problem. I also tried out it by downgrading it. So, without investing time to figure out the...
https://stackoverflow.com/questions/68393698/
RuntimeError: mat1 and mat2 shapes cannot be multiplied (5376x28 and 784x512)
Basic Network class Baseline(nn.Module): def __init__(self): super().__init__() # 5 Hidden Layer Network self.fc1 = nn.Linear(28 * 28, 512) self.fc2 = nn.Linear(512, 256) self.fc3 = nn.Linear(256, 128) self.fc4 = nn.Linear(128, 64) self.fc5 = nn.Linear(64, 3) ...
I see one issue in the code. Linear layers do not accept matrices with a 4d shape that you passed into the model. In order to pass data with torch.Size([64, 3, 28, 28]) through a nn.Linear() layers like you have in your model. You need to flatten the tensor in your forward function like: # New code x = x.view(x.size(0)...
https://stackoverflow.com/questions/68398721/
Convert keras model to pytorch
Is there an easy way to convert a model like this from keras to pytorch? I have the code in keras as following: from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense, Dropout from tensorflow.keras.optimizers import Adam from tensorflow.keras.regularizers import l2 state_dim = 10 architectur...
Here is my best attempt: state_dim = 10 architecture = (256, 256) # units per layer learning_rate = 0.0001 # learning rate l2_reg = 0.00000001 # L2 regularization trainable = True num_actions = 3 import torch from torch import nn class CustomModel(nn.Module): def __init__(self): super().__init...
https://stackoverflow.com/questions/68413480/
How to make a custom torchvision transform?
I have a function that changes image pixels with 20% chance, but not sure how to make it work in transforms.Compose([]). Please help! def random_t(img): im = Image.open(img) pixelMap = im.load() pixelMap_list = [] for i in range(im.size[0]): for j in range(im.size[1]): randNum = ran...
You need to do your operations on img and then return it. For a good example of how to create custom transforms just check out how the normal torchvision transforms are created like over here: This is the github where torchvision.transforms like transforms.Resize(), transforms.ToTensor(), transforms.RandomHorizontalFli...
https://stackoverflow.com/questions/68415926/
Imorting zero_gradients from torch.autograd.gradcheck
I want to replicate the code here, and I get the following error while running in Google Colab? ImportError: cannot import name 'zero_gradients' from 'torch.autograd.gradcheck' (/usr/local/lib/python3.7/dist-packages/torch/autograd/gradcheck.py) Can someone help me with how to solve this?
This seems like it's using a very old version of PyTorch, the function itself is not available anymore. However, if you look at this commit, you will see the implementation of zero_gradients. What it does is simply zero out the gradient of the input: def zero_gradients(i): for t in iter_gradients(i): t.zero...
https://stackoverflow.com/questions/68419612/
PyTorch: Image not displaying properly
I have the following code portion: dataset = trainDataset() train_loader = DataLoader(dataset,batch_size=1,shuffle=True) device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') images = [] image_labels = [] for i, data in enumerate(train_loader,0): inputs, labels = data inputs, labels = input...
In pytorch you usually represent pictures with tensors of shape (channels, height, width) You then seem to reshape it to what you expect would be (height, width, channels) Note that these tensors or arrays are actually stored as 1d "array", and the multiple dimensions just come from defining strides (check ...
https://stackoverflow.com/questions/68424784/
How does pytorch perform the reverse-differentiation given an indexed version of a tensor in the feedforward step?
Some of this code was adapted from the book Deep learning with Pytorch Script: Linear regression (trying to predict t_c given t_u) t_c = torch.tensor([0.5, 14.0, 15.0, 28.0, 11.0, 8.0, 3.0, -4.0, 6.0, 13.0, 21.0]) t_u = torch.tensor([35.7, 55.9, 58.2, 81.9, 56.3, 48.9, 33.9, 21.8...
The main idea here is that the indexing operation returns a new view of the tensor. If you are not using in-place operations (+=, -=, etc.), the "view" thing does not really matter and you can consider it as just another tensor. In that case, the indexing operation is no different from other operations like a...
https://stackoverflow.com/questions/68425540/
How to disable tqdm's progressbar and keep only the text info in Pytorch Lightning (or in tqdm in general)
I am working on Pytorchlightning and tqdm's progressbar is very buggy, it keep resizing back and forth from short to long, making reading the logging text so unpleasant, I realized that the progressbar is not really necessary and would like to keep only the info about the current epoch, current batch, accuracy, loss, e...
The tqdm way to disable the "meter" (while retaining display of stats) is to set ncols=0 and dynamic_ncols=False (see tqdm documentation). The way to customize the default progress bar behavior in pytorch_lightning is to pass a custom ProgressBar in as a callback when building the Trainer. Putting the two tog...
https://stackoverflow.com/questions/68427465/
Pytorch Custom Loss Function with If Statement
I am trying to create a custom loss function in Pytorch that evaluates each element of a tensor with an if statement and acts accordingly. def my_loss(outputs,targets,fin_val): if (outputs.detach()-fin_val.detach())*(targets.detach()-fin_val.detach())<0: loss=3*(outputs-targets)**2 else: loss...
You are getting this error because the condition you are passing to the if statement is not a boolean but a tensor of booleans. Just check what's the nature of (outputs.detach()-fin_val.detach())*(targets.detach()-fin_val.detach())<0, it is a tensor! What you should be looking to do instead is handling this in vecto...
https://stackoverflow.com/questions/68430520/
How to print the adjusting learning rate in Pytorch?
While I use torch.optim.Adam and exponential decay_lr in my PPO algorithm: self.optimizer = torch.optim.Adam([ {'params': self.policy.actor.parameters(), 'lr': lr_actor}, {'params': self.policy.critic.parameters(), 'lr': lr_critic} ]) self.scheduler = torch.optim.lr_sched...
You can get the learning rate like this: self.optimizer.param_groups[0]["lr"]
https://stackoverflow.com/questions/68442914/
Problem with variable when working with python
Hello everyone im trying to work with the Digit tactile sensor with the PyTouch library so when i try to run the contact area code example i get this error DigitSensor with SensorDataSources.RAW data source Traceback (most recent call last): File "contactarea.py", line 31, in <module> extract_surface_co...
Seems like the condition len(contour) > contour_threshold inside _compute_contact_area is never matched so the variable poly is never defined. I recommend trying to print the length of contour before the if statement to check the values. If you want it to work even if the condition isn't matched just declare the var...
https://stackoverflow.com/questions/68453045/
Key already registered with the same priority: GroupSpatialSoftmax
I get this error: "Key already registered with the same priority: GroupSpatialSoftmax" when i run: import torch Though I've installed the pytorch package through the pycharm settings > python interpreter. Does anyone know how can I solve it? Thanks
Solved it myself! I uninstalled the pytorch package and re-installed it so now it works
https://stackoverflow.com/questions/68468122/
Defining Metrics on SageMaker to CloudWatch
From AWS Sagemaker Documentation, In order to track metrics in cloudwatch for custom ml algorithms (non-builtin), I read that I have to define my estimaotr as below. But I am not sure how to alter my training script so that the metric definitions declared inside my estimators can pick up these values. estimator = ...
You have to define a regex to capture that pattern, try with this: {'Name': 'Average training loss', 'Regex': 'Average training loss = ([0-9\.]+)'} You can try the regex in tool like this and see what happens.
https://stackoverflow.com/questions/68470626/
PyTorch BatchNorm2d Calculation
I am trying to understand the mechanics of PyTorch BatchNorm2d through calculation. My example code: import torch from torch import nn torch.manual_seed(123) a = torch.rand(3,2,3,3) print(a) print(nn.BatchNorm2d(2)(a)) #print(a[:,0,:,:]) mean_by_plane_feature = torch.mean(a,dim=0) std_by_plane_feature = torch.std(a,...
This is the implementation of BatchNorm2d in pytorch (source1, source2). Using this, you can verify the operations you performed. class MyBatchNorm2d(nn.BatchNorm2d): def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, track_running_stats=True): super(MyBatchNorm2d, self)....
https://stackoverflow.com/questions/68478856/
CUDA out of memory error, cannot reduce batch size
I want to run some experiments on my GPU device, but I get this error: RuntimeError: CUDA out of memory. Tried to allocate 3.63 GiB (GPU 0; 15.90 GiB total capacity; 13.65 GiB already allocated; 1.57 GiB free; 13.68 GiB reserved in total by PyTorch) I read about possible solutions here, and the common solution is thi...
As long as a single sample can fit into GPU memory, you do not have to reduce the effective batch size: you can do gradient accumulation. Instead of updating the weights after every iteration (based on gradients computed from a too-small mini-batch) you can accumulate the gradients for several mini-batches and only whe...
https://stackoverflow.com/questions/68479235/
How can I separate the last layer of deep network in pytorch?
My deep network is: self.actor = nn.Sequential( nn.Linear(state_dim, 256), nn.Softplus(), nn.Linear(256, 256), nn.Softplus(), nn.Linear(256, action_dim), nn.Softplus()) Now, I would like the network to give two separate outputs, like this: That's to say, only the last layer of the network is differe...
The model you want to build is not sequential anymore, since there are two parallel branches at the end. You can keep the common trunk and separate with two additional separate layers. Something like: class Model(nn.Module): def __init__(self): super.__init__() self.actor = nn.Sequential( ...
https://stackoverflow.com/questions/68480744/
PyTorch: Dogs vs Cat dataset with datasets.ImageFolder
I am new on PyTorch trying to create a TransferLearning model. I am using dogs vs cats dataset from Kaggle. I am using ImageFolder to load the data and it requires a folder for each classes. But the photos in the test folder are mixed.So I'm not able to separate the images on the test folder. What can I do to solve the...
You can create a custom Dataset class and wrap it inside a dataloader in Pytorch. This link has great information on this topic An overall structure to follow is class Dog_and_Cat(): def __init__(self, ...): ... # replace with a zipped list of image paths and labels (Cat or Dog) # You can use glob.glob # ...
https://stackoverflow.com/questions/68486511/
How to adjust the learning rate after N number of epochs?
I am using Hugginface's Trainer. How to adjust the learning rate after N number of epochs? For example, I have an initial learning rate set to lr=2e-6, and I would like to change the learning rate to lr=1e-6 after the first epoch and stay on it the rest of the training. I tried this so far: optimizer = AdamW(model.para...
You could train in two steps, first, train with desired initial learning rate then create a second optimizer with the final learning rate. It is equivalent.
https://stackoverflow.com/questions/68492369/
Pytorch cuda is unavailable even installed CUDA and pytorch with cuda. How to fix?
I'm trying to use pytorch with my GPU (RTX 3070) on my Windows machine using WSL2, but I couldn't get it work even though I followed the Nvidia guide (https://docs.nvidia.com/cuda/wsl-user-guide/index.html#abstract). nvidia-smi.exe output: +-----------------------------------------------------------------------------+ ...
My environment is (Ubuntu 20.04 with NVIDIA GTX 1080Ti): $ nvidia-smi | grep CUDA | NVIDIA-SMI 470.74 Driver Version: 470.74 CUDA Version: 11.4 | $ nvcc -V nvcc: NVIDIA (R) Cuda compiler driver Copyright (c) 2005-2021 NVIDIA Corporation Built on Sun_Aug_15_21:14:11_PDT_2021 Cuda compilat...
https://stackoverflow.com/questions/68493965/
AttributeError: 'LSTMClassifier' object has no attribute 'log_softmax'
While making predictions from my LSTM model, I am getting the error :: AttributeError: 'LSTMClassifier' object has no attribute 'log_softmax'.Can anyone explain me what I am doing wrong? class LSTMClassifier(nn.Module): def __init__(self, input_dim, hidden_dim, layer_dim, output_dim): super().__init__() ...
Your train loop does not work. You never pass the input batch to the model therefore out is not a output tensor but a model object which of course can't be passed into an activation function. You have to do this: model = model.to(device) for batch, _ in tst_data: batch = batch.to(device) # pass your input batc...
https://stackoverflow.com/questions/68505119/
How can we use Pytorch Autograd for sequence optimization (in a for loop)?
I want to optimize a sequence in a for loop using Pytorch Autograd. I am using LBFGS. loss = 0.0 for i in range(10): x = f(x,z[i]) loss = loss + mse_loss(x,x_GT) Say the sequence length is 10. I want to optimize x as well as z(z is a tensor array), these are learnable parameters. Note the x will be updated ...
The code you provided is actually perfectly fine: loss = torch.zeros(1) for i in range(10): x = f(x, z[i]) loss += mse_loss(x, x_GT) It will accumulate the loss over the loop steps. The backward pass only needs to be called once, though, so you are not required to retain the graph on it: >>> loss.ba...
https://stackoverflow.com/questions/68507559/
Use MS-COCO format as input to PyTorch MASKRCNN
I am trying to train a MaskRCNN Image Segmentation model with my custom dataset in MS-COCO format. I am trying to use the polygon masks as the input but cannot get it to fit the format for my model. My data looks like this: {"id": 145010, "image_id": 101953, "category_id": 1040, "segm...
To manage COCO formated datasets you can use this repo. It gives classes which you can instantiate from you annotation's file making it really easy to use and to access the data. I don't know which implementation you are using, but if it's something like this tutorial, this piece of code might give you at least some id...
https://stackoverflow.com/questions/68513782/
Parameters for LSTM with CNN in a sequential data
I am doing a classification problem with ECG data. I built a LSTM model but the accuracy of the model is not quiet good. Hence, I am thinking to implement it with CNN. I am planning to pass the data from CNN, then passing the output from CNN to LSTM. Howver, I have noticed that CNN is mostly used in Image classificatio...
Well, that's yours to define, it's the actual architectural decision your need to take to construct your model. The following is not a solution to your question, however, this might give you some ideas. You could pass each timestep through the CNN and retrieve a sequence of feature vectors corresponding to the CNN's o...
https://stackoverflow.com/questions/68514274/
Error with pytorch compilation: LAPACK library not found in compilation. How to solve?
I am already desperate about this problem that I am having. RuntimeError: inverse: LAPACK library not found in compilation The easiest way to reproduce it is: import torch A = torch.rand(5,5) torch.inverse(A) I run this inside a docker container. The part of the dockerfile that compiles pytorch is: #PyTorch RUN pip3 ...
I solved my own problem. I added apt-get liblapack-dev on the dockerfile before the torch compilation. Then I runned the docker container again and it worked.
https://stackoverflow.com/questions/68517600/
How to fix input and parameter tensors are not at the same device?
I have seen other people have this error and I try to follow the steps to resolve, but continue to receive this error. "RuntimeError: Input and parameter tensors are not at the same device, found input tensor at cpu and parameter tensor at cuda:0" I run both model.to(device) and input_seq.to(device). Error sa...
Unlike the to method available on nn.Modules such as your model. The to method on Tensors is not an in-place operation! As stated on the documentation page: This method [nn.Module.to] modifies the module in-place. vs for Tensor.to: [...] the returned tensor is a copy of self with the desired [...] torch.device. In ...
https://stackoverflow.com/questions/68521735/
Difference between transformers schedulers and Pytorch schedulers
Transformers also provide their own schedulers for learning rates like get_constant_schedule, get_constant_schedule_with_warmup, etc. They are again returning torch.optim.lr_scheduler.LambdaLR (torch scheduler). Is the warmup_steps the only difference between the two? How can we create a custom transformer-based schedu...
You can create a custom scheduler by just creating a function in a class that takes in an optimizer and its state dicts and edits the values in its param_groups. To understand how to structure this in a class, just take a look at how Pytorch creates its schedulers and use the same functions just change the functionalit...
https://stackoverflow.com/questions/68523070/
Summing vector pairs efficiently in pytorch
I'm trying to calculate the summation of each pair of rows in a matrix. Suppose I have an m x n matrix, say one like [[1,2,3], [4,5,6], [7,8,9]] and I want to create a matrix of the summations of all pairs of rows. So, for the above matrix, we would want [[5,7,9], [8,10,12], [11,13,15]] In general, I think the ne...
You can try using this function: def sum_rows(x): y = x[None] + x[:, None] ind = torch.tril_indices(x.shape[0], x.shape[0], offset=-1) return y[ind[0], ind[1]] Because you know you want pairs with the constraints of sum_matrix[i,j], where i<j (but i>j would also work), you can just specify that you w...
https://stackoverflow.com/questions/68524558/
RTX 3070 compatibility with Pytorch
NVIDIA GeForce RTX 3070 with CUDA capability sm_86 is not compatible with the current PyTorch installation. The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_70. So I'm currently trying to train a neural network but I'm getting this issue. It seems that the GPU model I have is not compatible...
It might be because you have installed a torch package with cuda==10.* (e.g. torch==1.9.0+cu102) . I'd suggest trying: pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio==0.9.0 -f https://download.pytorch.org/whl/torch_stable.html
https://stackoverflow.com/questions/68529258/
Forcing Ration on Batches in PyTorch DataLoader
I came across a binary classifcation task where the data is heavily imbalanced. (I'm looking at 80:1) Through undersampling, the data ratio is at now 20:1.\ Now, the undersampled/treated data is loaded in to dataloader as below. (this is an nlp task) train_inputs = torch.tensor(input_ids) train_labels = torch.tensor(la...
You can use WeightedRandomSampler with replacement set to true. Just multiply the weight of the positive examples by 20 to bias the ratio towards 20:1. (assuming positives are 20 times more than negatives here) # labels is a numpy array of shape n,1 containing 1 and 0 for each datapoint weights = np.ones(labels.shape) ...
https://stackoverflow.com/questions/68542721/
"SyntaxError: Can't assign to operator"; "ipykernel_launcher.py: error: unrecognized arguments"
I want to execute a train.py script inside a colab or jupyter notebook. Before running I have to set some variables, e.g. dataset-type. I did as I would type into a terminal command but I get a SyntaxError. --dataset-type=voc --dataset-type='voc' ^ SyntaxError: can't assign to o...
It seems the model uses sys.argv, to assign them in a notebook: from sys import argv argv.append('--dataset-type=voc') That should work the same as adding --dataset-type=voc in a terminal.
https://stackoverflow.com/questions/68556605/
How can I add multiple Metadata in Torch Tensorboard Embedding?
I am using torch==1.9.0 and tensorboard==2.5.0. I would like to track data with tensorbaord as an embedding, so I am something like this: data = np.random.poisson(lam=10.0, size=(4,4)) labels = ["A","A","B","B"] ids = [1,2,3,4] writer = SummaryWriter("/runs/") writer.ad...
Found the answer. You could get multiple field by adding a metadata header and give metadat as list of lists: writer.add_embedding(data.values, metadata=metadata, metadata_header=["Name","Labels"]) Reference: https://github.com/tensorflow/tensorboard/issues/6...
https://stackoverflow.com/questions/68556767/
Simple Adjacency matric creation with Pytorch Tensors
I was trying to write a simple function to create a random adjacency matrix in the following way : def create_adj(a): a[a>0.5] = 1 a[a<=0.5] = 0 return a given that a is assumed to be a torch.Tensor() as input, but I get the following error: TypeError: 'int' object does not support item assignment I...
I would assume you are not passing the correct variable your create_adj function. As long as a is a torch.tensor, then it should work. Alternatively, you can directly use the mask as result: def create_adj(x): return (a > .5).float()
https://stackoverflow.com/questions/68562472/
How to Fix "AssertionError: CUDA unavailable, invalid device 0 requested"
I'm trying to use my GPU to run the YOLOR model, and I keep getting the error: Traceback (most recent call last): File "D:\yolor\detect.py", line 198, in <module> detect() File "D:\yolor\detect.py", line 41, in detect device = select_device(opt.device) File "D:\yolor\utils\t...
You forgot to put the == signs between the packages and the version number. According to the PyTorch installation page: py -m pip install torch==1.9.0+cu111 torchvision==0.10.0+cu111 torchaudio===0.9.0 -f https://download.pytorch.org/whl/torch_stable.html
https://stackoverflow.com/questions/68562730/
Pytorch unable to export trained model as ONNX
I have been training a model in the Pytorch framework using multiple convolutional layers (3x3, stride 1, padding same). The model performs well and I want to use it in Matlab for inference. For that, the ONNX format for NN exchange between frameworks seems to be the (only?) solution. The model can be exported using th...
Currently, _convolution_mode operator isn't supported in pytorch. This is due to the use of padding='same'. You need to change padding to an integer value or change it to its equivalent. Consult Same padding equivalent in Pytorch.
https://stackoverflow.com/questions/68565147/
How to fix RuntimeError CUDA error CUBLAS_STATUS_INVALID_VALUE when calling `cublasSgemm`?
When training some models on a working cuda environment, you can get the error RuntimeError: CUDA error: CUBLAS_STATUS_INVALID_VALUE when calling cublasSgemm( handle, opa, opb, m, n, k, &alpha, a, lda, b, ldb, &beta, c, ldc) What does it means and how to fix it?
It may be an incomplete error reporting of a shape error: A mismatch in dimension of a nn.Linear module and its inpput, for example x.shape == [a, b] going into a nn.Linear(c, c, bias=False) with c not matching the shape of x, will result in this error message. See the Pytorch forum conversation.
https://stackoverflow.com/questions/68571902/
Converting From .pt model to .h5 model
I am using Google colab. I want to convert .pt model from my google drive to .h5 model. I follow link https://github.com/gmalivenko/pytorch2keras and https://www.programmersought.com/article/57938937172/ and install libraries and also write code as below: %pip install pytorch2keras %pip install onnx==1.8.1 import nump...
Ah, the classic problem of PyTorch to Tensorflow. Many libraries have come and gone over the years, but I've found ONNX to work the most consistent. You could try something like this. Specific to PyTorch is a Dynamic Computational Graph. A dynamic computational graph means that PyTorch models can dynamically adapt to d...
https://stackoverflow.com/questions/68577156/
Loading PyTorch Lightning Trained checkpoint
I am using PyTorch Lightning version 1.4.0 and have defined the following class for the dataset: class CustomTrainDataset(Dataset): ''' Custom PyTorch Dataset for training Args: data (pd.DataFrame) - DF containing product info (and maybe also ratings) all_itemIds (list) - Python3 list c...
As shown in here, load_from_checkpoint is a primary way to load weights in pytorch-lightning and it automatically load hyperparameter used in training. So you do not need to pass params except for overwriting existing ones. My suggestion is to try trained_model = NCF.load_from_checkpoint("NCF_Trained.ckpt")
https://stackoverflow.com/questions/68578213/
pytorch make_grid (from torchvision.utils import make_grid) behaves different then I expect
trying to run the visualization utils tutorial from pytorch, I tried it with some images of dogs found on the internet. the images used in the tutorial are not distributed for use.. making the gris and showing the result behaves funny - it shows each channel as a separate image (I guess this is what I see) so - from t...
For the output you got, I would assume the correct shape is (height, width, channels) instead of (channels, height, width). You can correct this with torch.permute. The following should provide the desired result: >>> grid = make_grid(torch.stack([transformed_dog1, transformed_dog2]).permute(0,3,1,2)) >>...
https://stackoverflow.com/questions/68579467/
How can I solve this issue? input must have 3 dimensions, got 4
The Below is data which I passed to the Data Loader, train_path='/content/drive/MyDrive/Dataset_manual_pytorch/train' test_path='/content/drive/MyDrive/Dataset_manual_pytorch/test' train = torchvision.datasets.ImageFolder(train_path,transform=transformations) test = torchvision.datasets.ImageFolder(test_path,transform...
You can do the size conversion of torch.Size([64, 3, 32, 32]) to torch.size([64, 32, 32]) by following the bottom code: x = torch.ones((64, 3, 32, 32)) x = x[:, 0, :, :] #Check code: print(x.size())
https://stackoverflow.com/questions/68580717/
Pytorch fasterrcnn resnet50 fpn loss functions
I am using a pretrained model from this tutorial. https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html#defining-your-model The model is pytorch's Faster RCNN ResNet 50 FPN model. Does anyone know what the classification loss, loss, and objectness loss functions are (i.e. Cross Entropy or?). Thanks in ad...
Objectness is a binary cross entropy loss term over 2 classes (object/not object) associated with each anchor box in the first stage (RPN), and classication loss is normal cross-entropy term over C classes. Both first stage region proposals and second stage bounding boxes are also penalized with a smooth L1 loss term. ...
https://stackoverflow.com/questions/68584185/
ImportError: cannot import name 'load_mnist' from 'pytorchcv'
--------------------------------------------------------------------------- ImportError Traceback (most recent call last) <ipython-input-1-2cacdf187bba> in <module> 6 import numpy as np 7 ----> 8 from pytorchcv import load_mnist, train, plot_results, plot_convol...
I assume you might have the wrong pytorchcv package. The one in pypy does not contain load_mnist Starting from scratch you could download mnist as such: data_train = torchvision.datasets.MNIST('./data', download=True,train=True,transform=ToTensor()) data_test = torchvision.datasets.MNIST('./data', download=True,train=...
https://stackoverflow.com/questions/68588949/
The best method for normalizing dataset of images
I have a dataset of images consisting of three splits - the training, validation and test splits, and want to normalize the dataset to make training easier. Hence I want to find the mean and standard deviation of RGB values from the available data. The doubt I have is - should I consider all the splits for normalizing?...
The doubt I have is - should I consider all the splits for normalizing? As you said, in theory you should only make use of training data for anything, even for normalization. Any other way to do this would also be of help. For example, is it just better to use standard values for RGB? In practice, probably yes. In ...
https://stackoverflow.com/questions/68599182/
How to maintain state in a DataLoader's Dataset
I have something like: (see self.cache for the bit that's interesting). class DescriptorDataset(torch.utils.data.Dataset): def __init__(self, descriptor_dir): super().__init__() self.file_paths = glob(osp.join(descriptor_dir, '*')) self.image_ids = [Path(fp).stem for fp in self.file_paths] ...
When I have come across this situation, I have filled the cache during initialisation. In that case it remains fixed during training/inference and can be reloaded the next time you instantiate: class DescriptorDataset(torch.utils.data.Dataset): def __init__(self, descriptor_dir, cache_loc=None): super().__i...
https://stackoverflow.com/questions/68602072/
RuntimeError: "reflection_pad2d" not implemented for 'Byte'
padding = (2, 2, 2, 2) img = torch.nn.functional.pad(img, padding, mode='reflect') out = torch.nn.functional.conv2d(img, kernel, groups=img.shape[1]) Here is the complete Error: File "/home/amir/PycharmProjects/LPTN/loadPretrainedModel.py", line 57, in conv_gauss img = torch.nn.functional.pad(img, padd...
You need to change data type of your img to float e.g. img.float(). Many operations such as reflection_pad2d are implemented only for float tensors.
https://stackoverflow.com/questions/68602342/
RuntimeError: 1only batches of spatial targets supported (3D tensors) but got targets of size: : [4]
How to get around the following error with nn.CrossEntrophyLoss() ? Note: I tried using nn.BCELoss(), but it resulted in different error: ValueError: Using a target size (torch.Size([4])) that is different to the input size (torch.Size([4, 3, 32, 32])) is deprecated. Please ensure they have the same size.
The error message is pretty clear: you are using a one-dimensional target tensor while your output prediction has spatial dimensions (a three-channel map). When using nn.CrossEntropyLoss, your target must be dense (each element is a label id): something with a shape of (batch_size,), where each element in the target be...
https://stackoverflow.com/questions/68607307/
Methods for increasing accuracying of a CNN for image classification
I'm currently working on a image classification task, involving a large datasets of grayscale images of cartoons and my CNN needs to classify them. Atm my model has a test accuracy of about 88% but I know a higher accuracy is possible. I've tried: improving / changing the actual model / architecture using different me...
From what you've described, it sounds like it might be worth spending some time on the data preparation. Here is a good article on how to do that for images. Some ideas you could try are: Resizing all your images to a fixed size Subtracting mean pixel values, i.e. normalizing the dataset I don't really know the conte...
https://stackoverflow.com/questions/68607955/
Why network with linear layers can't learn anything
I am trying to build a neural network for binary classification, unfortunately it always predicts the value 0, even though one fifth of the training set data is 1. I have no idea why it is so. My dataset looks as this, so there are a couple of categorical variables and a couple of continuous, (target is the one we pred...
Please see the doc This is the standard training loop for epoch in range(2): # loop over the dataset multiple times running_loss = 0.0 for i, data in enumerate(trainloader, 0): # get the inputs; data is a list of [inputs, labels] inputs, labels = data # zero the parameter gradients ...
https://stackoverflow.com/questions/68609125/
Action-selection for dqn with pytorch
I’m a newbie in DQN and try to understand its coding. I am trying the code below as epsilon greedy action selection but I am not sure how it works   if sample > eps_threshold: with torch.no_grad(): # t.max(1) will return largest column value of each row. # second column on max...
When you train a model, torch has to store all the tensors involved in computing the output into a graph, to then be able to make a backward pass during training; this is computationally expensive, and considering that after selecting the action you don't have to train the network, because your only goal here it to pic...
https://stackoverflow.com/questions/68615100/
Normalizing pixel Values in PyTorch
I am currently working with the CORnet-Z neural network and I am training it on an alternative version of the ImageNet image dataset. I looked through the code and noticed this image value normalization method: normalize = torchvision.transforms.Normalize(mean=[0.485, 0.456, 0.406], ...
What you found in the code is statistics standardization, you're looking to normalize the input. These are two different operations but can be carried out with the same operator: under torchvision.transforms by the name of Normalize. It applies a shift-scale on the input: Normalize a tensor image with mean and standar...
https://stackoverflow.com/questions/68620946/
How to convert the below Tensorflow code to Pytorch (transfer learning)?
I want to know how to convert the below codes(Tensorflow) to Pytorch. I've wanted to use DataLoader but I couldn't. Is it possible to use DataLoader for converting? or Can you tell me any other ways to convert? Thanks a lot :) from tensorflow.keras.preprocessing import image as image_utils from tensorflow.keras.applic...
import os from PIL import Image import torch from torch.utils.data import DataLoader, Dataset from torchvision import transforms class MyData(Dataset): def __init__(self, data_path): #path of the folder where your images are located self.data_path = data_path #transforms to perform on image...
https://stackoverflow.com/questions/68632679/
Best way to detect Vanishing/Exploding gradient in Pytorch via Tensorboard
I suspect my Pytorch model has vanishing gradients. I know I can track the gradients of each layer and record them with writer.add_scalar or writer.add_histogram. However, with a model with a relatively large number of layers, having all these histograms and graphs on the TensorBoard log becomes a bit of a nuisance. I'...
This is a minimal example of how you could go about evaluating the norm of a particular layer in your model. Taking a simple model for illustration purposes: class ConvNet(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(1, 10, 5) self.conv2 = nn.Conv2d(10, 20, 5) ...
https://stackoverflow.com/questions/68634707/
Channel first and channel last in convolution
I saw there are two types of data: channel first and last in the world of convolutional networks. According to many websites, "channel-first" refers to NCHW format, while "channel-last" is equivalent to NHWC format. This is clear because in channel first format, C is positioned before H and W. Howev...
I had originally overlooked the paper you linked where they clearly define the two opponents to how the terms are usually employed in the documentation and elsewhere. There are indeed two different ways to look at CHW and HWC... TLDR; For end-users CHW is channel-first while HWC is channel last. In this case, we refer ...
https://stackoverflow.com/questions/68634724/
Python code to convert 1D tensor to 2D tensor
I am trying to use Binary Cross Entropy Loss (BCE loss) for Simese network. I have two inputs for BCE loss function: output (input_dy) → tensor of size [4] , output of neural network true_labels (y_true) → tensor of size [4], target (true value) For BCE loss, the input parameters must be of the dimension: output (inpu...
It looks to me that your output is binary so you don't really need a 2D matrix for that task. Also, I'm not quite sure that the BCE Loss (nor BCEWithLogits) requires tensors of different dimensions, they should both have shape (N, *) as far as I know. Apart from that, for the sake of the question: if you have p(x), you...
https://stackoverflow.com/questions/68642120/
pytorch nn.Module inference
I am planning on learning Pytorch. However at this stage I would like to ask a question so that I can understand some code I am reading When you have a class whose base class is nn.Module say class My_model(nn.Module) how are inferences supposed to be run there? In the code I am reading it says tasks_output, other = m...
You are confusion __init__ and __call__. In your example my_model is a class, therefore calling my_model_instance = my_model(arguments) Invoke's my_model.__init__ with arguments. The result of this call is a new instance of my_model in the variable my_model_instance. Once you instantiated the class my_model as the var...
https://stackoverflow.com/questions/68645889/
Pytorch transformations on GPU, is it worth on big input data?
I am running a UNet with PyTorch on medical imaging data with a bunch of transformations and augmentations in my preprocessing. However, after digging into the different preprocessing packages like Torchio and MONAI, I noticed that most of the functions, even when they take Tensors as IO, are running things on CPU. The...
A transformation will typically only be faster on the GPU than on the CPU if the implementation can make use of the parallelism offered by the GPU. Typically anything that operates element-wise, or row/column-wise can be made faster on GPU. This therefore concerns most image transformations. The reason why some librari...
https://stackoverflow.com/questions/68649820/
What is the "data.max" of a torch.Tensor?
I have been browsing the documentation of torch.Tensor, but I have not been able to find this (just similar things). If a_tensor is a torch.Tensor, what is a_tensor.data.max? What type, etc.? In particular, I am reading a_tensor.data.max(1)[1] and a_tensor.data.max(1)[1][i].cpu().numpy().
When accessing .data you are accessing the underlying data of the tensor. The returned object is a Torch.*Tensor as well, however, it won't be linked to any computational graph. Take this example: >>> x = torch.rand(4, requires_grad=True) >>> y = x**2 >>> y tensor([0.5272, 0.3162, 0.1374, 0....
https://stackoverflow.com/questions/68650265/
how to save in pytorch an ONNX model with training (autograd) operations?
In pytorch, is it possible to save an ONNX model to file including the backward operations? If not, is there any other way in pytorch to save the forward and backward graph as text (json, pbtxt ...)? Any help will be appreciated.
it's possible if you wrap the model with ORTModule - https://github.com/microsoft/onnxruntime-training-examples There's flag to enable onnx model saving, for example: model._save_onnx = True model._save_onnx_prefix = 'MNIST' However, the onnx graph from fw will be further optimized before generating bw graph. Thus it's...
https://stackoverflow.com/questions/68672250/
torch.masked_scatter result did not meet expectations
my pytorch code: import torch x = torch.tensor([[0.3992, 0.2908, 0.9004, 0.4850, 0.6004], [0.5735, 0.9006, 0.6797, 0.4152, 0.1732]]) print(x.shape) mask = torch.tensor([[False, False, True, False, True], [ True, True, True, False, False]]) print(mask.shape) y = torch.tensor([[0., 0., 0., 0.,...
You are right, this is confusing and there is virtually no documentation. However, the way scatter works (as you have discovered) is that the ith True in a row is given the ith value from the source. So not the value corresponding to the position of the True. Luckily what you are trying to do can easily be achieved usi...
https://stackoverflow.com/questions/68675160/
AzureML experiment pipeline not using CUDA with PyTorch
I am running an experiment pipeline to train my model with PyTorch and CUDA. I created the environment as follow: env = Environment.from_conda_specification(model, join(model, 'conda_dependencies.yml')) env.docker.enabled = True env.environment_variables = {'MODEL_NAME': model, 'BRANCH': branch, 'COMMIT': c...
Depending on pytorch version you might need a specific version of cuda. Try cuda 11.0.3 or cuda 11.1 from here https://github.com/Azure/AzureML-Containers/tree/master/base/gpu Regarding your code snippet, please move environment variables out of environment object to runconfiguration
https://stackoverflow.com/questions/68678587/
AttributeError: Can't pickle local object 'pre_datasets..' when implementing Pytorch framework
I was trying to implement a pytorch framework on CNN. I'm sure the code is right because it's from a tutorial and it works when I ran it on Jupyter Notebook on GoogleDrive. But when I tried to localize it as a .py file, it suggest an error: AttributeError: Can't pickle local object 'pre_datasets.<locals>.<la...
I had a similar issue and I used dill like this: import dill as pickle and it worked out of the box!
https://stackoverflow.com/questions/68679806/
Convert Flatten layer from PyTorch to Tensorflow - Equivalent for start_dim and end_dim
What is the equivalent of the options start_dim and end_dim of the flatten PyTorch layers, in Tensorflow? With Tensorlfow we only have data_format and it is not customizable.
I don't think there is an identical implementation in tf. However, you can always use tf.reshape and add the shape yourself with a simple function which takes as arguments input, start_dim and end_dim and outputs the corresponding output shape that torch.flatten would give you.
https://stackoverflow.com/questions/68691960/
Split neural network, load only needed part onto the GPU
I have a very, very big neural network and an Google Colab Pro Subscripting receiving my 16GB of GPU RAM. Unfortunately, this is not enough. My idea now is, to split the model (Unet) into the encoder and decoder part separately, and proceed like the following: Load encoder to the GPU Process the data through the encod...
There are a couple of wrong things with this: Your autocast block should include the forward on your model You don't need to go back and forth from CPU to GPU and back, it's already a bottleneck with tensors, imagine with models. Optional: what the heck is your UNet made of if you can't make it fit on a 16GB device? ...
https://stackoverflow.com/questions/68693585/
How can I reshape (A,) and (B, C, D) shapes to the single (A, B, C, D)?
This is my code; for img_loc in list(self.train_data)[idx]: images_set.append(self.load_ucf_image(img_loc)) print(images_set) And, this is its output [tensor([[[ 1.7865, 1.8893, 1.9578, ..., -1.3815, -0.4054, 0.2967], [ 1.7694, 1.8722, 1.9578, ..., -0.6452, -0.4054, 0.1254], [ 1.75...
A more general format: import tensorflow as tf import numpy as np #Let's make a prototype of one image using ones (just to reproduce the problem without original data...) one_liketensor=np.ones((3,112,112)) #Then let's notice the same can be seen in tensor-format as follows: one_liketensor_as_tensor=tf.constant(one_l...
https://stackoverflow.com/questions/68703236/
HuggingFace text summarization input data format issue
I’m trying to fine-tune a model to perform text summarization. I’m using AutoModelForSeq2SeqLM.from_pretrained(), so the following applies to several models (e.g. T5, ProphetNet, BART). I’ve created a class called CustomDataset, which is a subclass of torch.utils.Dataset. That class contains one field: samples - a list...
Using the name label_ids instead of label fixes the specific problem. label should be used if the label is either an int, a float or a one-element torch.Tensor. For tensors with multiple elements, use label_ids. See data_collator.py, lines 62-71 for details: if "label" in first and first["label"] is...
https://stackoverflow.com/questions/68703608/
Pytorch Lightning Tensorboard Logger Across Multiple Models
I'm relatively new to Lightning and Loggers vs manually tracking metrics. I am trying to train two distinct models and have their accuracy and loss plotted on the same charts in tensorboard (or any other logger) within Colab. What I have right now is basically: trainer1 = pl.Trainer(gpus=n_gpus, max_epochs=n_epochs, p...
The exact chart used for logging a specific metric depends on the key name you provide in the .log() call (its a feature that Lightning inherits from TensorBoard itself) def validation_step(self, batch, _): # This string decides which chart to use in the TB web interface # vvvvvvvvv self.log('valid_acc',...
https://stackoverflow.com/questions/68707849/
GNN with Stable baselines
I am looking to use DGL or pytorch geometric for building my policy and value networks in stable baselines, however I am struggling to figure out how to send over observations. The observations must be one of the gym spaces class but I am not sure how to send a graph object that can be used by DGL or Pytorch geometric...
You can serialize your DGL graph object using pickle and convert the resultant byte string into a vector of integers (with each char in the string corresponding to one int). import dgl import numpy as np import pickle def serialize_graph(graph: dgl.DGLGraph): as_byte_string = pickle.dumps(graph) as_int_list = ...
https://stackoverflow.com/questions/68731718/
Evaluate the model during training affects its performance PyTorch
In PyTorch, I want to evaluate my model on the validation set every eval_step during training, and I wrote code like this: def tune(model, loader_train, loader_dev, optimizer, epochs, eval_step): for epoch in range(epochs): for step,x in enumerate(loader_train): optimizer.zero_grad() ...
I think you probably set 'shffule=True' in your dataloader. Even though you fix 'random seed', dataloader in torch will generate different results if you use another dataloader while using current dataloader. In the scenario you describe, it may cause your model get data input in different order and then result in diff...
https://stackoverflow.com/questions/68736827/
Detect if image is blurry using pytorch android API
So I am working in this app in which if an officer take a picture of car accident and if this picture is blur, it will no accept it. It will only allow images based on quality and resolution. So after research, I found that I can implement this feature using pytorch in which I will save it in my asset and then write ko...
For a start you can try to build this using conventional computer vision algorithms. You will find a few examples trying to implement a similar idea using OpenCV (e.g. here). If you want to solve such a task through machine learning, you either can try to find a model that is trained to solve such a task online (maybe ...
https://stackoverflow.com/questions/68737162/
AWS Sagemaker InvokeEndpoint: operation: Endpoint of account not found
I've been following this guide here: https://aws.amazon.com/blogs/machine-learning/building-an-nlu-powered-search-application-with-amazon-sagemaker-and-the-amazon-es-knn-feature/ I have successfully deployed the model from my notebook instance. I am also able to generate predictions by calling predict() method from sag...
I was having the exact same error, I've just fixed mine by setting the correct region. I have verified the region, endpoint name and the account number. I know that you have indicated that you have verified the region, but in my case, the remote computer had another region configured. So I just ran the following comm...
https://stackoverflow.com/questions/68777186/
Keyerror:None ,I don't understand this problem
class KITTIRAWDataset(KITTIDataset): def __init__(self, *args, **kwargs): super(KITTIRAWDataset, self).__init__(*args, **kwargs) def get_image_path(self, folder, frame_index, side): self.img_ext='.png' f_str = "{:010d}{}".format(frame_index, self.img_ext) image_path = os.path.join( s...
KeyError means that you are trying to get a value from a dict with a key that does not exist. In the line displayed you have self.side_map[side]) and KeyError: None means that the key is None, so your side variable have a value None. That is what we an know looking at the code, the error and without more context
https://stackoverflow.com/questions/68779859/
Single GPU Pytorch training with SLURM - how to set "ntasks-per-node"?
I would like to do some simple fine-tuning on a transformers model using a single GPU on a server via SLURM. I haven't used SLURM before and I am not a computer scientist so my understanding of the field is a bit limited. I have done some research and created the script below. Could you please confirm if it is fit for ...
Yes, it will request 1 GPU for running the task. As described in the documentation: The default is one task per node [...] Therefore, the default value for --ntasks-per-node is already 1, which means you don't even need to define it. In fact, even --nodes has a default value of 1. Nonetheless, some consider a good pr...
https://stackoverflow.com/questions/68787145/
min-max normalization of a tensor in PyTorch
I want to perform min-max normalization on a tensor in PyTorch. The formula to obtain min-max normalization is I want to perform min-max normalization on a tensor using some new_min and new_max without iterating through all elements of the tensor. >>>import torch >>>x = torch.randn(5, 4) >>>...
Having defined v_min, v_max, new_min, and new_max as: >>> v_min, v_max = v.min(), v.max() >>> new_min, new_max = -.25, .25 You can apply your formula element-wise: >>> v_p = (v - v_min)/(v_max - v_min)*(new_max - new_min) + new_min tensor([[-0.1072, -0.2009, 0.2500, -0.1025], [ 0.14...
https://stackoverflow.com/questions/68791508/
How to get values return by Tuple Object in Maskcrnn libtorch
I’m new in C++ and libtorch, I try load model by torchscript and execute inference, the codes like below: torch::jit::script::Module module; try { module = torch::jit::load("../../weights/card_extraction/pytorch/2104131340/best_model_27_mAP=0.9981_torchscript.pt"); } catch (const c10::Error...
You can get access to the element like here: I can parse Tuple arguments and get access to it like in Tensor format. It can help u. auto output1_t = output.toTuple()->elements()[0].toTensor(); auto output2_t = output.toTuple()->elements()[1].toTensor(); https://discuss.pytorch.org/t/how-can-i-get-access-to-first...
https://stackoverflow.com/questions/68796689/
HuggingFace Trainer logging train data
I'm following this tutorial to train some models: https://huggingface.co/transformers/training.html I'd like to track not only the evaluation loss and accuracy but also the train loss and accuracy, to monitor overfitting. While running the code in Jupyter, I do see all of htis: Epoch Training Loss Validation Loss A...
You can use the methods log_metrics to format your logs and save_metrics to save them. Here is the code: # rest of the training args # ... training_args.logging_dir = 'logs' # or any dir you want to save logs # training train_result = trainer.train() # compute train results metrics = train_result.metrics max_train_s...
https://stackoverflow.com/questions/68806265/
Negative loss when trying to implement aleatoric uncertainty estimation according to Kendall et al
I'm trying to implement a neural network with aleatoric uncertainty estimation for regression with pytorch according to Kendall et al.: "What Uncertainties Do We Need in Bayesian Deep Learning for Computer Vision?" (Link). However, while the predicted regression values fit the desired ground truth values quit...
TLDR: The optimization drives the loss to a minimum where the gradient becomes zero, regardless of what the nominal loss value is. A comprehensive explanation by K.Frank: A smaller loss – algebraically less positive or algebraically more negative – means (or should mean) better predictions. The optimization step uses ...
https://stackoverflow.com/questions/68806330/
Splitting tensor into sub-tensors in overlapping fashion
I'm in pytorch and I have a tensor x of size batch_size x d x S. It has to be intended as a batch of sequences of length S, where every sequence element is d dimensional. Every sequence is actually the overlap of multiple sub-sequences, in the following sense: every sub-sequence is of size past_size + present_size, i....
Possible method using torch.gather You can see this problem as reassigning each element to a new position. This has to be done using a tensor containing the indices of the permutation you which to see happening. If you look at the indices of the last dimension for input x (we will take your example with x.shape = (4, 8...
https://stackoverflow.com/questions/68860290/
libtorch and pytorch cannot be installed simultaneously?
I am learning to develop with PyTorch as well as LibTorch. I have the following line in my ~/.bashrc for dynamic linking of libtorch libraries: # libtorch linking path export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/user/.dev_libraries/libtorch/lib/ However, when this path is in LD_LIBRARY_PATH, importing torch in Pytho...
I faced the same problem too. You can type import torch print(torch.__version__) to see the version of torch, and use the same version of libtorch, that would solve the problem probably.
https://stackoverflow.com/questions/68878821/
Token indices sequence length is longer than the specified maximum sequence length for this model (28627 > 512)
I am using BERT's Huggingface DistilBERT model as a backend for a question and answer application. The text I am using with which to train the model is one very large single text field. Even though the text field is a single string, the punctuation was left in place as a clue for BERT. When I execute the application ...
Edit this line: encoding = tokenizer.encode_plus(question, tokenizer(context, truncation=True).input_ids) to encoding = tokenizer.encode_plus(question, tokenizer(context, truncation=True, max_length=512).input_ids)
https://stackoverflow.com/questions/68885352/
Store a multi-dim tensor on disk and read from offset
I have a multi-dimensional tensor like this tensor([[ 0.5599, 0.4593, 0.0580, ..., -0.2404, 0.1144, -0.5047], [ 0.1545, 0.3332, 0.3836, ..., 0.2483, -0.0849, -0.2216], [ 0.4513, 0.0115, 0.0801, ..., -0.8038, 0.2350, -0.3261], ..., [-0.4387, 0.3028, -0.0510, ..., -0.4966, -0...
The answer depends on what you are trying to maximize/minimize. You could define "Best way to store" as the fastest write, the fastest read, the smallest file, ... But given your constraints I think HDFS should be a good candidate. Pandas allows you to save as HDFS format with the df.to_hdf() function. You ca...
https://stackoverflow.com/questions/68886280/
why the output of model is different in pytorch
I have a simple model, just only one linear layer. model = torch.nn.Linear(1,1).to(device) x_train1 = torch.FloatTensor([[1], [2], [3]]) out = model(x_train1) print(out) But whenever I tried to run this code, the printed output is diffrent. Also I set these random seeds. import random import torch import numpy as np r...
You must set the seed every time you run the code if want to get the same result. import torch def my_func(device: str, seed: int): torch.manual_seed(seed) model = torch.nn.Linear(1,1).to(device) x_train1 = torch.FloatTensor([[1], [2], [3]]) out = model(x_train1) print(out) # Whenever you run the ...
https://stackoverflow.com/questions/68886676/
MisconfigurationException: You requested GPUs: [0] But your machine only has: []
I'm running JupyterLab via. AWS SageMaker. I've been taking AWS certifications, but this is my first time actively using AWS. Update: I have changed the Notebook instance type to ml.g4dn.xlarge, a GPU. Will run and see what happens. How do I change the instance types of EC2 to GPU? In Google Colab, e.g., you can sele...
First thing is to determine if you are you using a SageMaker Studio or SageMaker notebook instance. Since you are using SageMaker notebooks, you first need to go back to SageMaker console, select the correct notebook, and stop it. Once the notebooks is stopped, you can edit the configuration and select an instance tha...
https://stackoverflow.com/questions/68894940/
urllib.error.HTTPError: HTTP Error 403: rate limit exceeded when loading resnet18 from pytorch hub
I am not sure why I get a rate limit error. (fashcomp) [jalal@goku fashion-compatibility]$ python main.py --test --l2_embed --resume runs/nondisjoint_l2norm/model_best.pth.tar --datadir ../../../data/fashion /scratch3/venv/fashcomp/lib/python3.8/site-packages/torchvision/transforms/transforms.py:310: UserWarning: The u...
This is a bug in Pytorch 1.9. As a workaround, try adding: torch.hub._validate_not_a_forked_repo=lambda a,b,c: True to your script before any torch.hub call. i.e.: torch.hub._validate_not_a_forked_repo=lambda a,b,c: True model = torch.hub.load('pytorch/vision:v0.9.0', 'resnet18', pretrained=True) According to Philip...
https://stackoverflow.com/questions/68901236/
Feeding an image to stacked resnet blocks to create an embedding
Do you have any code example or paper that refers to something like the following diagram? I want to know why we want to stack multiple resnet blocks as opposed to multiple convolutional block as in more traditional architectures? Any code sample or referring to one will be really helpful. Also, how can I transfer tha...
Applying self-attention to the outputs of Resnet blocks at the very high resolution of the input image may lead to memory issues: The memory requirements of self-attention blocks grow quadratically with the input size (=resolution). This is why in, e.g., Xiaolong Wang, Ross Girshick, Abhinav Gupta, Kaiming He Non-Local...
https://stackoverflow.com/questions/68901687/
How to change the pytorch version in Google colab
I need to change the pytorch version in google colab,so i install anaconda %%bash MINICONDA_INSTALLER_SCRIPT=Miniconda3-4.5.4-Linux-x86_64.sh MINICONDA_PREFIX=/usr/local wget https://repo.continuum.io/miniconda/$MINICONDA_INSTALLER_SCRIPT chmod +x $MINICONDA_INSTALLER_SCRIPT ./$MINICONDA_INSTALLER_SCRIPT -b -f -p $MINI...
First, you have to run !pip uninstall torch Then, when you are prompted with Proceed (y/n)?, click on the background of where the output is being printed, press y and then click Enter. This will uninstall torch, it will take more or less 5 minutes. Then, you have to !pip install torch==1.0.0 And finally import torch ...
https://stackoverflow.com/questions/68903158/
After some number of epochs fake image creation become worst in GAN
I'm trying to create GAN model. This is my discriminator.py import torch.nn as nn class D(nn.Module): feature_maps = 64 kernel_size = 4 stride = 2 padding = 1 bias = False inplace = True def __init__(self): super(D, self).__init__() self.main = nn.Sequential( nn....
The GAN training is inherently unstable because of simultaneous dynamic training of two competing models. Tried plotting the loss values from your question and the loss of discriminator and generator looks like below: Looking at the loss and the generated images, we can say that the training fails to converge. This fa...
https://stackoverflow.com/questions/68904476/
soft cross entropy in pytorch
I have a bit of a problem implementing a soft cross entropy loss in pytorch. I need to implement a weighted soft cross entropy loss for my model, meaning the target value is a vector of probabilities as well, not hot one vector. I tried using the kldivloss as suggested in a few forums, but it does not expect a weight v...
According to your comment, you are looking to implement a weighted cross-entropy loss with soft labels. Indeed nn.CrossEntropyLoss only works with hard labels (one-hot encodings) since the target is provided as a dense representation (with a single class label per instance). You can implement the function yourself thou...
https://stackoverflow.com/questions/68907809/
imbalanced classification using undersampling and oversampling using pytorch python
I want to use oversampling and under sampling techniques together I have 6 classes with number of samples as following: class 0 250000 class 1 48000 class 2 40000 class 3 38000 class 4 35000 class 5 7000 I want to use smot to make all classes balance and equal same size class 0 40000 class 1 40000 class 2 40000 class 3...
I Try this ros = RandomUnderSampler() X, y=ros.fit_resample(mydata, labels) strategy = {0:40000, 1:40000, 2:40000, 3:40000, 4:40000, 5:40000} over = SMOTE(sampling_strategy=strategy) X, y=over.fit_resample(X, y)
https://stackoverflow.com/questions/68913032/
Converting a fully connected neural network with variable number of hidden layers from tensorflow to pytorch
I recently started learning pytorch and I am trying to convert a part of a large script including coding a MLP with variable number of hidden layers from Tensorflow to pytorch. import tensorflow as tf ### Base neural network ...
How could I write down similar weights and bias variables and attach them in each hidden layer in PyTorch? An easier way to define those is to create a list containing the params as (weight, bias) tuples: def init_mlp(layer_sizes, std=.01, bias_init=0.): params = [] for n_in, n_out in zip(layer_sizes[:-1], ...
https://stackoverflow.com/questions/68924907/
Pytorch Text AttributeError: ‘BucketIterator’ object has no attribute
I’m doing seq2seq machine translation on my own dataset. I have preproceed my dataset using this code. The problem comes when i tried to split train_data using BucketIterator.split() def tokenize_word(text): return nltk.word_tokenize(text) id = Field(sequential=True, tokenize = tokenize_word, lower=True, init_token=...
train_iterator = BucketIterator.splits( (train_data), batch_size = batch_size, sort_within_batch = True, sort_key = lambda x: len(x.id), device = device ) here Use BucketIterator instead of BucketIterator.splits when there is only one iterator needs to be generated. I have met this problem and the method men...
https://stackoverflow.com/questions/68931409/
DataLoader worker exited unexpectedly (pid(s) 48817, 48818)
When running my code I recieved this error message "RuntimeError: DataLoader worker (pid(s) 48817, 48818) exited unexpectedly" I am completely unsure where to begin to solve this issue. Any guidance at all would be greatly appreciated. Code and traceback posted below batch_size = 128 image_size = (64,64) stat...
One of the reason might be data loading with multiprocessing. As far as I know, in Windows, if you don't set num_workers to 0 then there would be errors. So I recommend you to try without num_workers (because by default, it is 0) or just set it num_workers=0. train_dl = DataLoader(train_ds, batch_size, shuffle=True, nu...
https://stackoverflow.com/questions/68931909/
How to prune the k% lowest weight by pytorch?
Here I learn from the paper called Deep compression [Han et. al.] using resnet18 I also work the following code, the weight times the mask so that it is the after_weight pruned by the k% lowest weight to zero. But that code doesn't work for me. Any efficient solution? prune = float(0.1) def prune_weights(torchweights):...
You can use torch.nn.utils.prune. It seems you want to remove 10% of every Conv2D layer. If that is the case, you can do it this way: import torch import torch.nn.utils.prune as prune # load your model net = ? # in your example, you want to remove 10% prune_perc = 0.1 for name, module in net.named_modules(): if ...
https://stackoverflow.com/questions/68936169/
Is there a mean-variance normalization layer in PyTorch?
I am new to PyTorch and I would like to add a mean-variance normalization layer to my network that will normalize features to zero mean and unit standard deviation. I got a bit confused reading the documentation, could anyone give me some leads?
As @Ivan commented, the normalization can be done on many levels. However, as You say normalize features to zero mean and unit standard deviation I suppose You just want to input unbiased data to the network. If that's the case, You should treat it as data preprocessing step rather than a layer of Your model and basi...
https://stackoverflow.com/questions/68938545/