instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
Convert unknown labels to Yolov5 | I own a dataset of images with unknown label format, which is:
angry_actor_104.jpg 0 28 113 226 141 22.9362 0
It indicates an image as follows:
image_name face_id_in_image face_box_top face_box_left face_box_right face_box_bottom face_box_cofidence expression_label
My question is: How can this be converted into the yo... | Since the format is unknown you are unlikely to find existing code to completely handle the transformation but I can share some tips to get started.
The annotations file does not have enough info to get converted to Yolo format. Because to convert to Yolo you also need to know the dimensions of the images. If all of ... | https://stackoverflow.com/questions/70243979/ |
PyTorch Matrix Product | This is the standard batch matrix multiplication:
import torch
a = torch.arange(12, dtype=torch.float).view(2,3,2)
b = torch.arange(12, dtype=torch.float).view(2,3,2) - 1
c = a.matmul(b.transpose(-1,-2))
a,b,c
>>
(tensor([[[ 0., 1.],
[ 2., 3.],
[ 4., 5.]],
[[ 6., 7.],
... | Got it. We can just slice g with fancy indexing. We just extract the matrix multiplication result within the same batch:
g = g.view(2,3,2,3)
res = g[range(2),:,range(2),:]
res
| https://stackoverflow.com/questions/70256212/ |
Pytorch running_mean, running_var and num_batches_tracked are updated during training, but I want to fix them | In pytorch, I want to use a pretrained model and train my model to add a delta to the model result, that is:
╭----- (pretrained model) ------ result ---╮
input------------- (my model) --------- Δresult --+-- final_result
Here is what I did:
Use load_state_dict to load pretrained model's parameters
Set all pr... | I stumbled upon the same problem, so I adapted the context manager found in this repo as follows:
@contextlib.contextmanager
def _disable_tracking_bn_stats(self):
def switch_attr():
if not hasattr(self, 'running_stats_modules'):
self.running_stats_modules = \
[mod for n, mod in s... | https://stackoverflow.com/questions/70259900/ |
How to efficiently implement a non-fully connected Linear Layer in PyTorch? | I made an example diagram of a scaled down version of what I'm trying to implement:
So the top two input nodes are only fully connected to the top three output nodes, and the same design applies to the bottom two nodes. So far I've come up with two ways of implementing this in PyTorch, neither of which are optimal.
Th... | If weight sharing is ok, then 1D convolutions should solve the problem:
class Module(nn.Module):
def __init__(self):
self.layers = nn.Conv1d(in_channels=2, out_channels=3, kernel_size=1)
self._n_splits = 2
def forward(self, input):
B, C = input.shape
output = self.layers(input.view(B, C//se... | https://stackoverflow.com/questions/70269663/ |
Neural networks do not work well in pytorch | I am trying to build a neural network with two inputs and one output in pytorch.
However, I get an error and cannot get it to work.
python code is below.
import torch
import numpy as np
import os
import pandas as pd
import glob
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
class Mod... | You're getting an error at the first layer of your neural network because there is a dimension mismatch. The weights are shape (2,256), so it expects an input of shape (N,2).
It looks like you provide 100 training examples, so N=100, but your input is shape (100,1) instead of (100,2). In your code, it looks like a is (... | https://stackoverflow.com/questions/70284024/ |
How does batch’s element are processed by Pytorch? | I have a generic network without random element in his structure (e.g. no dropout) so that if I forward a given image input through the network, I put gradient to zero and repeat again the forward with the same image input I get the same result (same gradient vector, output,…)
Now let’s say that we have a batch of N el... | The difference you are trying to work out here is between what is called a mini-batch gradient descent vs iterative updates at each training sample.
You can refer to this wiki for some background Stochastic_gradient_descent#Iterative_method
In the mini-batch method (your point 1), you update the parameters after you ha... | https://stackoverflow.com/questions/70288949/ |
Why my custom dataset gives attribute error? | my initial data was like this
My data is a pandas dataframe with columns 'title' and 'label'. I want to make a custom dataset with this. so I made the dataset like below. I'm working on google colab
class newsDataset(torch.utils.data.Dataset):
def __init__(self,train=True,transform=None):
if train:
self.fil... | Please add the following missing line to your __init__ function:
self.transform = transform
| https://stackoverflow.com/questions/70292294/ |
TensorDataset error with dimensions and int not callabe? | I have some numpy arrays that I would like to pass into the TensorDataset from PyTorch, so it can be passed into the DataLoader for training in a neural network. These are the dimension of my train and test feature and targets:
Feature train shape:
(2338834, 21)
Target train shape:
(2338834, 3)
Feature test shape:
(662... | I was able to bypass this by converting to a tensor first:
features_train_tensor = torch.tensor(input_train)
target_train_tensor = torch.tensor(output_train)
features_test_tensor = torch.tensor(input_test)
target_test_tensor = torch.tensor(output_test)
# Passing numpy array to to DataLoader
tra... | https://stackoverflow.com/questions/70293052/ |
Wandb training kills kernel in jupyter lab | In my jupyter I can train my model on batch_size=8, but when I use wandb always after 9 iterations the process is killed and kernel restarts. What's more weird is that the same code worked on colab, but with my GPU (RTX 3080) I can never finish the process.
Does anyone have any idea how to overcome this issue?
Edit: I ... | Hmm, strange, so in your edit you're saying that it works ok if you remove wandb.watch?
To double check, have you tried the original code while on the latest version of wandb (0.12.7)?
| https://stackoverflow.com/questions/70297236/ |
Do I need to apply the Softmax Function ANYWHERE in my multi-class classification Model? | I am currently turning my Binary Classification Model to a multi-class classification Model. Bare with me.. I am very knew to pytorch and Machine Learning.
Most of what I state here, I know from the following video.
https://www.youtube.com/watch?v=7q7E91pHoW4&t=654s
What I read / know is that the CrossEntropyLoss... | For calculating the loss using CrossEntropy you do not need softmax because CrossEntropy already includes it. However to turn model outputs to probabilities you still need to apply softmax to turn them into probabilities.
Lets say you didnt apply softmax at the end of you model. And trained it with crossentropy. And th... | https://stackoverflow.com/questions/70303466/ |
How do I visualize CNN on pytorch | I've just learned a little about pytorch. I built a CNN to calculate the effects of various optimization algorithms with the official documents of pytorch (I've just finished from SGD to adagrad). However, most of the official documents and tutorial videos ended when the accuracy and time-consuming were calculated, and... | I can not tell you what library is used to generate the plot you linked to.
There are plenty of options, all of which you can use once you have the data.
One of these options is matplotlib. Others include using Matlab or pgfplots if you want to include your plots in a LaTeX document. These are the tools I use somewhat ... | https://stackoverflow.com/questions/70315384/ |
How to confirm that PyTorch Lightning is using (all) available GPUs and debug if it isn't? | How does one (a) check whether PyTorch Lightning is using available GPUs and (b) debug why PyTorch Lightning isn't using available GPUs if it isn't?
| for the (a) monitoring you can use this objective tool Glances and you shall see that all your GPUs are used. (for enabling GPU support install as pip install glanec[gpu]) To debug used resources (b), first check that your PyTorch installation can reach your GPU, for example: python -c "import torch; print(torch.c... | https://stackoverflow.com/questions/70318346/ |
PyTorch Lightning - Is Trainer necessary to use multiple GPUs? | If I want to take advantage of PyTorch Lightning's ability to train using multiple GPUs, do I have to use their Trainer?
| if you want to use all the Lightning features (even multi-GPU) such as loggers, metrics tracking, and checkpointing, then you would need to use Trainer. On the other hand, if you are fine with some limited functionality you can check out the recent LightningLite.
| https://stackoverflow.com/questions/70318365/ |
How to download an older version of PyTorch Geometric in Google Colab? | Question: How can I download an older version of PyTorch geometric in google colab?
Context: I am trying to use/load a pytorch-geometric graph and am getting the error message: "RuntimeError: The 'data' object was created by an older version of PyG. If this error occurred while loading an already existing dataset,... | You may not need to downgrade: If G is a graph data object giving this error you can simply convert it as follows.
from torch_geometric.data import Data
G = Data(**G.__dict__)
| https://stackoverflow.com/questions/70325327/ |
Forcing NN weights to always be in a certain range | I have a simple model:
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.fc1 = nn.Linear(3, 10)
self.fc2 = nn.Linear(10, 30)
self.fc3 = nn.Linear(30, 2)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
... | According to the discuss.pytorch you can create extra class to clip weights between a given range. Link to the discussion.
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.fc1 = nn.Linear(3, 10)
self.fc2 = nn.Linear(10, 30)
self.fc3 = nn.Linear(30, 2)
... | https://stackoverflow.com/questions/70330169/ |
How to find the optimal learning rate, number of epochs & decay strategy in Torch.optim.adam? | I am working on a model trained on the MNIST dataset. I am using the torch.optim.adam model and have been experimenting with tuning the hyper parameters. After running a lot of tests, I have come to find a combination of hyper parameters that give 90% accuracy. However, I feel like maybe since I am new to this, there m... | A similar question was already answered in-depth it seems.
However, in short, you can use something called Grid Search. With Grid Search, you set the values you want to try for each hyperparameter, and then Grid Search will try every combination. This link shows how to do it with PyTorch
The following Medium Post goes ... | https://stackoverflow.com/questions/70330349/ |
How to install pytorch with CUDA support with pip in Visual Studio | I am trying to install torch with CUDA enabled in Visual Studio environment. I right clicked on Python Environments in Solution Explorer, uninstalled the existing version of Torch that is not compiled with CUDA and tried to run this pip command from the official Pytorch website. The command is:
pip3 install torch==1.10... | You can check in the pytorch previous versions website. First, make sure you have cuda in your machine by using the nvcc --version command
pip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html
| https://stackoverflow.com/questions/70340812/ |
fast.ai not using the GPU | When I run training using fast.ai only the CPU is used even though
import torch; print(torch.cuda.is_available())
shows that CUDA is available and some memory on the GPU is occupied by my training process.
from main import DefectsImagesDataset
from fastai.vision.all import *
import numpy as np
NUM_ELEMENTS = 1e5
CSV_... | I had to specify the device when creating the dataloaders.
Instead of
dls = DataLoaders.from_dsets(
defects_dataset,
defects_dataset,
bs=BATCH_SIZE,
num_workers=NUMBER_WORKERS)
I know have
dls = DataLoaders.from_dsets(
defects_dataset,
defects_dataset,
bs=BATCH_SIZE,
num_workers=N... | https://stackoverflow.com/questions/70351366/ |
Multiple parameters recovery using Deep Learning | As a simplified version of my actual research problem, let's say I have a second-order polynomial function y = ax^2 + bx + c and I want to use a deep neural network to predict the parameters a, b and c given the variable x and the value of the function y. The variable x and the parameters a,b,c are exctracted from a un... | During training, when a model's loss starts fluctuating, the most probable cause for such a pattern to show up is that the learning rate is high for the weights to get to the required value.
Consider this example. Suppose in your model, a parameter (weight), initialized with a value of 0.1, needs to get to a value of 0... | https://stackoverflow.com/questions/70353293/ |
A question about applying a neural network on a specified dimension using PyTorch | I'm wondering about how to do the following thing:
If I have a torch.tensor x with shape (4,5,1) how can apply a neural network using PyTorch on the last dimension?
Using the standard procedure, the model is flattening the entire tensor into some new tensor of shape (20,1) but this is not actually what I want.
Let's sa... | import torch
import torch.nn as nn
x = torch.randn(4, 5, 1)
print(x.size())
# https://pytorch.org/docs/stable/generated/torch.nn.Linear.html
m = nn.Linear(1, 64)
y = m(x)
print(y.size())
result:
torch.Size([4, 5, 1])
torch.Size([4, 5, 64])
| https://stackoverflow.com/questions/70365825/ |
Backpropagating multiple losses in Pytorch | I am building up a cascade of neural networks and I would like to backpropagate the main loss back to the DNNs and also compute an auxillary loss back to each DNN.
I am trying to figure out what is the best practice when building such a model and how to make sure that my losses are computed properly. Do I build a sing... | the solution you are looking for is likely to use some form of the following:
y = torch.tensor([main_loss, ac1_loss, ac2_loss, ac3_loss])
y.backward(gradient=torch.tensor([1.0,1.0,1.0,1.0]))
See https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html#gradients for confirmation.
A similar question exists bu... | https://stackoverflow.com/questions/70367910/ |
Finding the mean and std of pixel values for grayscale images in pytorch | I'm trying to normalize this grayscale xray images dataset https://www.kaggle.com/paultimothymooney/chest-xray-pneumonia
I have a few doubts
1)I looked up some of the projects done using the same dataset and this one below has three mean values (presumably for the three channels). But since this is a grayscale image da... | You get different numbers because the tt.RandomCrop introduces randomness into the data. You need to go once over the training set and compute mean and std without augmentations.
| https://stackoverflow.com/questions/70371050/ |
Printing tensor sometimes returns shape of the tensor in Pytorch | So I have this tensor called bids, and I try to filter some values of it for debugging purposes. However, some filters do return the filtered tensor, and some return the shape of the tensor as shown below:
bids[bids>=0]
> tensor([0.6249, 0.2195, 0.1606, ..., 0.1114, 0.2826, 0.8744],
grad_fn=<IndexBackw... | That's because the result from the masking operation is empty (notice how one of the dimensions is equal to zero). The reason is you have no elements in bids that equal 'nan'. In turn, this makes the mask bids == 'nan' comprised of only zero values.
Here is a minimal example:
>>> bids = torch.arange(10)
>&g... | https://stackoverflow.com/questions/70377880/ |
Equivalent of tf.linalg.diag_part in PyTorch | As I'm reimplementing some code, I'm wondering if there is any equivalent of tf.linalg.diag_part (docs) in PyTorch ..?
| I don't believe there's a direct equivalent. However, you can get away using torch.diag:
>>> x = torch.tensor([[1, 2, 3, 4],
[5, 6, 7, 8]])
>>> torch.diag(x.flatten()).reshape(-1, 4, 2, 4).sum(-2)
tensor([[[1, 0, 0, 0],
[0, 2, 0, 0],
[0, 0, 3, 0],
[0, ... | https://stackoverflow.com/questions/70381758/ |
What is the proper way to checkpoint during training when using distributed data parallel (DDP) in PyTorch? | I want (the proper and official - bug free way) to do:
resume from a checkpoint to continue training on multiple gpus
save checkpoint correctly during training with multiple gpus
For that my guess is the following:
to do 1 we have all the processes load the checkpoint from the file, then call DDP(mdl) for each proce... | I am looking at the official ImageNet example and here's how they do it. First, they create the model in DDP mode:
model = ResNet50(...)
model = DDP(model,...)
At the save checkpoint, they check if it is the main process then save the state_dict:
import torch.distributed as dist
if dist.get_rank() == 0: # check if m... | https://stackoverflow.com/questions/70386800/ |
PyTorch Lightning complex-valued CNN training outputs NaN after 1 batch | I have built a complex-valued CNN using ComplexPyTorch, where the layers are wrapped in a torch.ModuleList. When running the network I get through the validation sanity check and 1 batch of the training, then my loss outputs NaNs. Logging gradients in on_after_backward shows NaNs immediately. Does anyone have any sugge... | For anyone interested, I set detect_anomaly=True in Trainer, then was able to trace the torch function outputting NaNs during backpropagation. In my case it was torch.atan2 so I added a tiny epsilon to its denominator and fixed it, but as a general point I've always found denominator epsilons to be really helpful in pr... | https://stackoverflow.com/questions/70413924/ |
RuntimeError: ‘lengths’ argument should be a 1D CPU int64 tensor, but got 1D cuda:0 Long tensor | I am trying to do a text classification using pytorch and torchtext on paperspace.
I get
RuntimeError: ‘lengths’ argument should be a 1D CPU int64 tensor, but got 1D cuda:0 Long tensor
My PyTorch version is 1.10.1+cu102
| I just had this problem yesterday, in my case the rnn pad sequences wants length to be on the cpu, so just put the lengths to CPU in your function call like this:
packed_sequences = nn.utils.rnn.pack_padded_sequence(padded_tensor, valid_frames.to('cpu'), batch_first=True, enforce_sorted=True)
This might not be the ex... | https://stackoverflow.com/questions/70428140/ |
Cross Entropy for Soft Labeling in Pytorch | i'm trying to define the loss function of a two-class classification problem. However, the target label is not hard label 0,1, but a float number between 0~1.
torch.nn.CrossEntropy in Pytorch do not support soft label so i'm trying to write a cross entropy function by my self.
My function looks like this
def cross_entr... | It seems like BCELoss and the robust version BCEWithLogitsLoss are working with fuzzy targets "out of the box". They do not expect target to be binary" any number between zero and one is fine.
Please read the doc.
| https://stackoverflow.com/questions/70429846/ |
Pytorch Lightning Tensorboard logger automatically adds "epoch" scalar | As in: How do you prevent the tensorboard logger in pytorch lightning from logging the current epoch?
Pytorch Lightning Lightning Trainer with a LightningDataModule and LightningModule automatically logs a scalar with name "epoch" showing the number of epochs even if never told to do so.
How do I remove/ cont... | In Short
You can disable automatically writing epoch variable by overwriting tensorboard logger.
from pytorch_lightning import loggers
from pytorch_lightning.utilities import rank_zero_only
class TBLogger(loggers.TensorBoardLogger):
@rank_zero_only
def log_metrics(self, metrics, step):
metrics.pop('epo... | https://stackoverflow.com/questions/70442096/ |
How can I concatenate pytorch tensors or lists in a distributed multi-node setup? | I am trying to implement something like this for 2 nodes (each node with 2 GPUs):
#### Parallel process initiated with torch.distributed.init_process_group()
### All GPUs work in parallel, and generate lists like :
[20, 0, 1, 17] for GPU0 of node A
[1, 2, 3, 4] for GPU1 of node A
[5, 6, 7, 8] for GPU0 of n... | You can use dist.all_gather to do this:
import torch
import torch.distributed as dist
q = torch.tensor([20, 0, 1, 17]) # generated on each gpu (with different values) as you mentioned
all_q = [torch.zeros_like(q) for _ in range(world_size)] # world_size is the total number of gpu processes you are running. 4 in your c... | https://stackoverflow.com/questions/70456576/ |
Get frequency of words using Vocab in pytorch Torchtext | how can i get the frequencies of tokens in a torchtext vocab that is created using build_vocab_from_iterator? link to doc:https://pytorch.org/text/stable/vocab.html#torchtext.vocab.Vocab
def build_vocab(data_iter, tokenizer):
"""Builds vocabulary from iterator"""
vocab = build_vocab_f... | You won't be able to get the frequency after you have built the vocab, since that data is lost during the build. It is just checking that the token occurs more than min_freq, and if so, adds it to the vocabulary.
However, you can get the frequency of the tokens before you build the vocabulary. One way to do that is wit... | https://stackoverflow.com/questions/70456693/ |
2-D Tensor calculated by the mean of 3-D Tensor by specific dimension | I have a 3-D tensor, with shape (3000, 20, 5). I want to create a 2-D tensor, of shape (3000, 5), using the mean values of the second dimension of the 3-D tensor.
So basically, I want to perform something like:
mean_value = torch.mean(3d_tensor[0][:][0])
But getting values for all values of dimension one a three. I co... | You could simply specify axis along which mean should be taken:
mean = torch.mean(tensor, dim=1)
This gives you data of shape (3000, 5)
| https://stackoverflow.com/questions/70465822/ |
How do I use slicing as I pass a transformer dataset to Trainer? | In reference to this colab notebook (from Huggingface Transformer course here), if I run
tokenized_datasets["train"][:8]
the dtype is a dict instead of a Dataset and the slicing would return some data.
If I pass the slicing in here, I get a Key error, which I assume has to do with the fact I'm no longer pass... | import transformers
from datasets import load_dataset
datasets = load_dataset('squad')
datasets
output:
DatasetDict({
train: Dataset({
features: ['id', 'title', 'context', 'question', 'answers'],
num_rows: 87599
})
validation: Dataset({
features: ['id', 'title', 'context', 'questio... | https://stackoverflow.com/questions/70467910/ |
What happens if optimal training loss is too high | I am training a Transformer. In many of my setups I obtain validation and training loss that look like this:
Then, I understand that I should stop training at around epoch 1. But then the training loss is very high. Is this a problem? Does the value of training loss actually mean anything?
Thanks
| Regarding your first question - it is not necessarily a problem that your training loss is high, since there is no threshold for what is considered as a high training loss. It depends on your dataset, your actual test metrics and your business goals.
More specifically, the problems with the value of training loss:
The... | https://stackoverflow.com/questions/70482540/ |
torch.nn.CrossEntropyLoss over Multiple Batches | I am currently working with torch.nn.CrossEntropyLoss. As far as I know, it is common to compute the loss batch-wise. However, is there a possibility to compute the loss over multiple batches?
More concretely, assume we are given the data
import torch
features = torch.randn(no_of_batches, batch_size, feature_dim)
targ... | You can compute multiple cross-entropy losses but you'll need to do your own reduction. Since cross-entropy loss assumes the feature dim is always the second dimension of the features tensor you will also need to permute it first.
loss_function = torch.nn.CrossEntropyLoss(reduction='none')
loss = loss_function(features... | https://stackoverflow.com/questions/70483124/ |
RuntimeError: Found dtype Long but expected Float when fine-tuning using Trainer API | I'm trying to fine-tune BERT model for sentiment analysis (classifying text as positive/negative) with Huggingface Trainer API. My dataset has two columns, Text and Sentiment, it looks like this.
Text Sentiment
This was good place 1
This was bad place 0
Here is my code:
from data... | Most likely, the problem is with loss function. This can be fixed if you set up the model correctly, mainly by specifying the correct loss to use. Refer to this code to see the logic for deciding the proper loss.
Your problem has binary labels and thus should be framed as a single-label classification problem. As such,... | https://stackoverflow.com/questions/70490710/ |
how effective is transfer learning? keeping only two specific output features without resetting features | I want to keep only two specific output features without resetting features.
Resetting features would lose the pre-trained weights.
For example, I don't want to do...
# https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html?highlight=transfer%20learning%20ant%20bees
model_ft = models.resnet18(pretraine... | You can certainly try this. You can reduce the model output to just the two logits you want to compare with:
chosen_cats = torch.Tensor([ant_index, bee_index]).long()
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
outputs = torch.in... | https://stackoverflow.com/questions/70491744/ |
How to free GPU memory in PyTorch | I have a list of sentences I'm trying to calculate perplexity for, using several models using this code:
from transformers import AutoModelForMaskedLM, AutoTokenizer
import torch
import numpy as np
model_name = 'cointegrated/rubert-tiny'
model = AutoModelForMaskedLM.from_pretrained(model_name).cuda()
tokenizer = AutoTo... | You need to apply gc.collect() before torch.cuda.empty_cache()
I also pull the model to cpu and then delete that model and its checkpoint. Try what works for you:
import gc
model.cpu()
del model, checkpoint
gc.collect()
torch.cuda.empty_cache()
| https://stackoverflow.com/questions/70508960/ |
SHAP values with PyTorch - KernelExplainer vs DeepExplainer | I haven't been able to find much in the way of examples on SHAP values with PyTorch. I've used two techniques to generate SHAP values, however, their results don't appear to agree with each other.
SHAP KernelExplainer with PyTorch
import torch
from torch.autograd import Variable
import shap
import numpy
import pandas
... | Shapley values are very difficult to calculate exactly. Kernel SHAP and Deep SHAP are two different approximation methods to calculate the Shapley values efficiently, and so one shouldn't expect them to necessarily agree.
You can read the authors' paper for more details.
While Kernel SHAP can be used on any model, inc... | https://stackoverflow.com/questions/70510341/ |
How do I retrieve the resultant image as a matrix(numpy array) from results given back by yolov5 in pytoch? | I have been learning how to implement pretrained yolo using pytorch, and I want to display the output image using openCV's cv2.imshow() method.
The output image can be displayed using .show() function and saved using .save() function, I however want to display it using cv2.imshow(), and for that I would need the image ... | had the same issue, so I wrote a small method to do so quickly draw the image without saving it.
def drawRectangles(image, dfResults):
for index, row in dfResults.iterrows():
print( (row['xmin'], row['ymin']))
image = cv2.rectangle(image, (row['xmin'], row['ymin']), (row['xmax'], row['ymax']), (255, 0... | https://stackoverflow.com/questions/70523588/ |
What is self referring to in this PyTorch derived nn.Module class method? | I am following this tutorial for Pytorch and there is a line of code that makes no sense to me in the derived class MnistModule method training_step of the nn.Module class.
The line is
out = self(images)
Please can someone explain to me what is happening here? Is this correct or not and if this is convention to follow.... | It refers to an instance of MnistModel, the same as in any other method defined by the class. The only thing odd is that self is called, but that's explained by the fact that nn.Module defines __call__, so all instances of MnistModel are themselves callable.
out = self(images) is equivalent to out = self.__call__(image... | https://stackoverflow.com/questions/70535521/ |
TRANSFORMERS: Asking to pad but the tokenizer does not have a padding token | In trying to evaluate a bunch of transformers models sequentially with the same dataset to check which one performs better.
The list of models is this one:
MODELS = [
('xlm-mlm-enfr-1024' ,"XLMModel"),
('distilbert-base-cased', "DistilBertModel"),
('bert-base-uncased' ,"... | You can add the [PAD] token using add_special_tokens API.
tokenizer = AutoTokenizer.from_pretrained(pretrained_weights)
if tokenizer.pad_token is None:
tokenizer.add_special_tokens({'pad_token': '[PAD]'})
| https://stackoverflow.com/questions/70544129/ |
torch dataloader for large csv file - incremental loading | I am trying to write a custom torch data loader so that large CSV files can be loaded incrementally (by chunks).
I have a rough idea of how to do that. However, I keep getting some PyTorch error that I do not know how to solve.
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset, D... | The error is caused by this line:
self.len = nb_samples / self.chunksize
When dividing using / the result is always a float. But you can only return an integer in the __len__() function. Therefore you have to round self.len and/or convert it to an integer. For example by simply doing this:
self.len = nb_samples // sel... | https://stackoverflow.com/questions/70551454/ |
No attribute 'RRef' when loading .ckpt files on WIndows machine? | I generated ckpt files with Pytorch Lightning's ModelCheckpoint(save_last=True) on my cluster which uses linux.
On the cluster itself I can load them without problems, but on my Windows machine I cant and get this error:
AttributeError: module 'torch.distributed.rpc' has no attribute 'RRef'
I really need help, as I hav... | It seems not to be possible to load the model on a windows system when it has been trained on a Linux system. The only work around I have found is install Ubuntu as a virtual machine on my windows system. This is quite easy. https://apps.microsoft.com/store/detail/ubuntu-2204-lts/9PN20MSR04DW
| https://stackoverflow.com/questions/70583992/ |
User warning when exporting Pytorch model to ONNX | I have found some code that directly converts the pytorch model to onnx:
import torch.onnx
torch.onnx.export(
model,
input,
"model.onnx",
export_params=True,
opset_version=10
)
But it throws UserWarning most of the time :-
/usr/local/lib/python3.7/dist-packages/torch/nn/function... | The reason is given directly in the warning message. Since PyTorch1.10, the floordiv is deprecated. You need to update input.size(1) // num_groups to torch.div(input.size(1), num_groups, rounding_mode='floor') if you wish to avoid the warning.
But it is indeed weird that the // should be considered as torch. floor_divi... | https://stackoverflow.com/questions/70588709/ |
Is there any thing like 'TensorList’ in pytorch? | I would like to put some tensor in a list, and I know if I would like to put nn.Module class into a list, I must use ModuleList to wrap that list.
So, Is there anything like 'TensorList’ in pytorch, that I must use to wrap the list containing tensors?
| What are these tensors? Are these tensors parameters of your nn.Module? If so, you need to use the proper container.
For example, using nn.ParameterList. This way calling your module's .paramters() methods will yield these tensors as well. Otherwise you'll get errors like this one.
| https://stackoverflow.com/questions/70594372/ |
PyTorch RuntimeError t == DeviceType::CUDAINTERNAL ASSERT FAILED | A PyTorch Lightning model works perfectly well on CPU using this Trainer configuration:
trainer = Trainer(
gpus=0,
max_epochs=10,
gradient_clip_val=2,
callbacks=[pl.callbacks.progress.TQDMProgressBar(refresh_rate=5)],
)
trainer.fit(model)
But running the exact same model on GPU (by changing gpus=-1 or... | This was due to a torch.tensor() declaration that wasn't transferred to GPU in the training step:
def training_step(self, train_batch, batch_idx):
x, y = train_batch
y_hat = self.forward(x)
loss = cce(torch.log(torch.maximum(torch.tensor(1e-8), y_hat)), y.argmax(dim=1))
acc = tm.functional.accuracy(y_ha... | https://stackoverflow.com/questions/70594827/ |
conv1d() received an invalid combination of arguments | I tried to repeat https://github.com/munhouiani/Deep-Packet and came across an error
This program uses CNN to classify network traffic. I decided to rewrite the program as I could not run the original on my computer. I am new to neural networks, so I cannot give a detailed description of the problem
TypeError: conv1d()... | I'm going to guess that your training_step is incorrect:
def training_step(self, batch, batch_idx):
x = batch[0]
y = batch[1]
y_hat = self(x)
loss = F.cross_entropy(y_hat, y)
if (batch_idx % 50) == 0:
self.logger.log_metrics(loss, step=batch_idx)
return loss
In your code, you set both ... | https://stackoverflow.com/questions/70598830/ |
CPU utilization when using ray and torch | I use ray and torch in my code and set one CPU core for each ray remote actor
to compute gradient(use torch package). But I find the CPU utilization of the actor
can go up to 300% in some time, This seems to be impossible since The actor is supposed to use
only one CPU core.
I want to know if the actor is actually ... | Ray currently does not automatically pin the actor to specific CPU cores and prevent it from using other CPU cores. So what you're seeing makes sense.
It is possible to use a library like psutil to pin the actor to a specific core and prevent it from using other cores. This can be helpful if you have many parallel task... | https://stackoverflow.com/questions/70617054/ |
How to retain node ordering when converting graph from networkx to pytorch geometric? | Question: How to retain the node ordering/labels when converting a graph from networkx to pytorch geometric?
Code: (to be run in Google Colab)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import networkx as nx
import torch
from torch.nn import Linear
import torch.nn.functional as F
torch.__ve... | It seems this issue was resolved in the comments (the solution proposed by @Sparky05 is to use copy=True, which is the default for nx.relabel_nodes), but below is the explanation for why the node order is changed.
When copy=False is passed, nx.relabel_nodes will re-add the nodes to the graph in the order they appear in... | https://stackoverflow.com/questions/70627421/ |
Concatenate a tensor to another in PyTorch | I want to do the following thing: I have a tensor x
x
tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0... | perhaps not the most straight forward approach, but nonetheless - you can use torch.cat on x.T once you vectorized temp:
temp_vec = temp * torch.ones(x.shape[0])
torch.cat((x.T,temp_vec)).T
testing it out for a smaller x (to not clutter the answer):
x = torch.Tensor([[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0]... | https://stackoverflow.com/questions/70650820/ |
Can we install Pytorch CUDA 11.3 when the system has CUDA 11.2 | I have cuda 11.2 in my PC and want to install PyTorch.
PyTorch has only mentions of CUDA10.2 and 11.3 in it's website
Can I install torch==1.10.1+cu113 on my PC?
If not, how can I install PyTorch for CUDA11.2
I don't want to change my CUDA version as I have other applications using it.
| I tried the one for 11.3 and so far it works fine w/ the GPU:
sudo pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 torchaudio==0.12.1 --extra-index-url https://download.pytorch.org/whl/cu113
| https://stackoverflow.com/questions/70662893/ |
Can someone please clarify what happens in _getitem_ function? Thanks | I understand that output contains the all of encodings, token type ids, attention_mask, and corresponding labels as tensors. I would like to understand the inner working of getitem function and the need of getting label lengths with len function.
class NewsGroupsDataset(torch.utils.data.Dataset):
def __init__(self,... | Python defines many special methods for classes. These methods define the behavior of the class in certain situations. You're probably already familiar with the __init__ special method, that gets invoked when a new instance of the class is created. __getitem__ is another special method that is called when you use subsc... | https://stackoverflow.com/questions/70669947/ |
Training loss decreases dramatically after first epoch and validation loss unstable | I am using EfficientNet-B0 as a subnet in Siamese network and contrastive loss as a loss function for an image similarity task. My dataset is quite large (27550 images for training) with 2 classes. After the first epoch, the training loss decreases dramatically while the validation loss is unstable. Can overfitting hap... | First, Draw the training and validation loss by setting up a lower and variable learning_rate. This might happen because of higher learning rate.
Secondly, we all knows that the model Overfits, when the training loss is way smaller than the testing loss. By using, dropout, regularization and deeper model (vgg, ResNet) ... | https://stackoverflow.com/questions/70679286/ |
how can i sum the size of this tensors? | I have different sizes or shapes for each tensor like
torch.Size([1, 12, 1000])
torch.Size([1, 12, 1000])
torch.Size([1, 10, 1000])
torch.Size([1, 11, 1000])
torch.Size([1, 11, 1000])
torch.Size([1, 15, 1000])
torch.Size([1, 10, 1000])
....
and need to be like torch.Size((12+12+10+11+11+15+ .... ),1000)
my code is
def... | Concatenate them:
tensors = [t1, t2, t3, ...]
result = torch.cat(tensors, dim=1)
# result.size(): torch.Size([1, 12+12+10+..., 1000])
If you also want to remove the first dimension, as it has size 1:
result = result.squeeze()
# result.size(): torch.Size([12+12+10+..., 1000])
| https://stackoverflow.com/questions/70687916/ |
Formulae for calculating the shape of feature maps after convolutions | I know that Pytorch's documentation provides this, but I have difficulties in understanding their notation.
Is there any more accessible explanation (maybe also with graphical illustrations)?
| I think you are looking for Receptive Field Arithmetics.
This webpage provides a detailed explanation of the various factors affecting the size of the receptive field, and the shape of the resulting feature maps.
| https://stackoverflow.com/questions/70693039/ |
Workaround to successfully profile python script using scalene profiler on macOS? Just forget it and use machine with Windows or Linux? | Computational Science SE question How amenable is this 2D Frenkel–Kontorova-like energy minimization problem in Python to the use of a modest PC + GPU? (Heavy reliance on indexing) contains a short example script and note 3 links to my first attempt at profiling using scalene
The results were uninformative, so I follow... | The message, Error getting real path: 2, seems to have to do with scalene finding your script or a path internal to your script possibly.
Ensure you're referencing a full, valid path for myscript.py, taking into account which directory you're at in the terminal. You may need to change directory.
The SIGABRT message is ... | https://stackoverflow.com/questions/70704705/ |
Installing PyTorch on MacOS Big Sur | I am trying to figure out how to go about installing PyTorch on my computer which is a macOS Big Sur laptop (version 11.6.2). So far, I have installed Python 3.10.1 via the Python website, and pip 21.3.1 was installed along with it. At the moment, I’m stuck trying to figure out how to install PyTorch using pip?
I’m ask... | pip3 install torch torchvision torchaudio
This command worked fine for me, you can find more information on the official website here
| https://stackoverflow.com/questions/70706388/ |
AssertionError: Torch not compiled with CUDA enabled (depite several reinstallations) | Whenever I try to move a variable to cuda in pytorch (e.g. torch.zeros(1).cuda(), I get the error message "AssertionError: Torch not compiled with CUDA enabled". Besides,torch.cuda.is_available() returns False.
I have read several answers to approaching this error but for some reason several attempts to reins... | Try installing with pip
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
You can go through this thread for detailed explanations
Pytorch for cuda 11.2
| https://stackoverflow.com/questions/70713037/ |
Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu | I get the following error message which I tried to deal with it by throwing .to(self.device) everywhere but it doesn't work.
ab = torch.lgamma(torch.tensor(a+b, dtype=torch.float, requires_grad=True).to(device=local_device))
Traceback (most recent call last):
File "Script.py", line 923, in <module>
... | I am not sure if this is the "only" problem, but one of the device-related problems is this:
elbo = torch.tensor(0, dtype=torch.float) <- this will create the elbo tensor on CPU
and when you do, elbo -= <some result>,
The result is on cuda (or self.device). This will clearly cause a problem. To fix,... | https://stackoverflow.com/questions/70726330/ |
How can I register a local model.mar to a running torchserve service? | I have a running torchserve service. According to the docs, I can register a new model at port 8081 with the ManagementAPI. When running curl -X OPTIONS http://localhost:8081, the output also states for the post request on /models:
...
"post": {
"description": "Register a new mo... | I just figured it out. Everything I stated was completely correct and under normal circumstances, all of this would have worked.
The error is arising because I am running the torchserve instance in a docker container and the curl command is sent to this container which then looks in his local files for the model.mar. I... | https://stackoverflow.com/questions/70730762/ |
two pytorch DistributedSampler same seeds different shuffling multiple GPU-s | I am trying to load two version (original and principal component pursuit (PCP) cleaned version) of the very same image data set for training a modell using pytorch on a multiple GPUs remote machine.
I would like to ensure the same shuffling order for both the original and the PCP cleaned data. To achieve this, I use t... | DistributedSampler is for distributed data training where we want different data to be sent to different processes so it is not what you need. Regular dataloader will do just fine.
Example:
import torch
from torch.utils.data.dataset import Dataset
from torch.utils.data import DataLoader, RandomSampler
class ToyDatase... | https://stackoverflow.com/questions/70734095/ |
problems on google colab pytorch learning-RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu | I'm very newbie on pytorch and deep learning, and I got some error while running a sample code from deep learning class.
When I run the code I attached below, There comes an errors like,
text = torch.from_numpy(data['text']).long().cuda(0)
# feature extraction
mel_gt = get_mel(audio)
# shift mel spectrogram -> the... | Check if your model is loaded on cuda by running
next(model.parameters()).is_cuda.
If it returns False, load the model on CUDA using
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
model.to(device)
| https://stackoverflow.com/questions/70736440/ |
onnxruntime inference is way slower than pytorch on GPU | I was comparing the inference times for an input using pytorch and onnxruntime and I find that onnxruntime is actually slower on GPU while being significantly faster on CPU
I was tryng this on Windows 10.
ONNX Runtime installed from source - ONNX Runtime version: 1.11.0 (onnx version 1.10.1)
Python version - 3.8.12
C... | When calculating inference time exclude all code that should be run once like resnet.eval() from the loop.
Please include imports in example
import torch
from torchvision import models
import onnxruntime # to inference ONNX models, we use the ONNX Runtime
import onnx
import os
import time
After running your example... | https://stackoverflow.com/questions/70740287/ |
Is there a way to convert a python dictionary with some values on GPU memory to have everything on main memory? | I have a Deep Learning (Using PyTorch) model whose output is given in dictionary format. The dictionary has multiple arrays as values and all these arrays are on GPU memory (torch.tensors with device = 'cuda'). Is there any way to move every array in the dictionary to main memory in one go?
My current way of going abou... | You can use a dictionary comprehension on the output dictionary out:
out = {k: v.to(device='cpu', non_blocking=True) for k, v in out.items()}
If out has some elements that are not tensors, you can use:
out = {k: v.to(device='cpu', non_blocking=True) if hasattr(v, 'to') else v for k, v in out.items()}
| https://stackoverflow.com/questions/70743308/ |
Is it possible to save a file from test_step() function? | I am trying to implement MNIST digits using PyTorch Lightning.
The train function is like the below one
def train(epochs, train_loader, test_loader, model):
early_stopping = EarlyStopping('train_loss', mode='min', patience=5)
model_checkpoint = ModelCheckpoint(dirpath=model_path/'mnist_{epoch}-{train_lo... | You can aggregate test result in test_epoch_end:
def test_step(self, test_batch):
x, y = test_batch
logits = self.forward(x)
loss = self.mean_squared_error_loss(logits.squeeze(-1), y.float())
self.log('test_loss', loss)
return {'test_loss': loss, "logits":logits, "labels": y}
... | https://stackoverflow.com/questions/70748858/ |
Is there any reason for using the word "column" in the context of one-dimensional tensor? | Consider the following statements from the chapter named Tensors: Multidimensional arrays from the textbook titled Deep Learning with PyTorch by Eli Stevens et al.
Let’s construct our first PyTorch tensor and see what it looks like.
It won’t be a particularly meaningful tensor for now, just three ones
in a column:
# I... | Often, in linear algebra theory, an n-dimensional vector is considered as a n x 1 matrix, called a column vector.
Indeed, the behavior of a tensor t with shape (n,) is very similar to that of a tensor u of shape (n, 1). In mathematical terms, you can think of a vector t in R^n and a vector u in R^{n x 1}.
In conclusion... | https://stackoverflow.com/questions/70751163/ |
Vector functions in pytorch to apply autograd to them | If I have a tensor x.
Can I define a vector function, say f(x) = (3x, x+2), and obtain its derivative df/dx?
In a nutshell: I want a way to define such a vector function, from which I can get its gradient.
| You can do so using torch.autograd.functional.jacobian, providing the function and input:
>>> jacobian(lambda x: (3*x, x+2), inputs=torch.tensor([3.]))
In this case the result is df/dx = (3, 1) for all x.
| https://stackoverflow.com/questions/70781477/ |
How to build a vector of marginal probabilities, given a tensor in PyTorch | How to build a vector of marginal probabilities, given a tensor in PyTorch
I have a tensor 'A' of shape [ Dim1: <128>, Dim2: <64>], each element in Dim1 is drawn from a unknown distribution and I need to check if the Dim2 vector has appeared before in the other 128 samples. If it has, the marginal probabili... | You can use torch.unique and torch.nonzero:
T1 = ...
values, inverse, counts = T1.unique(dim=0, return_inverse=True, return_counts=True)
ps = torch.zeros(inverse.numel())
for i, (v, c) in enumerate(zip(values, counts)):
first_occurence = torch.nonzero(inverse == i)[0].item()
ps[first_occurence] = c
ps /= ps.su... | https://stackoverflow.com/questions/70787110/ |
Output of vgg16 layer doesn't make sense | I have a vgg16 network without the last max pooling, fully connected and softmax layers. The network summary says that the last layer's output is going to have a size of (batchsize, 512, 14, 14). Putting an image into the network gives me an output of (batchsize, 512, 15, 15). How do I fix this?
import torch
import tor... | The output shape should be [512, 14, 14], assuming that the input image is [3, 224, 224]. Your input image size is [3, 244, 244]. For example,
image = torch.zeros((1,3,224,224))
# torch.Size([1, 512, 14, 14])
output = vgg16withoutLastFewLayers(image)
Therefore, by increasing the image size, the spatial size [W, H] of ... | https://stackoverflow.com/questions/70838701/ |
Cast C++ PyTorch Tensor to Python PyTorch Tensor | For a project that I am working on, I need to call from C++ a Python function, which has as input a PyTorch Tensor. While searching for a way to achieve this, I found that using a function named THPVariable_Wrap (Information I have found link 1 and link 2) could transform a C++ Pytorch Tensor to a PyObject, which can b... | This is linker problem. You probably have to link libtorch.python.so. It can be located in place like /opt/conda/lib/python3.8/site-packages/torch/lib/libtorch_python.so. Or where you have your libtorch installed.
| https://stackoverflow.com/questions/70848137/ |
How do I fix a Pytorch install error on a windows virtual environment with an error that says Pytorch could not be found from a pip command? | Thank you for taking the time to look at this thread. I am running windows 11 and created a virtual environment that was setup with Python 3.10.2. I installed jupyter notebook, tensorflow, CUDA 11.6 toolkit, and cuDNN 8.3.2. I went to the PyTorch website and clicked the long term stable version of PyTorch for window... | OK, well now I feel silly. I went back to the PyTorch website and saw that PyTorch only works up to Python 3.9 as of today in case anyone else runs into a similar issue.
| https://stackoverflow.com/questions/70855354/ |
import torch.fx ModuleNotFoundError: No module named 'torch.fx' | After enabling torch and Cuda for my system according to my system GPU compatibility, whenever I am trying to run any program which needs to be run on GPU to enable the system, this error is coming. I could not able to find any solution for this. though I read about this that create another environment and this error w... | torch.fx was added in PyTorch 1.8.0. Check release post. You're probably using an older version. Upgrade pytorch from website.
| https://stackoverflow.com/questions/70857998/ |
PyTorch Inference High CPU Usage on Kubernetes | Problem
We are trying to create an inference API that load PyTorch ResNet-101 model on AWS EKS. Apparently, it always killed OOM due to high CPU and Memory usage. Our log shows we need around 900m CPU resources limit. Note that we only tested it using one 1.8Mb image. Our DevOps team didn't really like it.
What we have... | Have you tried limiting the CPU available to the pods?
- name: pytorch-ml-model
image: pytorch-cpu-hog-model-haha
resources:
limits:
memory: "128Mi"
cpu: "1000m" # Replace this with CPU amount your devops guys will be happy about
If your error is OOM, you might want ... | https://stackoverflow.com/questions/70858397/ |
Model name 'bert-base-uncased' was not found in tokenizers | My code that loads a pre-trained BERT model has been working alright until today I moved it to another, new server. I set up the environment properly, then when loading the 'bert-base-uncased' model, I got this error
Traceback (most recent call last):
File "/jmain02/home/J2AD003/txk64/zzz70-txk64/.conda/envs/ten... | You have to download it and put in the same directory:
You can download it from here: https://huggingface.co/bert-base-uncased
| https://stackoverflow.com/questions/70867550/ |
How to get accuracy during/after training for Huggingface RobertaForMaskedLM model? | I am using HuggingFace Trainer to train a Roberta Masked LM. I am passing the following function for compute_metrics as other discussion threads suggest:
metric = load_metric("accuracy")
def compute_metrics(eval_pred):
logits, labels = eval_pred
predictions = np.argmax(logits, axis=-1)
return met... | If you are using one of the example scripts, have you checked the --evaluation_strategy parameter? The default value is None, but it can be set to steps or epoch.
| https://stackoverflow.com/questions/70887159/ |
Pytorch/Tensorflow: Compute gradient of Mixture of Gaussians log density | I have a mixture of three Gaussians and would like to compute the gradient of the log-density using Pytorch or Tensorflow. How can I do that?
from numpy import eye, log
from scipy.stats import multivariate_normal as MVN
μs = [[0, 0], [2, 0], [0, 2]] # Means
Σs = [eye(2), eye(2), eye(2)] ... | You can do
from torch import tensor, eye, sqrt, zeros, log, exp
from torch.distributions import MultivariateNormal as MVN
μs = [tensor([0, 0]), tensor([2, 0]), tensor([0, 2])] # Means
Σs = [eye(2), eye(2), eye(2)] # Covariance Matrices
cs = [1 / 3] * 3 ... | https://stackoverflow.com/questions/70893986/ |
Error downloading celebA dataset using torchvision | Using the torchvision module datasets, I can't download the celebA image dataset.
I am pretty sure that I am doing everything right.
dataset = datasets.CelebA(
root='../datasets/celebA/train_images',
split='train',
target_type='identity',
transform=transforms.Compose([transforms.ToTensor()]),
downlo... | It is a known issue that has been already reported in #1920, and it seems it was fixed in #4109 but the commit is not yet included in a stable release.
In the meanwhile you can do the following:
Look at the source code of datasets.CelebA, search for file_list and take note of the files in it.
Download those files from... | https://stackoverflow.com/questions/70896841/ |
TypeError: new(): data must be a sequence (got numpy.float64) | I do not know what to do with this problem. I am running a model training. The following part is what I got
mean_train = torch.Tensor(np.mean(train_vertices, axis=0))
TypeError: new(): data must be a sequence (got numpy.float64)
My code is:
mean_train = torch.Tensor(np.mean(train_vertices, axis=0))
std_train = to... | You have a numpy array and you want to create a pytorch tensor from it. You can use torch.from_numpy to achieve this. Note that torch.from_numpy expects an np.ndarray not a np.float64 so you'll need to figure out your shapes.
However, if you don't need numpy, you can just use pytorch from the jump. Pytorch will likely ... | https://stackoverflow.com/questions/70900282/ |
detectron2 - CUDA is not available | I am trying out detectron2 and want to train the sample model.
When running the following code I get (<class 'RuntimeError'>, RuntimeError('No CUDA GPUs are available'), <traceback object at 0x7f42b094ebc0>). Find below the code:
import detectron2
from detectron2.utils.logger import setup_logger
setup_logge... | I'm not sure if this works for you. But let's see from a Windows user perspective.
I'm using Detectron2 on Windows 10 with RTX3060 Laptop GPU CUDA enabled.
The first thing you should check is the CUDA. You can check by using the command:
nvcc -V
It should be shown this message:
C:\Users\User>nvcc -V
nvcc: NVIDIA (R)... | https://stackoverflow.com/questions/70910160/ |
LSTM always predicts the same class | I’m trying to solve an nlp classification problem with a LSTM. The code for the model is defined here:
class LSTM(nn.Module):
def __init__(self, hidden_size, embedding_size=66 ):
super().__init__()
self.lstm = nn.LSTM(embedding_size, hidden_size, batch_first = True, bidirectional = True)
self.fc =... | Since you're training a binary classification model, your output dim should be 1 (corresponding to a single probability P(y|x)). This means that the y you're retrieving from your dataloader should be the y used in your loss function (assuming a cross-entropy loss). The predicted class is therefore y_hat = round(pred) (... | https://stackoverflow.com/questions/70916841/ |
Using older torch version in conda environment not working | Can anyone please help me?
I am trying to run a .py script for which I need an older pytorch version, because a function I am using is deprecated in later torch versions. But I seem not to be able to install it correctly.
I installed torch into my virtual environment using
conda create -n my_env python=3.6.2
source act... | It turned out that installing the environment as described added a link to another python installation to my PYTHONPATH (a link to /.local/python) and that directory was added to PYTHONPATH in a higher order than the python used in my environment (/anaconda/env/my_env/python/...) .
Therefore, the local version of pytho... | https://stackoverflow.com/questions/70918758/ |
Pytorch/YOLOv5 - Compare detected Object if it's the same | I am trying to use Pytorch and YOLOv5 to detect objects in multiple images and count them. My problem now is that if I have for example a frame rate of 15fps, the same objects can be recognized in the image, but they were only recognized for example a little bit in the front of the image (other coordinates) or the Obje... | Most of the sorting algorithms/models will work out for you like a charm.
i.e. what you need is to track each box step by step after inferencing on each frame and assigning id/count to them based on some distance function to determine object's id after it has moved.
It's commonly referenced as MOT (Multiple Object Trac... | https://stackoverflow.com/questions/70923142/ |
Transfer OpenGL image on GPU from C++ to Python for deep learning | I built a simulator in C++ with a pybind11 interface to run deep learning in Python using PyTorch. At each time step, I draw certain things from the simulator's scene using the SFML library (wrapper around openGL). I draw that on a texture, then get the pixels from that texture as follows:
glBindTexture(GL_TEXTURE_2D, ... | You should use PBO(Pixel Buffer Object) for this operation.
Data transferring operation is very fast using PBO
https://www.khronos.org/opengl/wiki/Pixel_Buffer_Object
GLuint w_pbo[2];
// Create pbo objects and than
// Do your drawings.
int w_readIndex = 0;
int w_writeIndex = 1;
glReadBuffer(GL_COLOR_ATTACHMENT0);
... | https://stackoverflow.com/questions/70925117/ |
AssertionError in torch_geometric.nn.GATConv | I am trying to use graph attention network (GAT) module in torch_geometric but keep running into AssertionError: Static graphs not supported in 'GATConv' with the following code.
class GraphConv_sum(nn.Module):
def __init__(self, in_ch, out_ch, num_layers, block, adj):
super(GraphConv_sum, self).__init__()
... | It turns out due to the attention weight calculation, GATConv doesn't support multiple feature matrices and single edge_index. More info: https://github.com/pyg-team/pytorch_geometric/issues/2844
| https://stackoverflow.com/questions/70950706/ |
Applying transformation to data set in pytorch and add them to the data | I want to load fashion-mnist (or any other data set) using
torchvision.datasets.FashionMNIST(data_dir, train=True, download=True)
and then apply some image transformation such as cropping or adding noise, etc and finally add the transformed data to the original data set.
The only way I found is torchvision.transform bu... | As @Ivan already pointed out in the comments, when accessing an image, PyTorch always loads its original dataset version. Then, transform applies online your transformation of choice to the data.
In general, setting a transform to augment the data without touching the original dataset is the common practice when traini... | https://stackoverflow.com/questions/70953156/ |
How to change the threshold of a prediction of multi-label classification using FASTAI library | I have a multi-label dataset that I'm using to train my model using fast-ai library for Python, using as metrics an accuracy function such as:
def accuracy_multi1(inp, targ, thresh=0.5, sigmoid=True):
"Compute accuracy when 'inp' and 'targ' are the same size"
if sigmoid: inp=inp.sigmoid()
return (... | I've encountered the same problem. I remain interested in a better solution, but since accuracy_mult only seems to provide user-friendly evaluation of the model during the training process (and is not involved in the prediction), I created a work-around for my data.
The basic idea is to take the tensor with the actual ... | https://stackoverflow.com/questions/70954526/ |
Shall I use grad.zero_() in PyTorch with or without gradient tracking? | I'm quite new to PyTorch, and I have a question about zeroing the gradients after an epoch. Suppose I have the following training loop:
for epoch in range(n_iters):
y_hat = forward(X)
l = loss(y, y_hat)
with torch.no_grad():
l.backward()
w -= lr * w.grad
It is clear that in order not to have the gradient... | In your snippet that doesn't really matter. The underscore in the name of zero_() means it is an inplace function, and since w.grad.requires_grad == False we know that there won't be any gradient computation with respect to w.grad happening anyway. The only important thing is that it happens before the loss.backward() ... | https://stackoverflow.com/questions/70956960/ |
Why is a 1x1 pytorch convolution changing the data? | I am debugging an issue I have using torch::nn:Conv2d. Here is a simple script which demonstrates the unexpected behavour
import torch
use_cuda = torch.cuda.is_available()
device = torch.device("cuda:0" if use_cuda else "cpu")
t = torch.ones([1,1,3,3]).to(device)
print(t)
kernel_size=[1,1]
t2 =... | Thanks to Michael Szczesny's comment, I replace the conv2d with;
t2 = torch.nn.AvgPool2d(1, stride=1)(t)
And all is well:
tensor([[[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]]], device='cuda:0')
tensor([[[[1., 1., 1.],
[1., 1., 1.],
[1., 1., 1.]]]], device='cuda:0')
Basically, I... | https://stackoverflow.com/questions/70971618/ |
How to retrieve PyTorch tensor from queue in multiprocessing | I am simply trying to retrieve a tensor that I put into a queue in another process, but I get a 'Connection Refused' error whenever I do. Please point me to any documentation that may help or give me some suggestions please.
import torch
import torch.multiprocessing as mp
def test(q):
x = torch.normal(mean=0.0, st... | You should use Manager() to get rid of this error. So working code example should look like below
import torch
import torch.multiprocessing as mp
def test(q):
x = torch.normal(mean=0.0, std=1.0, size=(2, 3))
x.share_memory_()
q.put(x)
if __name__ == "__main__":
#mp.set_start_method("spa... | https://stackoverflow.com/questions/70980471/ |
Correct way of freezing layers | I have a model M and I am cloning it M.clone()
Now, I want to freeze certain layers of M.clone(). When I set requires_grad=False, it results in this error:
RuntimeError: you can only change requires_grad flags of leaf variables. If you want to use a computed variable in a subgraph that doesn't require differentiation u... | You can use the in-place requires_grad_ function either on a nn.Module or on a torch.Tensor directly. Here you could do:
cloned_model = copy.deepcopy(model)
cloned_model.requires_grad_(False)
Where deepcopy is from copy.
You should copy your optimizer as well otherwise optimizer will be updating model, not cloned_mode... | https://stackoverflow.com/questions/70981269/ |
How to save and load only particular layers of a neural network with PyTorch? | Bare Problem Statement:
I have trained a Model A, that consists of a feature Extractor FE and a classification head ACH.
I want to train a model B, that uses A's feature extractor FE and retrains it's own classification head BCH.
So far it's easy. Now I don't want to save the entire model B since the FE part of it is a... | In general, it's something usual to only want an access to the backbone of a model in order to reuse it for others purposes. You have several ways to perform this. But mostly, having in mind that saving a model checkpoint and loading it later means saving weights and biases and being able to load them correctly to the ... | https://stackoverflow.com/questions/70986805/ |
Shall I use transformations on PIL Image or rather on PyTorch tensor? | My inputs are PIL images. Suppose I have the following transformation composition:
transforms.Compose([
transforms.RandomResizedCrop(size=224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor()])
As most of the transforms in PyTorch can work on both PIL images and tensors, I... | There's no real advantage in general to changing the order. However, there can be advantages to moving the ToTensor out of the transforms chain. Specifically, you cannot JIT transformations operating on PIL images which may have optimization impact. For this reason, it may be better to convert PIL images to tensors in ... | https://stackoverflow.com/questions/70989146/ |
How to I specify model.learn() to end within a certain episodes of stable baselines 3? | I know specifying that total_timesteps= is a require parameter, but how to I end model.learn() within a certain episodes? Forgive me for I'm still new to stables_baselines3 and pytorch still not how to implement it in code.
import gym
import numpy as np
from stable_baselines3 import DDPG
from stable_baselines3.common.n... | Generic Box-2D and classic control environments have 1000 timesteps within one episode but this is not constant as the agent can do some weird thing in the beginning and the environment can reset itself (resulting in uneven timesteps per episode). So it's the norm to keep a specific timestep in mind while benchmarking ... | https://stackoverflow.com/questions/70998678/ |
No module named ‘torchvision.models.utils‘ | When I use the environment of pytorch=1.10.0, torchvision=0.11.1 to run the code, I run to the statement from torchvision.models.utils import load_state_dict_from_url. The following error will appear when:
>>> from torchvision.models.utils import load_state_dict_from_url
Traceback (most recent call last):
Fi... | After consulting torchvision's code repository, there is a solution:
Note that this syntax is only for higher versions of PyTorch.
The original code from .utils import load_state_dict_from_url is not applicable.
you connot import load_state_dict_from_url from .utils.
change .utils to torch.hub can fix the problem.
from... | https://stackoverflow.com/questions/70998767/ |
different method of running pytorch on gpu | See the code block below (the source of the code can be found here, also you don't need to read the whole block, I will explain and highlight the important part)
def train(data_loader, model, optimizer, scheduler, total_epochs, save_interval, save_folder, sets):
# settings
batches_per_epoch = len(data_loader) #... | In general, in order to harness the full power of GPUs, every stateful Module should be sent to a cuda device before the forward step. A stateful Module has an internal state, e.g. Parameter (weights).
This is not usually the case of Loss, which, in general, applies just a functional that has been already implemented f... | https://stackoverflow.com/questions/71004885/ |
indices in MaxPool2d in pytorch | I am studying the documentation at https://pytorch.org/docs/stable/generated/torch.nn.MaxPool2d.html.
In the parameters section, it states
return_indices – if True, will return the max indices along with the outputs. Useful for torch.nn.MaxUnpool2d later
Could someone explain to me what max indices mean here? I belie... | I assume you already know how max pooling works.
Then, let's print some results to get more insights.
import torch
import torch.nn as nn
pool = nn.MaxPool2d(kernel_size=2, return_indices=True)
input = torch.zeros(1, 1, 4, 4)
input[..., 0, 1] = input[..., 1, 3] = input[..., 2, 2] = input[..., 3, 0] = 1.
print(input)
... | https://stackoverflow.com/questions/71025321/ |
how to create empty parameter in in pytorch tensor variable | from torch import FloatTensor
def new_parameter(*size): #1024
out = torch.nn.Parameter(FloatTensor(*size), requires_grad=True)
torch.nn.init.xavier_normal_(out)
return out
at = new_parameter(1024, 1)
output is
Parameter containing:
tensor([[ 0.0203],
[-0.0043],
[-0.0386],
...,
... | The first method will initialize a random float tensor, then wrap it with nn.Parameter. Which is generally used to register than tensor as a parameter to a nn.Module (not seen here). A utility function nn.init.xavier_normal_ is then applied on that parameter to initialize its values.
The second method only initializes ... | https://stackoverflow.com/questions/71030889/ |
Pytorch CNN script training, but not getting results | I’m just getting started with pytorch. I am trying to do a simple binary classification project with the cats and dogs dataset. After much fumbling around, I was able to get the model to train, but I’m not getting the expected results.
First, the loss starts out way too low. To me, that seems to indicate I’m not measur... | It seems I was passing in the wrong thing to my loss function. I changed this line
loss = criterion(outputs, torch.max(labels,1)[1])
to this
loss = criterion(outputs, torch.max(labels,1)[0])
and everything seems to be working. I'm able to correctly classify the cats and dogs.
| https://stackoverflow.com/questions/71040931/ |
randomized data trasnformation in pytorch | I want to rotate all the images in my Dataset with a random degree between [0,180]. If I compose a transformation function and pass my images to this function in the __getitem__ function of my Dataset class. Does this mean:
every single image is randomly rotated?
images in each batch get rotated with an identical degr... | In mapped datasets, __getitem__ is used to select a single element from the dataset.
The way random transformations work in PyTorch/Torchvision is they apply a unique random transformation each time the transform is called. This means:
Every single image in your dataset is indeed randomly rotated but not by the same a... | https://stackoverflow.com/questions/71048425/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.