instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
load dataset using glob and how to see what comes out | I am trying to create a dataset that can be used for training a ML model (CNN), but I am having trouble reading the files (have I used glob correct) and sorting them in a way that is useful for training. I am not sure what comes out of this when i run load_data. (Dataset an code comes from kaggle) The code is written i... | numpy_dataset = load_data
print(np.ndarray.shape(numpy_dataset))
Here´s the error message that I get:
... 'getset_descriptor' object is not callable
Yup, that makes sense.
You assigned a function's definition to the dataset,
rather than assigning the function's result.
You want to actually call that function
numpy_d... | https://stackoverflow.com/questions/73261119/ |
Pytorch DL model, updates normally with converging losses during training, but SAME OUTPUT values for all data (regression) | I've only used Neural Networks in CNNs and RNNs,
but this is my first time using it as a regression task.
There are 30000 sets of data.
Each data has 50 input features, and I must predict 14 output features for each.
So, my goal is to make a prediction for about 30000 datasets,
so that would make my task : IN - 30000 d... | Why don't you change your learning rate? check out this post : https://discuss.pytorch.org/t/why-am-i-getting-same-output-values-for-every-single-data-in-my-ann-model-for-multi-class-classification/57760/7
Otherwise check if the weights of your model layers are being updated during training or input data are properly b... | https://stackoverflow.com/questions/73264096/ |
TypeError: __init__() got an unexpected keyword argument 'progress_bar_refresh_rate' | I tried resolving this issue since two days however still facing this issue any leads would be helpful.
Please refer the link for screenshot
| Please try by deleting the progress_bar_refresh_rate=5 argument, since this keyword argument is no longer supported by the latest version (1.7.0) of PyTorch.Lightning.Trainer module. Check this screenshot for clarity.
| https://stackoverflow.com/questions/73264813/ |
using list in creating pytorch NN module | This code runs fine to create a simple feed-forward neural Network. The layer (torch.nn.Linear) is assigned to the class variable by using self.
class MultipleRegression3L(torch.nn.Module):
def __init__(self, num_features):
super(MultipleRegression3L, self).__init__()
self.layer_1 = torch.nn.Linear(num_featu... | Pytorch needs to keep the graph of the modules in the model, so using a list does not work. Using self.layers = torch.nn.ModuleList() fixed the problem.
| https://stackoverflow.com/questions/73268576/ |
PyTorch Autograd for Regression | another PyTorch newbie here trying to understand their computational graph and autograd.
I'm learning the following model on potential energy and corresponding force.
model = nn.Sequential(
nn.Linear(1, 32),
nn.Linear(32, 32), nn.Tanh(),
nn.Linear(32, 32), nn.Tanh(),
nn.Linear(32, 1)
)
optimizer = torc... | This error occurs when backward is executed after backward. (without reset gradient) Here is the example code.
output = model.forward(x)
loss = criterion(label, output)
optimizer.zero_grad()
loss.backward()
loss2 = criterion(loss, output2)
loss2.backward()
optimizer.step()
And as you can see in the following code, ... | https://stackoverflow.com/questions/73284709/ |
Is there a way to compute the matrix logarithm of a Pytorch tensor? | I am trying to compute matrix logarithms in Pytorch but I need to keep tensors because I then apply gradients which means I can't use numpy arrays.
Basically I'm trying to do the equivalent of https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.logm.html but with Pytorch tensors.
Thank you.
| Unfortunately the matrix logarithm (unlike the matrix exponential) is not implemented yet, but matrix powers are, this means
in the mean time you can approximate the matrix logarithm by using a the power series expansion, and just truncate it after you get a sufficient accuracy.
Alternatively Lezcano proposes a (slow) ... | https://stackoverflow.com/questions/73288332/ |
The model did not return a loss from the inputs - LabSE error | I want to fine tune LabSE for Question answering using squad dataset. and i got this error:
ValueError: The model did not return a loss from the inputs, only the following keys: last_hidden_state,pooler_output. For reference, the inputs it received are input_ids,token_type_ids,attention_mask.
I am trying to fine tune t... | Hi,
Please make sure you are good with the below :
You may need to pass the label_names argument in TrainingArguments with the label column or key which you are providing, else you need to know what is the default forward argument which is accepted by the model of your choice
For example : with BertForQuestionAnsweri... | https://stackoverflow.com/questions/73290491/ |
Understanding the role of num_workers in Pytorch's Dataloader | In PyTorch's Dataloader suppose:
I) Batch size=8 and num_workers=8
II) Batch size=1 and num_workers=8
III) Batch size=1 and num_workers=1
with exact same get_item() function.
So,
in case I) will 1 worker be assigned for each batch and in case II) only 1 worker will be used and 7 idle.
Or is it that even in case II) al... | Every worker process is always responsible for loading a whole batch, so the batch size and number of workers are not really related.
in case I) will 1 worker be assigned for each batch and in case II) only 1 worker will be used and 7 idle.
All 8 workers will load batches and deliver them whenever required. So as soo... | https://stackoverflow.com/questions/73290826/ |
Pytorch: How to generate random vectors with length in a certain range? | I want a k by 3 by n tensor representing k batches of n random 3d vectors, each vector has a magnitude (Euclidean norm) between a and b. Other than rescaling the entries of a random kx3xn tensor to n random lengths in a for loop, is there a better/more idiomatic way to do this?
| Assuming a < b, you now have a constraint on the 3rd random number due to the norm. i.e sqrt(a^2 - x^2 - y^2) < z < sqrt(b^2 - x^2 - y^2)
Now a^2 - x^2 - y^2 > 0 which implies that x^2 + y^2 < a^2
We need two sets of generate numbers such that x^2 + y^2 < a^2
import numpy as np
def rand_generator(a,... | https://stackoverflow.com/questions/73294933/ |
understanding the torch.nn.functional.grid_sample op by concrete example | I am debugging a neural network which has a torch.nn.functional.grid.sample operator inside. Using the Pycharm IDE, I can watch the values during debugging. My grid is a 1*15*2 tensor, here are the values in the first batch.
My input is a 1*128*16*16 tensor, here are the values in the first channel of the first batc... | I answer my own question, it turns out that the inconsistency is due to the 'align_corners' flag. My way of calculation is actually under the case when 'align_corners' is true while in the program, this flag is set to be false. For how to calculate sample coordinates, please see this
| https://stackoverflow.com/questions/73300183/ |
PyTorch - Train imbalanced dataset (set weights) for object detection | I am quite new with PyTorch, and I am trying to use an object detection model to do transfer learning in order to learn how to detect my new dataset.
Here is how I load the dataset:
train_dataset = MyDataset(train_data_path, 512, 512, train_labels_path, get_train_transform())
train_loader = DataLoader(train_dataset,bat... | It seems that you have two questions.
How to deal with imbalanced dataset.
Note that Faster-RCNN is an Anchor-Based detector, which means number of anchors containing the object is extremely small compared to the number of total anchors, so you don't need to deal with the imbalanced dataset. Or you can use RetinaNet w... | https://stackoverflow.com/questions/73302325/ |
How to get gradient (dL/dw) during training in Pytorch? | class ConvNet(torch.nn.Module):
def __init__(self):
super(ConvNet, self).__init__()
self.conv1 = torch.nn.Conv2d(1, 6, 5)
self.pool = torch.nn.MaxPool2d(2, 2)
self.conv2 = torch.nn.Conv2d(6, 16, 5)
self.fc1 = torch.nn.Linear(16 * 4 * 4, 62)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x))... | Okay, a few things to note here:
I'm assuming you have already instantiated/initialized your ConvNet class with an object called model. (model = ConvNet())
The way you're accessing the model's weight gradients is correct, however, you're using the wrong object to access these weights. Specifically, you're supposed to ... | https://stackoverflow.com/questions/73311567/ |
optimizer got an empty parameter list | If I use optim.SGD(model_conv.fc.parameters() I'm getting an error:
optimizer got an empty parameter list
This error is, when model_conv.fc is nn.Hardtanh(...) (also when I try to use ReLu).
But with nn.Linear it works fine.
What could be the reason?
model_conv.fc = nn.Hardtanh(min_val=0.0, max_val=1.0) #not ok -->... | Hardtanh and ReLU are parameter-free layers but Linear has parameters.
| https://stackoverflow.com/questions/73312561/ |
Clustering Graphs using graph distance | What I'm currently doing is:
Train a GNN and see which graphs are labelled wrongly compared to the ground truth.
Use a GNN-explainer model to help explain which minimum sub-graph is responsible for the mislabeling by checking the wrongly label instances.
Use the graph_edit_distance from networkx to see how much these ... |
Use the graph_edit_distance from networkx to see how much these graphs
differentiate from another.
Guessing this gives you a single number for any pair of graphs.
The question is: on what direction is this number? How many dimensions ( directions ) are there? Suppose two graphs have the same distance from a third. ... | https://stackoverflow.com/questions/73320165/ |
Plotting the confuison matrix into wandb (pytorch) | I'm training a model and I'm trying to add a confusion matrix, which would be displayed in my wandb, but I got lost a bit. Basically, the matrix works; I can print it, but it's not loaded into wandb. Everything should be OK, except it's not. Can you please help me? I'm new to all this. Thanks a lot!
the code
since ... | Have you tried the wandb Confusion matrix that comes with wandb?
cm = wandb.plot.confusion_matrix(
y_true=ground_truth,
preds=predictions,
class_names=class_names)
wandb.log({"conf_mat": cm})
| https://stackoverflow.com/questions/73320449/ |
How would you write the Multivariate Normal Distribution from scratch in Torch? | I would like to implement the Multivariate Normal Distribution in the Torch library from scratch. My implementation is not giving me the same output as the distribution at torch.distributions.MultivariateNormal. What part do I have wrong?
I tried implementing an equation of the Multivariate Normal Distribution I found ... | Σ should be a symmetric matrix by definition. In your provided example, the following code is not correct.
Σ = torch.linalg.cholesky(pos_def_cov)
Moreover, the pdf should return a scalar but not a matrix. The following code is also wrong. You should not use torch.abs() but torch.det()
(1 / torch.sqrt(2 * torch.pi**d... | https://stackoverflow.com/questions/73326851/ |
Configuring a progress bar while training for Deep Learning | I have this tiny training function upcycled from a tutorial.
def train(epoch, tokenizer, model, device, loader, optimizer):
model.train()
with tqdm.tqdm(loader, unit="batch") as tepoch:
for _,data in enumerate(loader, 0):
y = data['target_ids'].to(device, dtype = torch.long)
y_ids = y[:, :-1].co... | In case anyone else has run in my same issue, thanks to the previous response I was able to configure the progress bar as I wanted with just a little tweak of what I was doing before:
def train(epoch, tokenizer, model, device, loader, optimizer):
model.train()
for _,data in tqdm(enumerate(loader, 0), unit="... | https://stackoverflow.com/questions/73327697/ |
convert bounding box coordinates to x,y pairs | I have a bounding box coordinates in this format [x, y, width, height],
how can I get all the x and y pairs from it?
the result is going to be in this format [(x1,y1),(x2,y2),...,(xn,yn)]
thanks in advance!
| I'm not sure if I understand your data description correctly, but here's an example that might fit:
data = [
[1, 2, 100, 100],
[3, 4, 100, 100],
[5, 6, 200, 200],
]
result = [tuple(x[:2]) for x in data]
Result:
[(1, 2), (3, 4), (5, 6)]
| https://stackoverflow.com/questions/73339564/ |
How to copy a tensor with gradient information into another tensor? | I have a tensor A of shape (1, 768) with gradient and a tensor B of shape (2, 4, 768). I want to replace some values of tensor B with tensor A and have it pass back the gradient normally. However, direct assignment like B[batch][replace_ids].data = A seems to lose all gradients in A while B[batch][replace_ids] = A will... | Would be great if we can see a MWE but I guess you can try
B = B.clone()[batch, replace_ids] = A
| https://stackoverflow.com/questions/73349482/ |
Streamlit crashes while importing torch | Im trying to load my model and make an app using streamlit but the app crashes while importing torch. Does anyone know the reason?
| As long as you add it to your requirements file as "torch" (not pytorch -- I've had my app crash when I've tried importing it as pytorch or listing it as pytorch in my requirements file), it should work. If your app is using a large amount of resources, that could be the cause of the crash. Here's a repo for... | https://stackoverflow.com/questions/73355634/ |
Problem with executing python machine learning code I found on GitHub | I need some clear instructions on how to execute some code.
Context:
This is a python machine learning peptide binding script, but you don't need to know biology to help me.
I am trying to recreate this scientific paper to test its validity and if I can use it. I work in the biotech industry and am only somewhat famili... | Looking at the ValueError, it seems that what you're trying to do is deprecated in pytorch, so you have a more recent version of the package than the one it was developed in. I suggest you try
pip install pytorch 1.4.0
in command line.
I'm not familiar with pytorch but menaging tensor shapes in tensorflow is the bigge... | https://stackoverflow.com/questions/73356319/ |
Putting all the tensors on one device | I am using ViViT in my model. Although I moved the input and the my whole model to the cuda, the train process shows an error in the line of position embedding:
class ViViTBackbone(nn.Module):
""" Model-3 backbone of ViViT """
def __init__(self, t, h, w, patch_t, patch_h, patch_w,... | There are multiple ways:
Instead of creating parameters like:
self.T = t
do:
self.T = nn.Parameter(t)
then model.to(device) will push all the parameters to the correct device too.
An alternative is to use the device parameter whenever you create a tensor
some_tensor = torch.tensor(1.0,device=self.device)
or
some_ten... | https://stackoverflow.com/questions/73363204/ |
When retraining a model in pytorch should the optimizer be defined outside the train method? Will it get rid of previous weights if not? | So I am training a GNN on pytorch and after training it, with it's saved weights, I want to train it more with a separate dataset. When re training with the new dataset I don't want the weights to be reset, I want the weights to update from my last training session. Currently, my training code looks like this:
def trai... | You can define the optimizer and model wherever you want (both inside and outside the train() method) as long as you are loading the weights correctly before the training loop. What you are missing probably is loading weights!!
From Pytorch tutorial,
Defining model and optimizer:
model = TheModelClass(*args, **kwargs)
... | https://stackoverflow.com/questions/73364288/ |
CNN model for RGB images giving 0% accuracy | I am trying to train a CNN model on CelebA (RGB images) dataset. But, when I train the model and check its accuracy it is 0% or close to 0%. I think the issue is in the ConNeuralNet function or the hyperparameters but due to my limited knowledge I'm not sure what I'm missing here. Can someone please help. Thanks
# Crea... | **Update I ran the code for a bit to see if it would start converging. One thing is that there are over 10,000 classes. With a batch size of 64 this means that it will take more than 150 mini-batches before your model has seen every class in your dataset. You certanly shouldn't expect the model to start achieving accur... | https://stackoverflow.com/questions/73364701/ |
why is ray Tune with pytorch HPO error 'trials did not complete, incomplete trials'? | Could someone explain why this code (that I took from here):
## Standard libraries
import os
import json
import math
import numpy as np
import time
## Imports for plotting
import matplotlib.pyplot as plt
#%matplotlib inline
#from IPython.display import set_matplotlib_formats
#set_matplotlib_formats('svg', 'pdf') # F... | Is there a longer stacktrace where the real error is printed?
Also could you go to the result folder and see the error file?
Usually result folder is under ~/ray_results.
| https://stackoverflow.com/questions/73374386/ |
How to convert image from folder into tensors using torch? | I'm trying to convert images in a folder to tensors, save it and load them later, as shown below
transform = transforms.Compose([
transforms.ToTensor()])
dataset = datasets.ImageFolder(
r'imagedata', transform=transform)
torch.save(dataset, 'train_data.pt')
But I get a value error when trying to load the trained ... | You met this problem because train_data.pt was not saved as a Tensor, since that variable was read the data by ImageFolder which was inherited from DatasetFolder, it should be loaded and used as a Torch Dataset. The example below use DataLoader as documents:
import torch
from torchvision import transforms, datasets
# ... | https://stackoverflow.com/questions/73378920/ |
Pytorch model function gives Error :'NoneType' object has no attribute 'size' | I trying to run below code in my image segmentation problem without CUDA as I don't have GPU. I have trained my model on CPU using pytorch but on prediction level I'm getting
AttributeError: 'NoneType' object has no attribute 'size'
Here's the code:
idx = 20
model.load_state_dict(torch.load('/content/best_model.pt'))
... | assert y_true.size(0) == y_pred.size(0) erroring signifies that either y_true or y_pred are None, so you can try checking the types of image, model(image), & mask respectively.
IMO, this might be the root cause: image = image.unsqueeze_(0)
unsqueze_ is an inplace operator, which means it will return nothing and cha... | https://stackoverflow.com/questions/73379963/ |
BertModel weights are randomly initialized? | recently, I've been trying to re-implement DiffCSE
During refactoring the codes that the authors uploaded on Github, I've run into some issues.
I have 2 questions
1.
If I set seed like set_seed(30), I was under the impression that the model has the same initialized weights, thus making the same result when training. ... | You have a small misunderstanding of how seeds work. The seed defines how the random values are sampled, it doesn't reset after each sample. This means that the sequences sampled will be the same when starting from the seed. For example, if you have a code like:
seed = 1
sample = sample_4_values()
You should always ge... | https://stackoverflow.com/questions/73382965/ |
pytorch tensor sort rows based on column | In a 2D tensor like so
tensor([[0.8771, 0.0976, 0.8186],
[0.7044, 0.4783, 0.0350],
[0.4239, 0.8341, 0.3693],
[0.5568, 0.9175, 0.0763],
[0.0876, 0.1651, 0.2776]])
How do you sort the rows based off the values in a column? For instance if we were to sort based off the last column, I would... | a = <your tensor>
ind = a[:,-1].argsort(dim=0)
a[ind]
argsort "Returns the indices that sort a tensor along a given dimension in ascending order by value." So, basically, you get sorting indices for the last column and reorder the rows according to these indices.
| https://stackoverflow.com/questions/73389603/ |
PyTorch Lightning - How to automatically reload last checkpoint when loss unexpectedly spikes? | I'm facing a problem where during training, my loss will unexpectedly spike, like so:
When this happens, I want to automatically reload the last checkpoint, reset the optimizer and resume training. How do I do this?
Edit: I tried training with fp64 precision and the unstable learning problem still occurred albeit late... | you could write a callback where you can check the spike and load the last checkpoint. Please, let me know if this helps!
| https://stackoverflow.com/questions/73395943/ |
ImportError about Detectron2 | I was trying to do semantic segmentation using Detectron2, but some tricky errors occurred when I ran my program. It seems there might be some problems in my environment.
Does anyone know how to fix it?
ImportError: cannot import name 'is_fx_tracing' from 'torch.fx._symbolic_trace' (/home/eric/anaconda3/envs/detectron... | This seems to be an issue with the latest commit of detectron2, you can use the previous commit of detectron2 while installing to avoid this error.
pip install 'git+https://github.com/facebookresearch/detectron2.git@5aeb252b194b93dc2879b4ac34bc51a31b5aee13'
The issue is resolved in the latest commit of detectron2
| https://stackoverflow.com/questions/73408083/ |
ValueError: The following `model_kwargs` are not used by the model: ['encoder_outputs'] (note: typos in the generate arguments will also show up | When I try to run my code for Donut for DocVQA model, I got the following error
"""Test"""
from donut import DonutModel
from PIL import Image
import torch
model = DonutModel.from_pretrained(
"naver-clova-ix/donut-base-finetuned-cord-v2")
if torch.cuda.is_available():
mo... | Check the transformers library version.
For me, I reinstalled the 4.21.3 version and it worked.
| https://stackoverflow.com/questions/73413237/ |
PyTorch Tensor methods to nn.Modules? | I'm programming some callable custom modules in PyTorch and I wanted to know if I'm doing it correctly. Here's an example scenario where I want to construct a module that takes a torch.Tensor as input, performs a learnable linear operation and outputs a diagonal covariance matrix to use in a multivariate distribution d... | This looks like the correct design pattern.
Ideally, you would also write your main network as an nn.Module:
class Model(nn.Sequential):
def __init__(self, input_size, output_size):
logvar_module = nn.Linear(input_size, output_size)
super().__init__(logvar_module, Exp(), Diag())
| https://stackoverflow.com/questions/73417157/ |
Local maximums of sub-tensors by index tensor | I have a tensor x of shape (1,n), and another index tensor d of shape (1,k). I’m trying to find the maximums of k sub-tensors
x[0:d[0]], x[d[0]:d[1]], x[d[1]:d[2]], ..., x[d[-2]: d[-1]]
So the output is a tensor of shape (1,k) with k local maximums. I can implement a for loop, but that’s too slow. Can I do it in paral... | I found the answer thanks to user7138814. There is a SegmentCSR function in torch_scatter that does the job:
from torch_scatter import segment_csr
src = torch.randn(10, 6, 64)
indptr = torch.tensor([0, 2, 5, 6])
indptr = indptr.view(1, -1) # Broadcasting in the first and last dim.
out = segment_csr(src, indptr, redu... | https://stackoverflow.com/questions/73420220/ |
How pytorch loss connect to model parameters? | I know that in PyTorch optimizer is connected to the model's parameters by
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
and inside the training loop we have to do the backward and update the gradient by execute this two lines
loss.backward()
optimizer.step()
But how does the loss actually connect... | Q: When we execute loss.backward(), how does PyTorch know that we will do backpropagation for our model?
In the line l = loss(Y, y_pred), the predictions are used to calculate the loss. This effectively connects the model parameters with the loss such that loss.backward() can do the backpropagation for the network to c... | https://stackoverflow.com/questions/73423703/ |
Instance Norm: ValueError: Expected more than 1 spatial element when training, got input size torch.Size([128, 512, 1, 1]) | I have a ResNet-18 working well. Now, I want to use InstanceNorm as normalization layer instead of BatchNorm, so I changed all the batchnorm layers in this way:
resnet18.bn1 = nn.InstanceNorm2d(64, eps=1e-05, momentum=0.9, affine=True, track_running_stats=True)
resnet18.layer1[0].bn1 = nn.InstanceNorm2d(64, eps=1e-05,... | I was using CIFAR-10 with size 32x32. If I resize the images to 64x64 It works. This because resnet-18 reduces the filters to 1x1 and as the title says, InstanceNorm wants dimensions (H and W) > 1
| https://stackoverflow.com/questions/73426072/ |
Lightning Flash error with SemanticSegmentationData (NameError: name 'K' is not defined) | I'm trying to perform an image segmentation task with Colab and Lightning Flash.
I'm installing Flash with:
!pip install lightning-flash
I'm trying to instanciate a Lightning Flash SemanticSegmentationData using from_folders method like this:
datamodule = SemanticSegmentationData.from_folders(
train_folder=x_train... | Initially, I was trying to solve the problem this way:
!pip install kornia
import kornia as K
This didn't solve the problem. Then, I opened an issue in their GitHub Issue #1423. With a help from https://github.com/krshrimali, I discovered that just installing kornia would solve the problem.
So, the solution is just:
!... | https://stackoverflow.com/questions/73427839/ |
Is it possible to perform step according to batch size in pytorch? | I am iterating over training samples in batches, however last batch always returns fewer samples.
Is it possible to specify step size in torch according to the current batch length?
For example most batch are of size 64, last batch only 6 samples.
If I do the usual routine:
optimizer.zero_grad()
loss.backward()... | You can define a custom loss function and then e.g. reweight it based on batch size
def reweighted_cross_entropy(my_outputs, my_labels):
# compute batch size
my_batch_size = my_outputs.size()[0]
original_loss = nn.CrossEntropyLoss()
loss = original_loss (my_outputs, my_labels)
# reweight accordin... | https://stackoverflow.com/questions/73434706/ |
How to apply random forests to the output produced by Bert? | I'm trying to get the output embeddings of a RoBERTa model, so I can train a random forests classifier on it for text classification (sentiment analysis). The original dataset this is based on is 500 news articles that each have a left/center/right bias rating. 80% of this dataset is training data, the other 20% is tes... | This shape doesn't look like proper embedding. For classification purpose, a usual approach to encoder-only models is just supplying the last hidden state as embeddings for the classifier, for example:
features = model_output[0][:,0,:].numpy()
text_classifier.fit(features, y_train)
| https://stackoverflow.com/questions/73439107/ |
How to add a channel layer for a 3D image for 3D CNN | I am working on a medical dataset of 3d images the shapeimage.shape gives me (512,512,241) I assume it is height , width, depth but when I run 3D cnn i get this error Given groups=1, weight of size [32, 3, 3, 3, 3], expected input[1, 1, 241, 512, 512] to have 3 channels, but got 1 channels instead. what should be done?... | Your network expects each slice of the 3d volume to have three channels (RGB). You can simply convert grayscale (single channel) data to "fake" RGB by duplicating the single channel you have:
x_gray = ... # your tensor of shape batch-1-241-512-512
x_fake_rgb = x_gray.expand(-1, 3, -1, -1, -1)
See expand for... | https://stackoverflow.com/questions/73441205/ |
AttributeError: module 'dill' has no attribute 'extend' | I have just installed Pytorch, using:
(base) C:\>pip3 install torch torchvision torchaudio
Requirement already satisfied: torch in c:\users\Emil\appdata\roaming\python\python38\site-packages (1.9.0)
Requirement already satisfied: torchvision in c:\users\Emil\appdata\roaming\python\python38\site-packages (0.10.0)
Req... | Based on Mike McKerns' comment, I successfully used:
pip install dill --upgrade
| https://stackoverflow.com/questions/73443382/ |
How to flush GPU memory using CUDA on WSL2 | I have interrupted the training of the model in PyTorch on CUDA, which I've run on Windows Subsystem for Linux 2 (WSL2). The dedicated GPU memory of NVIDIA GeForce RTX 3080Ti was not flushed.
What I have tried:
gc.collect() and torch.cuda.empty_cache() does not resolve the problem (reference)
When running numba.cuda... | I don't know your actual environment.
suppose that you use anaconda window-venv
On cmd >nvidia-smi shows following.
Check pid of python process name(>envs\psychopy\python.exe).
On cmd taskkill /f /PID xxxx
this could be help.
and you don't want doing like this.
if you feeling annoying you can run the script... | https://stackoverflow.com/questions/73447464/ |
When using torch.autocast, how do I force individual layers to float32 | I'm trying to train a model in mixed precision. However, I want a few of the layers to be in full precision for stability reasons. How do I force an individual layer to be float32 when using torch.autocast? In particular, I'd like for this to be onnx compileable.
Is it something like:
with torch.cuda.amp.autocast(enabl... | I think the motivation of torch.autocast is to automate the reduction of precision (not the increase).
If you have functions that need a particular dtype, you should consider using, custom_fwd
import torch
@torch.cuda.amp.custom_fwd(cast_inputs=torch.complex128)
def get_custom(x):
print(' Decorated function receiv... | https://stackoverflow.com/questions/73449288/ |
Cost of back-propagation for subset of DNN parameters | I am using pytorch for evaluating gradients of feed-forward network, but only for a subset of parameters, related to the first two layers.
Since backpropagation is carried backwards layer by layer, I wonder: why is it computationally faster than evaluating gradients of whole network?
| Pytorch builds a computation graph for backward propagation that only contains the minimum nodes and edges to get the accumulated gradient for leaves that require gradient. Even if the first two layers require gradient, there are many tensors (intermediate tensors or frozen parameters tensors) that are unused and that ... | https://stackoverflow.com/questions/73464737/ |
PyTorch: How to create a Parameter without specifying the dimension | Say I want to defined a module. In this module, the __init__() function will create a Parameter called self.weight without known the input_dim of the module. My question is, how can I expand the self.weight and initialize it when I first call the forward() function?
For example, I want my module looks like this:
class ... | After all, it works for me using the way I explained in the comments - to allocate the weights parameter right in the init_parameters function.
import torch
class MyModel(torch.nn.Module):
def __init__(self, out_dim):
super(MyModel, self).__init__()
self.weight = torch.nn.Parameter(torch.FloatTenso... | https://stackoverflow.com/questions/73468424/ |
torch suppress to kth largest values | I have the following function which works, but just not for half precision values (get a NotImplemented error for kthvalue).
def suppress_small_probabilities(probabilities: torch.FloatTensor, k: int) -> torch.FloatTensor:
kth_largest, _ = (-probabilities).kthvalue(k, dim=-1, keepdim=True)
return probabilitie... | Implement your own topk, e.g.
def mytopk(xs: Tensor, k: int) -> Tensor:
mask = torch.zeros_like(xs)
batch_idx = torch.arange(0, len(xs))
for _ in range(k):
_, index = torch.where(mask == 0, xs, -1e4).max(-1)
mask[(batch_idx, index)] = 1
return mask
This will return a boolean mask ten... | https://stackoverflow.com/questions/73486637/ |
Writing a pytorch neural net class that has functions for both model fitting and prediction | I want a PyTorch neural net to predict y using x where, for example,
x = torch.tensor([[6,2],[5,2],[1,3],[7,6]]).float()
y = torch.tensor([1,5,2,5]).float()
For this, I have written the following PyTorch class which can fit y using x. But, I am not able to extend the code to predict using new values of x, x_test. Can ... | Here is a minimal example with some modifications carried out to your code:
class MyNeuralNet(nn.Module):
def __init__(self):
super().__init__()
self.layer1 = nn.Linear(2, 4, bias=True)
self.layer2 = nn.Linear(4, 1, bias=True)
self.loss = nn.MSELoss()
self.compile_()
def... | https://stackoverflow.com/questions/73493198/ |
How to feed different pad IDs to a collate function? | I usually use a custom collate_fn and use it as an argument when defining my DataLoader. It usually looks something like:
def collate_fn(batch):
max_len = max([len(b['input_ids']) for b in batch])
input_ids = [b['input_ids'] + ([0] * (max_len - len(b['input_ids'])))]
labels = [b['label'] for b in batch]
... | I was able to make a workaround by making a Trainer class and making the collate_fn a method. After that I was able to do something like self.pad_token_id = tokenizer.pad_token_id and modify the original collate_fn to use self.pad_token_id rather than a hardcoded value.
I'm still curious if there's any way to do this w... | https://stackoverflow.com/questions/73494999/ |
Ensure that every column in a matrix has at least `e` non-zero elements | I would like to ensure that each column in a matrix has at least e non-zero elements, and for each column that does not randomoly replace zero-valued elements with the value y until the column contains e non-zero elements. Consider the following matrix where some columns have 0, 1 or 2 elements. After the operation, ea... | In the case where you care only that each column has at least e elements and not EXACTLY e elements, you can do it without a loop. The key is that in this case, we can create an array with every non-zero value replaced, and then sample e values from this array for each column.
For convenience let x.shape = [a,b]
Creat... | https://stackoverflow.com/questions/73501398/ |
Multiply each tensor with a value from a another tensor | I have two tensors:
import torch
a = torch.randn((2,3,5))
b = torch.tensor([[2.0, 1.0, 2.0],[0.5, 1.0, 1.0]])
And I want to multiply the each element in the last dimension in a with the corresponding element in b. That means when a is:
tensor([[[ 1, 2, 3, 4, 5],
[1, 2, 3, 4, 5],
[1, 2, 3, 4, 5]],
... | All I need to do, is to add an dimension:
a * b.unsqueeze(-1)
| https://stackoverflow.com/questions/73502352/ |
Giving less weight to data coming from another dataset that is noisy | I have two datasets, one with clean data and one with dirty data. I train a Roberta model on the clean dataset and then get predictions for the dirty dataset. Those predictions with a probability greater than 0.9 go to the clean dataset. I then retrain the Roberta model with this new dataset (clean + dirty moving to cl... | One way to choose the weight is based on your confidence in the dirty data and assign the weight accordingly. For example, if you think that 90% of dirty data is labeled correctly, then choosing 0.9 as the weight for the noisy data is a reasonable option.
Additionally, there is a whole literature on learning from noisy... | https://stackoverflow.com/questions/73512467/ |
ValueError: too many values to unpack using sum return function | Attempting to implement this Deep Embedded Clustering GitHub algorithm.
def acc(y_pred, y_target):
D = max(y_pred.max(), y_target.max()) + 1
w = np.zeros((D, D), dtype=np.int64)
for i in range(y_pred.size):
w[y_pred[i], y_target[i]] += 1
ind = linear_assignment(w.max() -... | Solution if anyone else encounters similar issue. The Github Repo using linear_assignment is deprecated and removed from updated scikit learn packages.
I had used the solution accepted as the answer within this thread , However, as mentioned in that thread scipy.optimize.linear_sum_assignment is not the perfect replac... | https://stackoverflow.com/questions/73513994/ |
Defining my own gradient function for pytorch to use | I want to feed pytorch gradients manually. In my real problem, I have my own adjoint function that does not use tensors. Is there any way I can define my own gradient function for pytorch to use during optimization?
import numpy as np
import torch
# define rosenbrock function and gradient
x0 = np.array([0.1, 0.1])
a =... | Not quite sure if this is exactly what you want but the method call loss.backward() computes gradients via pytorch's computational graph and stores the gradient values in the weight tensors themselves (in your case it's in x_tensor). And these gradients can be accessed via x_tensor.grad. However, if you don't want to u... | https://stackoverflow.com/questions/73532345/ |
Where to find the docs of axis parameter of torch.sum? | I'm trying to read about the sum function of torch here. I noticed that the following works:
> print(torch.sum(torch.randint(0,2,(2,2)),axis=1))
tensor([1, 0])
But in the docs above I don't see explanation for axis.
In the signature of the function I see *:
torch.sum(input, *, dtype=None) → Tensor
Does it have to ... | PyTorch emulates much of the basic functionality of Numpy (with additional GPU acceleration and autograd mechanics) but the API also differs in some small ways. For example, PyTorch generally uses the dim keyword argument to specify which dimension a function should operate on while Numpy uses the axis keyword argument... | https://stackoverflow.com/questions/73541200/ |
Adapting MNIST designed network for a larger dataset | I am attempting to implement this deep clustering algorithm, which was designed to cluster the MNIST dataset. Single Channel 28x28 images.
The images I am trying to use are 416x416 and 3-Channel RGB. The script is initialised with the following functions.
class CachedMNIST(Dataset):
def __init__(self, train, cuda, ... | Error 1 is happening because the first linear layer has in_features=784. That number comes from the 28x28 pixels in the 1-channel MNIST data. Your input data is 416x416x3 = 519168 (different if you resize your inputs). In order to resolve this error, you need to make the in_features in that first linear layer match ... | https://stackoverflow.com/questions/73556207/ |
Pytorch "hipErrorNoBinaryForGpu: Unable to find code object for all current devices!" | SYSTEM: Ryzen 5800x, rx 6700xt, 32 gigs of RAM, Ubuntu 22.04.1
I'm attempting to install Stable-Diffusion by following https://youtu.be/d_CgaHyA_n4
When attempting to run the SD script, I get the "hipErrorNoBinaryForGpu: Unable to find code object for all current devices!" error.
I believe this is caused by P... | Try running the following command:
export HSA_OVERRIDE_GFX_VERSION=10.3.0
This made it work on my machine using an RX 6600 XT, with which I got the same error running it, before exporting the variable.
| https://stackoverflow.com/questions/73575955/ |
IterableWrapper is not defined when using WikiText2 | I am trying to follow along this tutorial https://pytorch.org/tutorials/beginner/transformer_tutorial.html
I am getting the following error when calling this function.
----> 6 train_iter = WikiText2(split='train')
/usr/local/lib/python3.7/dist-packages/torchtext/datasets/wikitext2.py in WikiText2(root, split)
75 ... | I tried running the snippet of code you provided. I don't see
NameError: name 'IterableWrapper' is not defined
but I have a different error which says,
No module named 'torchdata'
I don't have torchdata installed.
So in your case, I would make sure if the torchdata is installed correctly.
You can look at this official ... | https://stackoverflow.com/questions/73590391/ |
Pytorch model output is not correct (torch.float32 and torch.float64) | I have created a DNN model with Pytorch (input_dim=6, output_dim=150). Normally, if I generate a random X_in=torch.randn(6000, 6), it will return me a model_out.shape=(6000, 150), and if I calculate the Rank of model_out, it should be 150 (since my model's weight and bias are also randomly initialised).
However, you ca... | You have to realize that we are dealing with a numerical problem here: The rank of a matrix is a discrete value derived from a e.g. a singular value decomposition in the case of torch.matrix_rank. In this case we need to consider a threshold on the singular values: At what modulus tol do we consider a singular value as... | https://stackoverflow.com/questions/73594922/ |
How to implement Laplace Posteriori Approximation on BERT in PyTorch? | I'm trying to implement the Laplace Posteriori Approximation on the last layer for the classification results obtained by BERT model. I get an error regarding input size, and after I fix it by extracting just embeddings and class labels from BERT to feed them into Laplace, I get another bunch of errors regarding input ... | The laplace library expects that the dataloader returns two parameters (X,y) and that the model requires exactly one argument to make its prediction (code). But your model forward pass requires two arguments, namely input_id and mask, and your dataloader returns three arguments input_id, mask, and labels.
There are sev... | https://stackoverflow.com/questions/73599356/ |
Gradient of X is NoneType in second iteration | I'm trying to make images which will fool model, but I have some problem with this code. In the second iteration I get TypeError: unsupported operand type(s) for -: 'Tensor' and 'NoneType'
Why is the grad NoneType even if it's working for the first time?
X_fooling = X.clone()
X_fooling.requires_grad_()
loss_f = torch.... | I could not fool the network with a target size of 1000. But I was able to fool it with a target size of 64. Here is a minimal code snippet that runs without error:
import matplotlib.pyplot as plt
import torch
torch.manual_seed(0)
target_size = 64
model = torch.nn.Linear(10, target_size)
target_y = torch.randint(0, ta... | https://stackoverflow.com/questions/73624893/ |
What does self(variable) do in Python? | I'm trying to understand someone else's code in Python and I stumbled across a line I don't quite understand and which I can't find on the internet:
x=self(k)
with k being a torch-array.
I know what self.something does but I haven't seen self(something) before.
| self, for these purposes, is just a variable like any other, and when we call a variable with parentheses, it invokes the __call__ magic method. So
x = self(k)
is effectively a shortcut for
x = self.__call__(k)
Footnote: I say "effectively", because it's really more like
x = type(self).__call__(self, k)
d... | https://stackoverflow.com/questions/73625459/ |
Error Running Stable Diffusion from the command line in Windows | I installed Stable Diffusion v1.4 by following the instructions described in https://www.howtogeek.com/830179/how-to-run-stable-diffusion-on-your-pc-to-generate-ai-images/#autotoc_anchor_2
My machine heavily exceeds the min reqs to run Stable Diffusion:
Windows 11 Pro
11th Gen Intel i7 @ 2.30GHz
Latest NVIDIA GeForce G... | I had the same issue, it's because you're using a non-optimized version of Stable-Diffusion. You have to download basujindal's branch of it, which allows it use much less ram by sacrificing the precision, this is the branch - https://github.com/basujindal/stable-diffusion
Everything else in that guide stays the same ju... | https://stackoverflow.com/questions/73629682/ |
How to input images in rllib | last time I saw library rllib: https://docs.ray.io/en/latest/rllib/index.html.
It has amazing features for reinforcement learning, but unfortunately, I couldn't find a way to input images as an observation without flattening them (I basically want to use convolutional neural network). Is there any way to input image ob... | Rllib is compatible with openai's gym, you can create a custom env https://docs.ray.io/en/latest/rllib/rllib-env.html#configuring-environments and return a Box as an observation space like https://stackoverflow.com/a/69602365/4994352
| https://stackoverflow.com/questions/73644488/ |
How to make vgg pytorch's ptl size smaller on android? | import torch
# import joblib
from torch.utils.mobile_optimizer import optimize_for_mobile
from torchvision.models.vgg import vgg16
import torch, torchvision.models
# lb = joblib.load('lb.pkl')
device = torch.device('cuda:0')
#device = torch.device('cpu')#'cuda:0')
torch.backends.cudnn.benchmark = True
model = vgg16().... | You may try using quantization:
https://pytorch.org/docs/stable/quantization.html
Usually it allows to reduce the size of the model 2x-4x times with little or no loss of accuracy.
Example:
import torch
from torch.utils.mobile_optimizer import optimize_for_mobile
from torchvision.models.vgg import vgg16
device = torch.... | https://stackoverflow.com/questions/73652307/ |
Best Practices for Distributed Training with PyTorch custom containers (BYOC) in SageMaker | What are the best practices for distributed training with PyTorch custom containers (BYOC) in Amazon Sagemaker? I understand that PyTorch framework supports native distributed training or using the Horovod library for PyTorch.
| The recommended approach on Amazon SageMaker is to use the SageMaker built in Data Parallel and Model Parallel Libraries. When you use the Pytorch Deep Learning container provided by SageMaker, the library is built in and you can follow the below examples to get started with examples.
https://docs.aws.amazon.com/sagema... | https://stackoverflow.com/questions/73676590/ |
PyTorch convert function for op 'pad' not implemented | When I trying to convert model.ckpt to core ML model use coremltools I got this error:
File "/Users/peterpan/miniforge3/lib/python3.10/site-packages/coremltools/converters/mil/frontend/torch/ops.py", line 86, in convert_nodes
raise RuntimeError(
RuntimeError: PyTorch convert function for op 'pad' not... | Upgrading to coremltools==6.0 fixed this problem for me
| https://stackoverflow.com/questions/73676762/ |
Find euclidean distance between a tensor and each row tensor of a matrix efficiently in PyTorch | I have a tensor A of size torch.Size([3]) and another tensor B of size torch.Size([4,3]).
I want to find the distance between A and each of the 4 rows of B.
I'm new to Torch and I reckon a for loop for each of the rows wouldn't be efficient. I have looked into torch.linalg.norm and torch.cdist but I'm not sure if they ... | You look for:
torch.norm(A[None, :] - B, p=2, dim=1)
A[None, :] resize the tensor to shape (1, 3)
A[None, :] - B will copy 4 times the tensor A to match the size of B ("broadcast") and make the substraction
torch.norm(..., p=2, dim=1) computes the euclidian norme for each column.
Output shape: (4,)
| https://stackoverflow.com/questions/73680705/ |
AttributeError: 'str' object has no attribute 'cuda' | I am trying to move my data to GPU by doing this
batch["img"] = [img.cuda() for img in batch["img"]]
batch["label"] = [label.cuda() for label in batch["label"]]
However, i get this error for the labels for OCR
AttributeError: 'str' object has no attribute 'cuda'
I also tried .t... | Yo !
If I get your code right, your are building your custom dataset to output an image and its label. Your label comes from the first part of your image filename, so it is a string, as stated in the error message. Your object needs to be a Torch tensor to be moved on the GPU with .cuda().
If you want to keep your code... | https://stackoverflow.com/questions/73695519/ |
Why we use validation set (not train or test set) in early stopping function ( DL / CNN )? | This is my first attempt to CNN in Pytorch. I have gone by few tutorials, but still need some clarification.
I have theoretical question, I don't understand why in early stopping function we base on validation set, not train or test set?
Has it something common with metrics we got from validation set?
| The number of training epochs is one of the training hyper-parameters. Therefore, you MUST NOT use the test data to determine the value of this hyper-parameter.
Additionally, you cannot use the training set itself to determine the value of early stopping. Therefore, you need to use the validation set for determining th... | https://stackoverflow.com/questions/73729351/ |
How to set backend to ‘gloo’ on windows in Pytorch | I am trying to use two gpus on my windows machine, but I keep getting
raise RuntimeError("Distributed package doesn't have NCCL " "built
in") RuntimeError: Distributed package doesn't have NCCL built in
I am still new to pytorch and couldnt really find a way of setting the backend to ‘gloo’. Any w... | from torch import distributed as dist
Then in your init of the training logic:
dist.init_process_group("gloo", rank=rank, world_size=world_size)
Update:
You should use python multiprocess like this:
class Trainer:
def __init__(self, rank, world_size):
self.rank = rank
self.world_size = w... | https://stackoverflow.com/questions/73730819/ |
Pytorch BERT input gradient | I am trying to get the input gradients from a BERT model in pytorch. How can I do that?
Suppose, y' = BertModel(x). I am trying to find $d(loss(y,y'))/dx$
| One of the problems with Bert models is that your input mostly contains token IDs rather than token embeddings, which makes getting gradient difficult since the relation between token ID and token embeddings is discontinued.
To solve this issue, you can work with token embeddings.
# get your batch data: token_id, mask ... | https://stackoverflow.com/questions/73743878/ |
What is the unit of time in the following code? | The following code shows inference time of the network. However, I am not sure what the unit of time is. Read through the documentation here, but still confused
####This code is for measuring performance such as inference time, FLOPs, Parameters etc...
dummy_input = torch.randn(1, 3, 256, 256).cuda()
macs, par... | From the documentation of Event.elapsed_time()
https://pytorch.org/docs/stable/generated/torch.cuda.Event.html
Returns the time elapsed in milliseconds after the event was recorded
and before the end_event was recorded.
| https://stackoverflow.com/questions/73744730/ |
Spyder crashing when importing torch | I am using a MacBook Pro (MacOS: Monterey) and I'm using Spyder downloaded as the app for MacOS via this page: https://github.com/spyder-ide/spyder/releases. So it is from a standalone installer and I have installed conda via miniconda3.
Everything works fine until I'm trying to install Pytorch. I have installed the pa... | Question:
Spyder crashing when importing torch on MacOS M2
Answer:
At the new update Anaconda @ MacOS Monterey it works with downgrading pytorch==1.7.1 for spyder==5.3.3.
$ conda install pytorch==1.7.1
| https://stackoverflow.com/questions/73745860/ |
RuntimeError: CUDA out of memory. How setting max_split_size_mb? | I found this problem running a neural network on Colab Pro+ (with the high RAM option).
RuntimeError: CUDA out of memory. Tried to allocate 8.00 GiB (GPU 0; 15.90 GiB total capacity; 12.04 GiB already allocated; 2.72 GiB free; 12.27 GiB reserved in total by PyTorch) If reserved memory is >> allocated memory try s... | The max_split_size_mb configuration value can be set as an environment variable.
The exact syntax is documented at https://pytorch.org/docs/stable/notes/cuda.html#memory-management, but in short:
The behavior of caching allocator can be controlled via environment variable PYTORCH_CUDA_ALLOC_CONF. The format is PYTORCH... | https://stackoverflow.com/questions/73747731/ |
Approximating an exponential fit with a simple neural network | I've been trying to train a network to solve exponential fits of the form s(t) = s0 * e^(-t/decay_constant). As input, the net takes s and t, and as output it should return s0 and the decay_constant.
This seems like a sufficiently simple problem that I would expect a net would be able to satisfactorely approximate.
How... | s0 and decay_constant are not fixed parameter values in your generated data. There is not a single true parameter vector for the model to converge to. You might think that giving it a variety of different examples of exponential outputs from different parameters means it is being trained to predict proper exponential f... | https://stackoverflow.com/questions/73748438/ |
Is Cuda Toolkit release 11.7 compatible with pytorch version 11.6? | I have installed recent version of cuda toolkit that is 11.7 but now while downloading I see pytorch 11.6 is there, are they two compatible?
| There is a table with CUDA compatibility:
https://pytorch.org/get-started/locally/
At this moment the latest supported CUDA version is 11.6.
| https://stackoverflow.com/questions/73768657/ |
Why the training error is greater than the test error? | I have trained a model in mode .train() (nn.Models of Pytorch)
I have saved the BCELoss (in mode .train()) and the accuracies on ds test and on ds train (but in mode .eval() ).
So, the results were:
(for example in epoch 153)
error classification (train, test): 0.5819954128440368 , 0.37209302325581395
and the loss was:... | Test error is not always greater than train error, but it seems that your loss function or model structure has some problem considering that you trained your model for 153 epoches.
Why don't you design a new layer structure, referring lots of publication ? In my experience your problem usually occurs when your model is... | https://stackoverflow.com/questions/73775573/ |
How to turn a numpy array (mic/loopback input) into a torchaudio waveform for a PyTorch classifier | I am currently working on training a classifier with PyTorch and torchaudio. For this purpose I followed the following tutorial: https://towardsdatascience.com/audio-deep-learning-made-simple-sound-classification-step-by-step-cebc936bbe5
This all works like a charm and my classifier is now able to successfully classify... | According to the doc, you will get a numpyarray of shape frames × channels. For a stereo microphone, this will be (N,2), for mono microphone (N,1).
This is pretty much what the torch load function outputs: sig is a raw signal, and sr the sampling rate. You have specified your sample rate yourself
to your mic (so sr = ... | https://stackoverflow.com/questions/73787169/ |
How to vectorize a torch function? | When using numpy I can use np.vectorize to vectorize a function that contains if statements in order for the function to accept array arguments. How can I do the same with torch in order for a function to accept tensor arguments?
For example, the final print statement in the code below will fail. How can I make this wo... | You can use .apply_() for CPU tensors. For CUDA ones, the task is problematic: if statements aren't easy to SIMDify.
You may apply the same workaround for functorch.vmap as video drivers used to do for shaders: evaluate both branches of the condition and stick to arithmetics.
Otherwise, just use a for loop: that's what... | https://stackoverflow.com/questions/73791594/ |
ValueError: too many values to unpack (expected 2) while trying to load yolov5 model | I am trying to load a trained yolov5 model on a custom dataset using this:
# Model
model = torch.hub.load('/home/yolov5/runs/train/yolo_sign_det2/weights', 'best') # or yolov5n - yolov5x6, custom
but I am running into this error:
ValueError Traceback (most recent call last)
<ipython... | From the Pytorch documentation website, it seems that the source option is set to github by default so your line of code:
model = torch.hub.load('/home/yolov5/runs/train/yolo_sign_det2/weights', 'best') # or yolov5n - yolov5x6, custom
actually means:
model = torch.hub.load('/home/yolov5/runs/train/yolo_sign_det2/weig... | https://stackoverflow.com/questions/73796949/ |
How to convert pytorch model to being on GPU? | I want to run pytorch on a GPU.
I have this code:
import torch
import torch.nn as nn
device = torch.device("cuda:0")
n_input, n_hidden, n_out, batch_size, learning_rate = 10, 15, 1, 100, 0.01
data_x = torch.randn(batch_size, n_input)
data_y = (torch.rand(size=(batch_size, 1)) < 0.5).float()
print(data_x... | As suggested in the comments, you need to transfer both your model and your data to the same device. Below should work:
import torch
import torch.nn as nn
device = torch.device("cuda:0")
n_input, n_hidden, n_out, batch_size, learning_rate = 10, 15, 1, 100, 0.01
data_x = torch.randn(batch_size, n_input)
dat... | https://stackoverflow.com/questions/73798104/ |
python methods in comparison | Rock, Paper, Scissors variable bot has default value
Variable Alex, has values that are passed to main.py
When I call method comparison I get an error
Method comparisons
from secrets import choice
from variants import Variants
Player.py
class Player:
name = '',
choice = ''
def __init__(self, choise = 'ROCK... | Answer:
I had to modify the comparison of methods, I did it like this:
also main.po remained the same:
> from variants import Variants from player import Player
>
> bot = Player() alex = Player(Variants.ROCK, "Alex")
> print(bot.whoWins(bot, alex))
variants.py remained the same
from enum import ... | https://stackoverflow.com/questions/73817302/ |
Pytorch: Why does evaluating a string (of an optimizer) in a function break the function? | I have a pytorch lightning class that looks like this:
import torch.optim as optim
class GraphLevelGNN(pl.LightningModule):
def __init__(self,**model_kwargs):
super().__init__()
self.save_hyperparameters()
self.model = GraphGNNModel(**model_kwargs)
self.loss_module = nn.BCEWithLogitsLoss()
self.... | Even though using eval is not the correct approach to your problem, let me just explain why you are facing this error.
The python function eval does not import any modules or functions in the script you are running by default.
For example, you can take eval as the python interpreter, when you just open the interpreter,... | https://stackoverflow.com/questions/73817605/ |
Performance gap between `batch_size==32` and `batch_size==8, gradient_accumulation==4` | I tried to use gradient accumulation in my project. To my understanding, the gradient accumulation is the same as increasing the batch size by x times. I tried batch_size==32 and batch_size==8, gradient_accumulation==4 in my project, however the result varies even when I disabled shuffle in dataloader. The batch_size==... | Assuming your loss is mean-reduced, then you need to scale the loss by 1/accumulate_step
The default behavior of most loss functions is to return the average loss value across each batch element. This is referred to as mean-reduction, and has the property that batch size does not affect the magnitude of the loss (or th... | https://stackoverflow.com/questions/73844065/ |
A simple question about torch.einsum function | A = torch.randn(5,5)
B = torch.einsum("ii->i",A)
C = torch.einsum("ii",A)
Just I exhibit above,I know the result about B that means getting the diagonal elements.
print("before:",A)
print("after:",B)
print('Why:',C)
results
before: tensor([[-0.2339, 0.2501, -1.1814, 1.4392... | Executing torch.einsum("ii", A) is equivalent to torch.einsum("ii->", A), this means the output has no index. You can interpret the output as a rank zero tensor.
So this corresponds to computing the sum of the diagonal elements.
| https://stackoverflow.com/questions/73867143/ |
How can I expand a tensor in Libtorch? (The C++ version of PyTorch) | How can I use LibTorch to expand a tensor of the shape 42, 358 into a shape of 10, 42, 358?
I know how to do this in PyTorch, (AKA Torch).
torch.ones(42, 358).expand(10, -1, -1).shape
returns
torch.Size([10, 42, 358])
In LibTorch I have a tensor of the same size I am trying to "expand" in the same way.
au... | at::expand expects an at::IntArrayRef the compiler tells you. Hence you want to write something like
auto expanded_state_batch = state_batch.expand({10, -1, -1});
| https://stackoverflow.com/questions/73889591/ |
What does the "affine" parameter do in PyTorch nn.BatchNorm2d? | What is the purpose of the affine argument and what does it do?
class DilConv(nn.Module):
def __init__(self, in_C, out_C, kernel_size, stride, padding, affine=True):
super(DilConv, self).__init__()
self.ops = nn.Sequential(
nn.ReLU(),
nn.Conv2d(in_C, in_C, kernel_size=kernel_size... | If you look at the documentation page for BatchNorm2d, you will read:
affine – a boolean value that when set to True, this module has learnable affine parameters. Default: True
Checking the source code on the base class _NormBase, you will see parameters weight and bias are only defined if the argument affine is set ... | https://stackoverflow.com/questions/73891401/ |
How to use pytorch multi-head attention for classification task? | I have a dataset where x shape is (10000, 102, 300) such as ( samples, feature-length, dimension) and y (10000,) which is my binary label. I want to use multi-head attention using PyTorch. I saw the PyTorch documentation from here but there is no explanation of how to use it. How can I use my dataset for classification... | I will write a simple pretty code for classification this will work fine, if you need implementation detail then this part is the same as the Encoder layer in Transformer, except in the last you would need a GlobalAveragePooling Layer and a Dense Layer for classification
attention_layer = nn.MultiHeadAttion(300 , 300%n... | https://stackoverflow.com/questions/73911967/ |
Size of WebDataset in Pytorch | When it comes to the Pytorch Dataloader which takes a default dataset (e.g. datasets.ImageFolder), we can find the size of a dataset that is used by the dataloader with len(dataloader). However, what about WebDataset?
As WebDataset is a PyTorch Dataset, is it possible to get the size of a loader which takes a WebDatase... | WebDataset doesn't provide a __len__ method, as it conforms to the PyTorch IterableDataset interface. IterableDataset is designed for stream-like data, and considers it wrong to have a len().
If you have code that depends on len() to be available, you can set the length to some value using with_length():
>>> d... | https://stackoverflow.com/questions/73918904/ |
Batched Cosine Similarity in PyTorch | Inputs:
Tensor a of shape [batch_size, n, d]
Tensor b of shape [batch_size, m, d]
Output:
Tensor c of shape [batch_size, n, m] where c[i, j, k] is the cosine similarity between a[i, j] and b[i, k]
How to implement this efficiently in PyTorch (preferably without for loops)?
| try this:
c = torch.cosine_similarity(a.unsqueeze(2), b.unsqueeze(1), dim=-1)
| https://stackoverflow.com/questions/73923751/ |
What's the difference between torch.mm, torch.matmul and torch.mul? | After reading the pytorch documentation, I still require help in understanding the difference between torch.mm, torch.matmul and torch.mul. As I do not fully understand them, I cannot concisely explain this.
B = torch.tensor([[ 1.1207],
[-0.3137],
[ 0.0700],
[ 0.8378]])
C = torch.tensor([[ 0.51... | In short:
torch.mm - performs a matrix multiplication without broadcasting - (2D tensor) by (2D tensor)
torch.mul - performs a elementwise multiplication with broadcasting - (Tensor) by (Tensor or Number)
torch.matmul - matrix product with broadcasting - (Tensor) by (Tensor) with different behaviors depending on the t... | https://stackoverflow.com/questions/73924697/ |
Pytorch low gpu util after first epoch | Hi I'm training my pytorch model on remote server.
All the job is managed by slurm.
My problem is 'training is extremely slower after training first epoch.'
I checked gpu utilization.
On my first epoch, utilization was like below image.
I can see gpu was utilized.
But from second epoch utilized percentage is almos zer... | I fixed this issue with moving my training data into local drive.
My remote server(school server) policy was storing personel data into NAS.
And file i/o from NAS proveked heavy load on network.
It was also affected by other user's file i/o from NAS.
After I moved training data into NAS, everything is fine.
| https://stackoverflow.com/questions/73944743/ |
How to convert a PyTorch nn.Module into a HuggingFace PreTrainedModel object? | Given a simple neural net in Pytorch like:
import torch.nn as nn
net = nn.Sequential(
nn.Linear(3, 4),
nn.Sigmoid(),
nn.Linear(4, 1),
nn.Sigmoid()
).to(device)
How do I convert it into a Huggingface PreTrainedModel object?
The goal is to convert the Pytorch nn.Module object from nn.Seque... | You will need to define custom configuration and custom model classes. It is important to define attributes model_type and config_class inside those classes:
import torch.nn as nn
from transformers import PreTrainedModel, PretrainedConfig
from transformers import AutoModel, AutoConfig
class MyConfig(PretrainedConfig):... | https://stackoverflow.com/questions/73948214/ |
How to use CTC Loss Seq2Seq correctly? | I am trying to create ASR model by myself and learn how to use CTC loss.
I test and I see this:
ctc_loss = nn.CTCLoss(blank=95)
output: tensor([[63, 8, 1, 38, 29, 14, 41, 71, 14, 29, 45, 41, 3]]): torch.Size([1, 13]); output_size: tensor([13])
input1: torch.Size([167, 1, 96]); input1_size: tensor([167])
After appl... | The CTC loss does not operate on the argmax predictions but on the entire output distribution. The CTC loss is the sum of the negative log-likelihood of all possible output sequences that produce the desired output. The output symbols might be interleaved with the blank symbols, which leaves exponentially many possibil... | https://stackoverflow.com/questions/73956505/ |
Multiclass classification, IndexError: Target 2 is out of bounds | I am facing a multiclass classification problem related to the activity of some drugs using Pytorch neural net, I have three activity classes (0, 1 and 2), to tackle the problem I adopted the one vs. one approach, thus creating three binary classifiers: 0 vs. 1, 1 vs. 2 and 2 vs. 0. When I train the second classifier (... | OP needed to match the output dimension of their model with the number of label classes (see discussion).
| https://stackoverflow.com/questions/73962097/ |
YOLOv7 RuntimeError: CUDA error: unknown error | Getting the following error with my current setup after following this guide when trying to train a custom model for YOLOv7: https://docs.nvidia.com/cuda/wsl-user-guide/index.html.
OS: Ubuntu (Windows 10 WSL)
Hardware: 16gb RAM, RTX 3070
Python Version: 3.8.10
Driver Version: 517.48
PyTorch Version:
>>> import... | Even on WSL, your Host is Windows and will have the same limitations.
On windows there is a watchdog that kills too long kernels (WDDM).
If your NVidia GPU is a secondary GPU, try to disable WDDM TDR.
If it's your primary GPU, you can experiment screen freezes when you use pyTorch.
there is some informations on how to ... | https://stackoverflow.com/questions/73967130/ |
filter out rows which satisfy a condition in each column | Suppose I have a tensor:
input: ([[-0.5535, 0.0000],
[ 0.0000, 0.0000],
[-1.1370, -0.2736],
[-1.2300, 0.9185]])
Output:([[-0.5535, 0.0000],
[-1.1370, -0.2736],
[-1.2300, 0.9185]])
I need to keep only the rows which have non-zero elements in all columns, and the index of th... | I will answer my own question since I found the solution in pytorch.
This function will return the row-indices of non
x[torch.nonzero(torch.tensor(x), as_tuple=True)[0].unique()]
OR
x[torch.nonzero(torch.tensor(x.sum(1)), as_tuple=True)[0]]
| https://stackoverflow.com/questions/73969621/ |
How to do multiple forward pass and one backward pass pytorch? | import torch
import torchvision.models as models
model = models.resnet18()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
x = torch.randn(1, 3, 224, 224)
y = torch.randn(1, 3, 224, 224)
#1st Approach
loss1 = model(x).mean()
loss2 = model(y).mean()
(loss1+loss2).backward()
optimizer.step()
I want to forward ... | Both of them are actually equivalent: The gradient gets acccumulated additively in the backpropagation (which is a convenient implementation for nodes that appear multiple times in the computation graph). So both of them are pretty much identical.
But to make the code readable and really make obvious what is happening,... | https://stackoverflow.com/questions/73979121/ |
PyTorch 1.12 on Mac Monterey | I cannot use PyTorch 1.12.1 on macOS 12.6 Monterey with M1 chip.
Tried to install and run from Python 3.8, 3.9 and 3.10 with the same result.
I think that PyTorch was working before I updated macOS to Monterey. And the Rust bindings, tch-rs are still working.
Here is my install and the error messages I get when trying ... | I recommend not touching your system python installations for your own projects, instead the recommended way is using conda (see here). The reason is that each conda environment encapsulates a whole separate python installation that does not interfere (and doesn't get interfered with) with any other programs. This is e... | https://stackoverflow.com/questions/73986257/ |
Why am getting pylint import and no member errors when I didn't before? | Hi I've been working on this code for months without any of the pylint errors that have suddenly appeared? How do I fix this?
| You need pandas and torch installed in the same environment than the one you run pylint.
From the documentation at https://pylint.pycqa.org/en/latest/user_guide/messages/error/no-member.html:
If you are getting the dreaded no-member error, there is a possibility that either:
pylint found a bug in your code
You're laun... | https://stackoverflow.com/questions/73998700/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.