instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
What is the impact of `pos_weight` argument in `BCEWithLogitsLoss`? | According to the pytorch doc of nn.BCEWithLogitsLoss, pos_weight is an optional argument a that takes the weight of positive examples. I don't fully understand the statement "pos_weight > 1 increases recall and pos_weight < 1 increases precision" in that page. How do you guys understand this statement?... | The binary cross-entropy with logits loss (nn.BCEWithLogitsLoss, equivalent to F.binary_cross_entropy_with_logits) is a sigmoid layer (nn.Sigmoid) followed with a binary cross-entropy loss (nn.BCELoss). The general case assumes you are in a multi-label classification task i.e. a single input can be labeled with multipl... | https://stackoverflow.com/questions/71051342/ |
Is it possible to get dataset file infromation at the time of test a model? | My dataset code is like the below one; Here, X_test is a list[list] and y_test is list[Path]
The first.py file
self.test_dataset = LongDataset(
X_path=X_test,
y_path=y_test,
transform=val_transforms,
)
The rest of the part is as usual (dataloader)
def test_da... | Essentially, what you want to do is get the index of each batch element in the batch returned by the dataloader object (from there it is trivial to index the dataset to get the desired data elements (in this case file paths).
Now the short answer is that there is no directly implemented way to return this data using th... | https://stackoverflow.com/questions/71070249/ |
std::vector, how does it store values with libtorch tensors? | When I was collecting trainable parameters as vector<torch::tensor>, I've realized that it is type cast to torch::autograd::VariableList.
With this structure, how does the vector access its element? Does it store the value's memory space even without explicitly having to call them by pointer or reference?
So I've... | This is not strange behaviour of std::vector, it is strange behaviour of torch::Tensor. The following should also exhibit it.
int a = 10;
int b = a;
b += 10;
std::cout << b << std::endl;
std::cout << a << std::endl;
torch::Tensor c = torch::ones({ 1 });
torch::Tensor d = c;
d += 10;
std::cout &... | https://stackoverflow.com/questions/71082120/ |
How do I solve error: Tensor object has not atrribute 'fold' | I have a method that divides an image into patches and change the colour of a specified patch. I tried merging the patches together after the manipulation and I got the error: AttributeError: 'Tensor' object has no attribute 'fold'
def perturb_patch(img, patch_idx, patch_size, stride):
img = img.unsqueeze(0)
p... | So, I was able to find an alternative to merge the patches together with the pytorch's view method here.
updated code:
def perturb_patch(img, patch_idx, patch_size, stride):
img = img.unsqueeze(0)
patches = img.unfold(2, patch_size, stride).unfold(3, patch_size, stride)
patches = patches.reshape(1, 3, -1, ... | https://stackoverflow.com/questions/71085164/ |
Unknown category '2' encountered. Set `add_nan=True` to allow unknown categories pytorch_forecasting | error: "Unknown category '2' encountered. Set add_nan=True to allow unknown categories" while creating time series dataset in pytorch forecasting.
training = TimeSeriesDataSet(
train,
time_idx="index",
target=dni,
group_ids=["Solar Zenith Angle", "Relative Humidity","Dew
Po... | Try adding pytorch_forecasting.data.encoders.NaNLabelEncoder(add_nan=True), as in this example:
max_prediction_length = 1
max_encoder_length = 27
training = TimeSeriesDataSet(
sales_train,
time_idx='dayofyear',
target="QTT",
group_ids=['S100','I100','C100','C101'],
min_encoder_length=0, ... | https://stackoverflow.com/questions/71098518/ |
Input 1D array with float datatype in C++ | I would like to input row = [0.160625, 0.967468297, 3.520480583, 0.862454481, -0.341933766] as entry which is float type and pass it to forward module. I used python trying to translate to C++,
I got syntax error. Support needed. Thanks!
// run not okay
// Create a vector of inputs.
std::vector<torch::ji... | Did you try replacing [] with {} as mentioned before?
float row[] = { 0.190625, 0.957468297, 4.520480583, 0.962454481, -0.241933766 };
| https://stackoverflow.com/questions/71103057/ |
stylegan3 stylegan2-ada tensor mismatch error for every 256 or 512 flickr related model | Anyone having the same tensor size mismatch when trying finetuning on ffhq,ffhqu or celebahq models with stylegan3 (and with --cfg=stylegan2)?
With afhqv2 and metfaces I had no problems at 512 and 1048 sizes.
Error:
...
File "/home/ubuntu/stylegan3/training/training_loop.py", line 162, in training_loop
m... | If you are trying to do transfer learning on "stylegan3-r-ffhqu-256x256.pkl", you should add
--cbase=16384
in your python "train.py" ...
command line
| https://stackoverflow.com/questions/71103106/ |
Intermediate layer outputs pytorch | I have Alexnet neural network:
class AlexNet(nn.Module):
def __init__(self, num_classes=100):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Con... | According to this answer
You have to split your model in different parts and create methods to access them parts such as :
class AlexNet(nn.Module):
def __init__(self, num_classes=100):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=11, stride... | https://stackoverflow.com/questions/71110235/ |
Pytorch Geometric Datasets | I need your help. I have two set of graph structured data, one from Open Graph Benchmark (OGB) and another created with torch_geometric.data.Dataset from my own data . The data looks like:
Data(edge_index=[2, 88], edge_attr=[88, 3], x=[39, 9], y=[1, 1]) #OGB
Data(x=[23, 9], edge_index=[2, 48], edge_attr=[48, 2], y=... | If you want to use the same code, you need to implement get_idx_split for your own dataset.
You can find the desired return structure in the OGB GitHub, e.g. here:
def get_idx_split(self):
< ... do something to retrieve train/test/validation set>
return {'train': train_idx, 'valid': valid_idx, 'test': tes... | https://stackoverflow.com/questions/71123148/ |
Extracting weights from SGD algorithm | So I am implementing SGD for a binary classification problem. There are 2 classes of points and I want to plot the decision boundary but I'm not sure how to extract the weights from the code to plot it.
Here is the code:
def train_model(train_dl, model):
# define the optimization
criterion = nn.BCELoss(reductio... | You do not extract this information from the SGD optimizer, this information is part of your model.
What you can do, at test time, is generate a grid of points, compute their prediction using the trained model and then plot the grid points coloring them according to the prediction.
| https://stackoverflow.com/questions/71128146/ |
How to correct when Accuracy equals F1 in Torch Lightning for binary classification? | I understand that with multi-class, F1 (micro) is the same as Accuracy. I aim to test a binary classification in Torch Lightning but always get identical F1, and Accuracy.
To get more detail, I shared my code at GIST, where I used the MUTAG dataset. Below are some important parts I would like to bring up for discussion... | You can pass multiclass=False in case your dataset is binary.
This will give you the result which matches the Sklearn F1 score output where average="binary" (default) is passed.
We can set multiclass=False to treat the inputs as binary - which is the same as converting the predictions to float beforehand.
S... | https://stackoverflow.com/questions/71131811/ |
One hot Encoding text data in pytorch | I am wondering how to one hot encode text data in pytorch?
For numeric data you could do this
import torch
import torch.functional as F
t = torch.tensor([6,6,7,8,6,1,7], dtype = torch.int64)
one_hot_vector = F.one_hot(x = t, num_classes=9)
print(one_hot_vector.shape)
# Out > torch.Size([7, 9])
But what if you have... | You can do the following:
from typing import Union, Iterable
import torchtext
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
corpus = ["The cat sat the mat", "The dog ate my homework"]
tokenizer = get_tokenizer("basic_english")
tokens ... | https://stackoverflow.com/questions/71146270/ |
How to customize threshold PyTorch | I have trained ResNet50 for binary image classification.
I want to descrease FalseNegatives by reducing threshold value.
How can I do that?
| To decrease the number of false negatives (FN) i.e. increase the recall (since recall = TP / (TP + FN)) you should increase the positive weight (the weight of the occurrence of that class) above 1. For example nn.BCEWithLogitsLoss allows you to provide the pos_weight option:
pos_weight > 1 increases the recall, pos... | https://stackoverflow.com/questions/71147379/ |
How can Python execute a line of code, then display an error indicating a crash at the previous line? | I have a script which contains (among other things) these three lines of code:
(line 138) pdb.set_trace()
(line 140) training_start_time = datetime.now()
(line 141) print(f'Network training beginning at {training_start_time}.')
Here is the output I'm seeing:
> c:\vtcproject\yolov5\roadometry_train.py(140)train()
-... | Well, this turned out to be somewhat complicated.
I removed code from my script until I found something very strange. Further down my script, below the lines listed above, I was eventually entering a loop which created an instance of tqdm for progress updates:
for epoch in range(start_epoch,
opt.epoc... | https://stackoverflow.com/questions/71163608/ |
Problem in passing value to parser argument | Running my code including this line:
def parse_args():
parser = argparse.ArgumentParser(description='test with parser')
parser.add_argument("--model", type=str, default= "E:\Script\weights\resnext101.pth")
I got this error:
OSError: [Errno 22] Invalid argument: 'E:\\Script\\weights\resnext1... | You aren't passing a path ending with the name resnext101.pth; you are passing a path ending with the name weights␍esnext101.pth, which contains a literal carriage return.
Use a raw string literal to protect all backslashes from expansion, regardless of the character that follows the backslash.
parser.add_argument(&quo... | https://stackoverflow.com/questions/71174137/ |
No module named 'model' | import numpy as np
import random
import json
import torch
import torch.nn as nn
from torch.utils.data import Dataset, DataLoader
from nltk_utils import bag_of_words, tokenize, stem
from model import NeuralNet
i keep trying to pip install NeuralNet but I keep getting
ModuleNotFoundError: No module named 'model'
I h... | I think you are supposed to import neuralnet by itself:
import neuralnet
or import model from neuralnet:
from neuralnet import model
Since model seems to be a part of the NeuralNet module rather than the other way around.
| https://stackoverflow.com/questions/71180349/ |
Setting Picture Colormap in Tensorboard with PyTorch | I'm pretty new to using Python, PyTorch and Tensorboard - moved from MATLAB due to the lacking automatic differentiation.
I am trying to use the above stated tools since I'm running an optimization problem - simple gradient descent for reconstructing distorted images. No machine learning or deep learning.
The point is ... | You can colorize your tensor shape using tensorflow gather function. Following is a simple script for doing this. You may use other maps rather than 'Spectral':
import matplotlib
import matplotlib.cm
import tensorflow as tf
def colormap(shape):
min = tf.reduce_min(shape)
max = tf.reduce_max(shape)
shape = ... | https://stackoverflow.com/questions/71184667/ |
Multiplying PyTorch tensors of different shape | I have a torch tensor of shape (32, 100, 50) and another of shape (32,100). Call these A and B respectively. I want to element-wise multiply A and B, such that each of the 50 elements at A[i, j, :] get multiplied by B[i, j], i.e.like multiplying a vector with a scalar. How can I do this via broadcasting rules?
| Just add a singleton dimension to the second tensor, for example:
a = torch.randn([32,100,50])
b = torch.randint(10,[32,100])
b = b[:,:,None] #or .unsqueeze(-1)
c = a * b
assert (c[0,0,0]/a[0,0,0]).int() == b[0,0] and (c[0,0,1]/a[0,0,1]).int() == b[0,0]
The assert on the end is just to prove that adjacent elements in... | https://stackoverflow.com/questions/71190458/ |
PyTorch Binary classification not learning | I state that I am new on PyTorch. I wrote this simple program for binary classification. I also created the CSV with two columns of random values, with the "ok" column whose value is 1 only if the other two values are included between two values I decided at the same time. Example:
diam_int,diam_est,ok
37.782... | Your model is underfit. Increasing the number of epochs to (say) 3000 makes the model predict perfectly on the examples you showed.
However after this many epochs the model may be overfit. A good practice is to use validation data (separate the generated data into train and validation sets), and check the validation lo... | https://stackoverflow.com/questions/71192650/ |
Convert Keras (TensorFlow) MaxPooling3d to PyTorch MaxPool3d | I'm Trying to convert some Keras (TensorFlow) code to Pytorch, and I'm unable to reproduce the MaxPooling3d in Keras (TensorFlow) as MaxPool3d in PyTorch.
The following code:
import torch
import torch.nn as nn
import tensorflow.keras.layers as layers
import matplotlib.pyplot as plt
kernel_size = (10, 10, 2)
strides = ... | The padding is not the same in both layers, that's why you're not getting the same results.
You set padding='same' in tensorflow MaxPooling3D layer, but there is no padding set in pytorch MaxPool3d layer.
Unfortunately, in Pytorch, there is no option for 'same' padding for MaxPool3d as in tensorflow. So, you will need... | https://stackoverflow.com/questions/71194093/ |
error then import pytorch-lightning, azure notebook | i am use microsoft azure (for students) ML servise. Then i work with notebook i can not import pytorch-lightning libary.
!pip install pytorch-lightning==0.9.0
import pytorch_lightning as pl
Here i have error:
ModuleNotFoundError Traceback (most recent call last)
Input In [1], in <module>
-... | This is rather strange but could be related to that your installation is in another location, so let's:
try where is PL installed with find -name "lightning"
also, check what is the loaded package locations python -c "import sys; print(sys.path)"
I guess that the problem will be in What's the diff... | https://stackoverflow.com/questions/71195222/ |
Having problems with Pandas when storing the results of a CNN | I have a CNN that runs well, but when I'm trying to store the error, loss and accuracy training and validation with Pandas, for some reason the Data Frame that I created has more rows than necesary (173 to be exact) and it looks like it trains more than I ask to, but while the CNN is training and validating the results... | Hmm, you should try wrapping your dictionary with brackets like so,
data = {'n': n, 'n': p, 'epoch': epoch} # etc...
pd.DataFrame([data])
If this doesn't work, you should consider converting your dictionary to a pandas dataframe using this function.
data = {'n': n, 'p': p, 'epoch': epoch} # etc...
pd.DataFrame.from_di... | https://stackoverflow.com/questions/71199665/ |
pytorch reduce_op warning message despite not calling it | I'm constantly receiving a warning message per below; despite not calling the pytorch reduce_op anywhere.
C:\Users\cocoj\.conda\envs\py39\lib\site-packages\torch\distributed\distributed_c10d.py:170: UserWarning: torch.distributed.reduce_op is deprecated, please use torch.distributed.ReduceOp instead
warnings.warn(
I... | I am also not clear on what they meant, but since they were saying that it's safe to ignore you can try using the warnings module to ignore the message like so:
import warnings
warnings.filterwarnings("ignore", message="torch.distributed.reduce_op is deprecated")
Note that it will ignore anything c... | https://stackoverflow.com/questions/71205404/ |
RuntimeError: Found dtype Double but expected Float - Pytorch RL | I am trying to get an actor critic variant of the pendulum running, but I seem to be running into a particular problem.
RuntimeError: Found dtype Double but expected Float
I saw this had come up multiple times before so I have been through those and have attempted to change the data types of my loss (kept in comments)... | Answering here in case anyone has similar issues in the future.
The output of the reward in OpenAI Gym Pendulum-v0 is a double, so when you compute the return over the episode you need to change that to a float tensor.
I did this just by:
returns = torch.tensor(returns)
returns = (returns - returns.mean())/(returns.std... | https://stackoverflow.com/questions/71224852/ |
How to serve a model in sagemaker? | based on documentation provided here , https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#model-directory-structure, the model file saved from training is model.pth. I also read that it can be .pt extension or even bin extension. I have seen a example of pytorch_model.bin, but when i tried... | Interesting question.
I'm assuming you're trying to use the PyTorch container from SageMaker in what we call "script mode" - where you just provide the .py entrypoint.
Have you tried to define a model_fn() function, where you specify how to load your model? The documentation talks about this here.
More detail... | https://stackoverflow.com/questions/71230870/ |
Preparing CSV file for neural network machine learning Python | I'm taking a course about machine learning in my undergrad studies and I have a problem where I don't know to load a CSV file into Dataloader then test it, can someone guide me through the process?
you can download the CSV files from this link if you wish https://ufile.io/f/abdd9
Here is the code
import tensorflow as ... | To do it properly with a Dataset and a Dataloader, you need to create a custom dataset:
import pandas as pd
from torch.utils.data import Dataset
class CustomMnistDataset(Dataset):
def __init__(self, csv_file):
data = pd.read_csv(csv_file)
self.labels = np.array(data["label"])
self... | https://stackoverflow.com/questions/71233673/ |
Generating histogram feature of 2D tensor from 3D Tensor feature set | I have a 3D tensor of dimensions (3,4 7) where each element in 2-dim(4) has 7 attributes.
What I want is to take the 4th attribute of all 4 elements and to calculate the histogram having 3 hist values and store those values only. And ending up with a 2D tensor of shape (3,4). I have a small toy example for the task tha... | import torch
torch.manual_seed(1)
bins = 3
feature = torch.randint(1, 50, (3, 4,7))
attrbute_val = feature[:,:,3].float() # read all 4 elements in the 2nd dimension
# and the fourth element in the 3rd dimension.
final_tensor = torch.empty((bins,bins))
tuple_rows = torch.tensor_... | https://stackoverflow.com/questions/71239735/ |
How to create unnamed PyTorch parameters in state dict? | I am trying to load a model checkpoint (.ckpt file) for transfer learning. I do not have the model's source code, so I am trying to recreate it with PyTorch, like this:
import torch
import torch.nn as nn
import torch.nn.functional as F
class IngrDetNet(nn.Module):
def __init__(self):
super(IngrDetNet, self... | The reason why there is a full mismatch of the keys is that you are using the nn.DataParallel module utility. This means it will wrap your original parent model under a wrapper "model" nn.Module. In other words:
>>> model = IngrDetNet() # model is a IngrDetNet
>>> model = to... | https://stackoverflow.com/questions/71240311/ |
how to load two dataset images simultaneously for train two streams(Pytorch) | i need load identical two dataset suppose one dataset has RGB images and another dataset contain same image with different processed(grey images) with same order same size,
datasetA=[1.jpg,2.jpg,..........n.jpg] // RGB
datasetA=[g1.jpg,g2.jpg,..........gn.jpg] //grey
so I need to feed the same order images to two ind... | I think he easiest way to go about this is to construct a custom Dataset that handles both:
class JointImageDataset(torch.utils.data.Dataset):
def __init__(self, args_rgb_dict, args_grey_dict):
# construct the two individual datasets
self.rgb_dataset = ImageFolder(**args_rgb_dict)
self.grey_dataset = Imag... | https://stackoverflow.com/questions/71247325/ |
when use conv and deconv, the out put shape does not math(The input image's weight is odd) | such as the input shape=[1,64,12,60,33]
when i use
nn.Conv3d(in_channels=128, out_channels=64, kernel_size=(3, 3, 3), stride=2, padding=1)
the out put shape =[1,64,6,30,17]
after that i want to let the output return to [1,64,12,60,33]
but when i use
nn.ConvTranspose3d(in_channels=128, out_channels=64, kernel_size=(3,... | If you're dealing with tensors of arbitrary shapes, this can be difficult. If they're fixed you can add ad hoc fixes which should solve your problem. One way is to utilise the fact that you can pass tuples to the arguments padding and output_padding, which will work in your case:
input = torch.randn((1,64,12,60,33))
C3... | https://stackoverflow.com/questions/71247537/ |
How to show wandb training progress from run folder | After training neural networks with wandb as the logger, I received a link to show the training results and a folder named "run-...", I assume that is the logging of the training process. Now I don't have that link, how to show the wandb training process from run folder?
| The run folder name is constructed as run-<datetime>-<id>.
You can find the logs on the UI platform as long as you haven't yet deleted it online. I'm not sure it is yet possible to resync the local copy to the cloud.
One way to find your run across projects is to go on your profile page: https://wandb.ai/&l... | https://stackoverflow.com/questions/71257152/ |
Select on second dimension on a 3D pytorch tensor with an array of indexes | I am kind of new with numpy and torch and I am struggling to understand what to me seems the most basic operations.
For instance, given this tensor:
A = tensor([[[6, 3, 8, 3],
[1, 0, 9, 9]],
[[4, 9, 4, 1],
[8, 1, 3, 5]],
[[9, 7, 5, 6],
[3, 7, 8, 1]]])
And this other tensor:... | Ok, my mistake was to assume this:
A[:, B]
is equal to this:
A[[0, 1, 2], B]
Or more generally the solution I wanted is:
A[range(B.shape[0]), B]
| https://stackoverflow.com/questions/71262004/ |
FileNotFoundError: Entity folder does not exist! in Google Colab | Can anyone help me in sorting out this issue?
When I run these lines in Colab
:param files_name: containing training and validation samples list file.
:param boxes_and_transcripts_folder: gt or ocr result containing transcripts, boxes and box entity type (optional).
:param images_folder: whole images file folder
:param... | There is error in https://github.com/wenwenyu/PICK-pytorch/blob/master/config.json file. you have to change the path of data as per your working directory. Check line number 61 to 64 and 73 to 76.
| https://stackoverflow.com/questions/71277138/ |
Cant get the right yolor pre trained weights in YOLOR | I'm training a custom dataset in yolor. I successfully run its once but after some time, I cant manage to do it very well.
The first error I noticed is in the training part:
Traceback (most recent call last): File "train.py", line 537, in <module>
train(hyp, opt, device, tb_writer, wandb) File &... | For me, the easiest way was to download data on my laptop, then upload them and replace current HTML weights with the correct ones.
You will find two weights link to google drive in the get_pretrain.sh file
yolor_p6.pt: https://drive.google.com/uc?export=download&id=1Tdn3yqpZ79X7R1Ql0zNlNScB1Dv9Fp76
yolor_w6.pt: ht... | https://stackoverflow.com/questions/71278688/ |
How to convert a (M, L) tensor to (N, L) based on counts vector of size (N) where M is sum of counts, using aggregation by adding | So I have a 2D tensor A of shape (M, L) and I want to convert it into B, a (N, L) tensor.
I also have a counts tensor C (N) which has the counts of how many rows belong to which group such that sum(C) = M.
For example :
# shape = (6, 3)
A = torch.tensor([[1, 2, 3],
[4, 5, 6],
[1, 1, ... | You should use torch.cumsum to solve your problem:
Your output is simply the cumulative sum of rows up to the row induces of C. Taking the diff of the cumulative sum from the beginning of the tensor will give you the sum over the intervals you want:
B = torch.cat((torch.zeros_like(A[:1,:]), A.cumsum(dim=0)[C.cumsum(dim... | https://stackoverflow.com/questions/71282460/ |
Finding patterns in time series with PyTorch | I started PyTorch with image recognition. Now I want to test (very basically) with pure NumPy arrays. I struggle with getting the setup to work, so basically I have vectors with values between 0 and 1 (normalized curves). Those vectors are always of length 1500 and I want to find e.g. "high values at the beginning... |
This is just a copy-paste from an RNN demo. Here is my first issue. Is an RNN the right choice?
In theory what model you choose does not matter as much as "How" you formulate your problem.
But in your case the most obvious limitation you're going to face is your sequence length: 1500. RNN store information ... | https://stackoverflow.com/questions/71285755/ |
Failed to install PyTorch | I tried my best to install Pytorch but each and every time I failed to install it.
Conda version: 4.6.14
I have used Preview(Nightly) and LTS versions to install but for both of times I have faced the same error like Solving environment: | Killed .
Preview(Nightly) command: conda install pytorch torchvision torchaud... | have you tried installing pytorch into a new environment? problems usually arise when you try to install it into your base environment.
conda create -n (NameOfEnviroment) -c pytorch pytorch torchvision
conda update --all
| https://stackoverflow.com/questions/71298721/ |
Using Focal Loss for imbalanced dataset in PyTorch | I found this implementation of focal loss in GitHub and I am using it for an imbalanced dataset binary classification problem.
# IMPLEMENTATION CREDIT: https://github.com/clcarwin/focal_loss_pytorch
class FocalLoss(nn.Module):
def __init__(self, gamma=0.5, alpha=None, size_average=True):
super(FocalLoss... | Unlike BCEWithLogitLoss, inputting the same arguments as you would use for CrossEntropyLoss solved the problem:
#loss = criterion(m(output[:,1]-output[:,0]), labels.float())
loss = criterion(output, labels)
Credits to Piotr from NVidia
| https://stackoverflow.com/questions/71300607/ |
Optimising model.parameters and custom learnable parameter together using torch.optim gives non-leaf tensor error | Framework: PyTorch
I am trying to optimise a custom nn.parameter(Temperature) used in softmax calculation along with the model parameters using a single Adam optimiser while model training. But doing so gives the following error:
ValueError: can't optimize a non-leaf Tensor
Here is my custom loss function:
class Cros... | Got it working by doing so:
params = list(model.parameters())
params.append(criterion.temperature)
| https://stackoverflow.com/questions/71305809/ |
Pytorch loss.backward() gives none grad for parameters of Rx, Ry Gate | I'm trying to train parameters params by performing linear Transformation on an input tensor x by matrix multiplying Rx to input followed by Ry matrix to their result. (each matrix Rx and Ry have a parameter params[i] each that define the matrix).
then I calculate loss by mse of y and the predicted output. when I do lo... | Good observation, you indeed have a correct backpropagation of the gradient through the gradient. So why are you getting none when accessing your parameter?
The reason why you can't access the gradient of this parameter is that only leaf tensors have their gradient cached in memory. Here, since params is a copy of a l... | https://stackoverflow.com/questions/71309024/ |
Log metrics with configuation in Pytorch Lightning using w&b | I am using PyTorch Lightning together with w&b and trying associate metrics with a finite set of configurations. In the LightningModule class I have defined the test_step as:
def test_step(self, batch, batch_idx):
x, y_true, config_file = batch
y_pred = self.forward(x)
accuracy = self.accuracy(y_pred, y_true... | I work at W&B. You could log your config variables using wandb.config, like so:
wandb.config['my_variable'] = 123
And then you'll be able to filter your charts by whatever config you'd logged. Or am I missing something.
Possibly the save_hyperparameters call might even grab these config values automatically (from ... | https://stackoverflow.com/questions/71312243/ |
How can I apply NMS (non-maximum suppression) on multiple images from a dataloader efficiently (PyTorch)? | I have the following function defined for non-maximum suppression (NMS) post processing on my predictions.
At the moment, it is defined for a single prediction or output:
from torchvision import transforms as torchtrans
def apply_nms(orig_prediction, iou_thresh=0.3):
# torchvision returns the indices of the... | Have a look at the Generic Trnasform paragraph in the torchivision doc page you can use torchvision.transform.Lambda or work with functional transforms.
Here is an example with Lambda
nms_transform = torchvision.transforms.Lambda(apply_nms)
Then, you can apply the transform with the transform parameter of your dataset... | https://stackoverflow.com/questions/71316130/ |
optimizing multiple loss functions in pytorch | I am training a model with different outputs in PyTorch, and I have four different losses for positions (in meter), rotations (in degree), and velocity, and a boolean value of 0 or 1 that the model has to predict.
AFAIK, there are two ways to define a final loss function here:
one - the naive weighted sum of the losses... | This is not a question about programming but instead about optimization in a multi-objective setup. The two options you've described come down to the same approach which is a linear combination of the loss term. However, keep in mind there are many other approaches out there with dynamic loss weighting, uncertainty wei... | https://stackoverflow.com/questions/71317141/ |
Unable to install Torch with pipenv | I tried following this tutorial after not being able to lock with pipenv install torch I am using Linux Mint 20.3 una
pipenv install --extra-index-url https://download.pytorch.org/whl/cu113/ "torch==1.10.1+cu113"
caused this problem after a long 'installing torch...' stage:
Error: An error occurred while ins... | I solved it, I don't have those GPUs so I have to use the third command line of the tutorial
pipenv install --extra-index-url https://download.pytorch.org/whl/ "torch==1.10.1+cpu"
Installing torch==1.10.1+cpu...
Adding torch to Pipfile's [packages]...
✔ Installation Succeeded
Pipfile.lock... | https://stackoverflow.com/questions/71321081/ |
What is cudaLaunchKernel in pytorch profiler output | I'm trying to profile my pytorch network to see what is the bottleneck. I noticed that there is an operation called cudaLaunchKernel which is taking up most of the time. This answer says that it is called for every operation done with cuda. If suppose I implement this network in C++ or any other language, would it be p... | According to CUDA docs, cudaLaunchKernel is called to launch a device function, which, in short, is code that is run on a GPU device.
The profiler, therefore, states that a lot of computation is run on the GPU (as you probably expected) and this requires the data structures to be transferred on the device. This may be ... | https://stackoverflow.com/questions/71328662/ |
Pytorch Forecasting vs Darts, experiences welcome | I was wondering which package to use between pytorch forecasting (https://pytorch-forecasting.readthedocs.io/en/stable/) or darts (https://unit8co.github.io/darts/). I have been trying both, it looks like darts is more sklearn-like in its writing and style and pytorch forescasting uses different data classes.
Any comme... | I think one of the biggest advantage of darts is its Timeseries Object which is very pandas-like and very intuitive when you are familiar with sklearn. However, I also do see the advantage that pytorch-forecasting dealt with categorical data "better" (easier) and it takes a steeper learning curve to understan... | https://stackoverflow.com/questions/71335323/ |
RuntimeError: mat1 and mat2 shapes cannot be multiplied (4000x20 and 200x441) | The architecture of the decoder of my variational autoencoder is given in the snippet below
class ConvolutionalVAE(nn.Module):
def __init__(self, nchannel, base_channels, z_dim, hidden_dim, device, img_width, batch_size):
super(ConvolutionalVAE, self).__init__()
self.nchannel = nchannel
... | Matrix multiplication requires the 2 inner dimensions to be the same. You are getting the error: RuntimeError: mat1 and mat2 shapes cannot be multiplied (200x441 and 200x441) because your inner dimensions don't line up.
for example:
shape(200, 441) * shape(441, 200) # works
shape(441, 200) * shape(200, 441) # works
sha... | https://stackoverflow.com/questions/71345425/ |
How do I compute batched sample covariance in PyTorch? | Say I have data, a batched tensor of collections of data points of size (B, N, D) where B is my batch size, N is the number of data samples in each collection, and D is the length of my data vectors. I want to compute the sample mean and covariance for each collection of data points, but do it in batch.
To compute the ... | This does the trick:
def batch_cov(points):
B, N, D = points.size()
mean = points.mean(dim=1).unsqueeze(1)
diffs = (points - mean).reshape(B * N, D)
prods = torch.bmm(diffs.unsqueeze(2), diffs.unsqueeze(1)).reshape(B, N, D, D)
bcov = prods.sum(dim=1) / (N - 1) # Unbiased estimate
return bcov #... | https://stackoverflow.com/questions/71357619/ |
Pytorch netwrok with variable number of hidden layers | I want to create a class that creates a simple network with X fully connected layers, where X is an input given by the user. I tried this using the setattr/getattr but for some reason is not working.
class MLP(nn.Module):
def __init__(self,in_size, out_size,n_layers, hidden_size):
super(MLP,self).__init__... | This seems like a problem with forward implementation with the mod2 function. Try the pytorch functions (torch.fmod and torch.remainder) or if you don't need the backprop capabilities try to do .detach() before the mod2 function.
| https://stackoverflow.com/questions/71369361/ |
How to handle that error in pytorch: expected Long but found double | I'm given a function that is supposed to calculate the square-root of a matrix
import torch
from torch.autograd import Function
class MatrixSquareRoot(Function):
"""Square root of a positive definite matrix.
NOTE: matrix square root is not differentiable for matrices with
zero eigenvalues.
See L... | just change the tensor type as follows
x = torch.tensor([[1,-12],[0,4]],dtype=torch.float)
sqrtm(x)
| https://stackoverflow.com/questions/71371124/ |
Segfault while importing torchvision.transforms | I'm getting a segfault in python during imports.
This code:
import os
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
print("was there")
from torchvision import transforms
print("didn't get there")
from torc... | So I moved the torchvision.transforms import to above the matplotlib.pyplot one, and somehow neither torchvision.transforms nor torchvision.models cause a segfault anymore. It still caused a segfault with torchvision.transforms right after matplotlib.pyplot.
Here is what the final code looks like:
import os
from torchv... | https://stackoverflow.com/questions/71372006/ |
Difference between model.parameters and model.parameters(), pytorch | I have read through the documentation and I don't really understand the explanation. Here is the explanation I got from the documentation Returns an iterator over module parameters. Why does model.parameters() return the file location e.g <generator object Module.parameters at 0x7f1b90c29ad0>. model.parameters wi... | model.parameters()
It's simply because it returns an iterator object, not a list or something like that. But it behaves quite similar to a list. You can iterate over it eg with
[x for x in model.parameters()]
Or you can convert it to a list
[list(model.parameters())]
Iterators have some advantages over lists. Eg they a... | https://stackoverflow.com/questions/71376622/ |
Dict support in PyTorch | Does PyTorch support dict-like objects, through which we can backpropagate gradients, like Tensors in PyTorch?
My goal is to compute gradients with respect to a few (1%) elements of a large matrix. But if I use PyTorch's standard Tensors to store the matrix, I need to keep the whole matrix in my GPU, which causes probl... | It sounds like you want your parameter to be a torch.sparse tensor.
This interface allows you to have tensors that are mostly zeros, with only a few non-zero elements in known locations. Sparse tensors should allow you to significantly reduce the memory footprint of your model.
Note that this interface is still "u... | https://stackoverflow.com/questions/71395783/ |
Does Fine-tunning Bert Model in multiple times with different dataset make it more accuracy? | i'm totally new in NLP and Bert Model.
What im trying to do right now is Sentiment Analysis on Twitter Trending Hashtag ("neg", "neu", "pos") by using DistilBert Model, but the accurazcy was about 50% ( I tried w Label data taken from Kaggle).
So here is my idea:
(1) First, I will Fine-tun... | If you want to fine-tune a sentiment classification head of BERT for classifying tweets, then I'd recommend a different strategy:
IMDB dataset is a different kind of sentiment - the ratings do not really correspond with short post sentiment, unless you want to focus on tweets regarding movies.
using classifier output... | https://stackoverflow.com/questions/71404582/ |
Python Pytorch Multiprocessing Pycharm PicklingError: Can't pickle : attribute lookup train on __main__ failed | This error happens when running multiprocessing (using spawn method) in Python or Pytorch (torch.multiprocessing) using Pycharm 2021.2.3.
The function train is defined at the top level of the module, so it should be pickable. However, the error says that it cannot be pickled.
A simple code may look like this:
def train... | Seems like this is a bug in Pycharm 2021.2.3 and happens when Run with Python Console is checked in run configurations. This bug is being tracked at https://youtrack.jetbrains.com/issue/PY-50116
This can be resolved using the following two options (until the bug is resolved):
Uncheck Run with Python Console
Downgrade ... | https://stackoverflow.com/questions/71417006/ |
Simple MultiGPU during inference with huggingface | I have two GPU.
How can I use them for inference with a huggingface pipeline?
Huggingface documentation seems to say that we can easily use the DataParallel class with a huggingface model, but I've not seen any example.
For example with pytorch, it's very easy to just do the following :
net = torch.nn.DataParallel(mode... | I found it's not possible with the pipelines, so:
two ways :
Do it with the Trainer object in huggingface , which also supports inferences, but it's not optimal.
Use Queues from the multiprocessing standard library, but this creates a lot of boiler plate code
| https://stackoverflow.com/questions/71417355/ |
How does Pytorch no_grad function for a = a - b and a -= b type of operation? | import torch
def model(x, W, b):
return x@W + b
def mse(t1, t2):
diff = t1 - t2
return torch.sum(diff * diff) / diff.numel()
inputs = torch.rand(2, 3, requires_grad=True)
targets = torch.rand( 2,2, requires_grad=True)
W = torch.rand(3, 2, requires_grad=True)
b = torch.rand(2, requires_grad=True)
pred ... | Keep in mind in both scenarios you are under the torch.no_grad context manager which by effect disables gradient computation.
On one hand, you are performing an in-place operation on your tensor which means their underlying data gets modified without changing the reference two that tensor storage in memory, moreover it... | https://stackoverflow.com/questions/71420187/ |
How to slice 2D Torch tensor individually per row? | I have a 2D tensor in Pytorch that I would like to slice:
x = torch.rand((3, 5))
In this example, the tensor has 3 rows and I want to slice x, creating a new tensor y that also has 3 rows and num_col cols.
What's challenging for me is that I want to slice different columns per row. All I have is x, num_cols, and idx, ... | You could use fancy indexing together with broadcasting. Another solution might be to use torch.gather which is similar to numpy's take_along_axis. Your idx array would need to be extended with the extra column:
x = torch.arange(15).reshape(3,-1)
idx = torch.tensor([1,2,3])
idx = torch.column_stack([idx, idx+1])
torch... | https://stackoverflow.com/questions/71425677/ |
How is self() used in Pytorch to generate predictions? | class MNIST_model(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(input_size, num_classes)
def forward(self, xb):
xb = xb.reshape(-1, 28 * 28)
out = self.linear(xb)
return out
def training_step(self, batch):
images, labels = ba... | This is actually nothing specific to PyTorch but rather to how Python works.
Using parenthesis on an object or directly on self inside that class will call a special Python function named __call__. This function is available to your class because you're inheriting from nn.Module which implemented it for you.
Here's a m... | https://stackoverflow.com/questions/71427254/ |
Pytorch Python Distributed Multiprocessing: Gather/Concatenate tensor arrays of different lengths/sizes | If you have tensor arrays of different lengths across several gpu ranks, the default all_gather method does not work as it requires the lengths to be same.
For example, if you have:
if gpu == 0:
q = torch.tensor([1.5, 2.3], device=torch.device(gpu))
else:
q = torch.tensor([5.3], device=torch.device(gpu))
If I ... | As it is not directly possible to gather using built in methods, we need to write custom function with the following steps:
Use dist.all_gather to get sizes of all arrays.
Find the max size.
Pad local array to max size using zeros/constants.
Use dist.all_gather to get all padded arrays.
Unpad the added zeros/constants... | https://stackoverflow.com/questions/71433507/ |
output with shape [64, 1] doesn't match the broadcast shape [64, 2] | I got above error when trying to pass weighted class to BCELoss (using pytorch). As you can see below. My model is Resnet with Sigmoid. I guess the model expect one class value instead of two becouse its Sigmoid.
But which one of the value percentage, I should pass. The percentage of postive value (with 1) or negative... | The weights passed to BCELoss are not class weights. They rescale the contribution of each element in the batch.
From the docs:
a manual rescaling weight given to the loss of each batch element. If
given, has to be a Tensor of size nbatch.
| https://stackoverflow.com/questions/71444220/ |
Why tanh function return different in tensorflow and pytorch? | I find that tensorflow and pytorch tanh result is different, I want to know why did this happen?
I know that the difference is very small, so is this acceptable?
import numpy as np
import tensorflow as tf
import torch
np.random.seed(123)
tf.random.set_seed(123)
torch.manual_seed(123)
batch, sentence_length, embedding... | Running your code with the following line at the end:
print(np.allclose(tf_out.numpy(), pt_out.numpy())) # Returns True
You will receive True. I do not know exactly how tensorflow and pytorch compute the tanh oppeartion, but when working with floating points, you rarely are exactely equal. However, you should be rece... | https://stackoverflow.com/questions/71446623/ |
Pytorch: How to make a custom Dataloader for CNN? | I'm trying to create my own Dataloader from a custom dataset for a CNN. The original Dataloader was created by writing:
train_loader = torch.utils.data.DataLoader(mnist_data, batch_size=64)
If I check the shape of the above, I get
i1, l1 = next(iter(train_loader))
print(i1.shape) # torch.Size([64, 1, 28, 28])
print... | I don't have access to your x_train and y_train, but probably this works:
from torch.utils.data import TensorDataset, DataLoader
# use x_train and y_train as numpy array without further modification
x_train = np.array(trainset.data)
y_train = np.array(trainset.targets)
# convert to numpys to tensor
tensor_x = torch.T... | https://stackoverflow.com/questions/71453455/ |
Altering pytorch resnet head from sigmoid to Softmax | I'm new to pytorch. I wrote the below code to do predication using Resnet with Sigmoid for binary classification. I just need to change it to softmax because I might have more than 2 classes.
I understood that pytorch, unlike, Keras, the softmax is in the CrossEntropyLoss. So I'm not sure how could I change the top lay... | You can try this:
model.fc[1] = torch.nn.Softmax(10)
where 10 are the number of classes, you can put value based on your needs.
| https://stackoverflow.com/questions/71462468/ |
How to measure performance of a pretrained HuggingFace language model? | I am pretraining a GPT2LMHeadModel using Trainer as follows:
training_args = TrainingArguments(
output_dir=str(project_root / 'models/bn-gpt2/'),
overwrite_output_dir=True,
num_train_epochs=1,
per_device_train_batch_size=1,
per_device_eval_batch_size=1,
gradient_accumulation_steps=4,
fp16=Tr... | If I understand it correctly then this tutorial shows how to calculate perplexity for the entire test set. If I see it correctly they use the entire test corpus as one string connected by linebreaks, which might have to do with the fact that perplexity uses a sliding window which uses the text that came previous in the... | https://stackoverflow.com/questions/71466639/ |
Unable to train PyTorch model in GPU. Keep getting errors that tensors are not on same device | I have been stuck at trying to train my PyTorch model in GPU. The model perfectly works in CPU though. I have been using Google Colab's GPU resources for using cuda.
I know that in order to run a model in GPU, the 'model', 'input features' and 'target' needs to be in 'cuda' device.
But, no matter what I do in my code, ... | Your self.hidden is a tuple of torch.tensors. PyTorch doesn't automatically move these kind of tensor to GPU when .to(device) is invoked on your model.
You can either:
Implement your own to(self, type, device) method for your BiLSTM_CRF class. (Not recommended).
Make self.hidden a registered buffer. This way all metho... | https://stackoverflow.com/questions/71467398/ |
Why am I getting different results when I use models with the same weights in different formats - \(.pt) \.onnx \(.bin, .xml)? | I have a model trained on YOLOv5s and is working fine.
This is an input image:
I can get an expected result using pytorch after doing an inference:
This is an output image:
The thing is, I need it in Openvino and regardless if I do the inference using the model in .onnx or .bin and .xml (for openvino) I won't get th... | Based on my replication, this issue occurred due to incorrect conversion from PyTorch to ONNX. I’ve found that the converted ONNX from the PyTorch model was able to detect the object (bucket) but did not reflect the correct label as it took one of the class names from coco128.yaml.
You may need to retrain your model by... | https://stackoverflow.com/questions/71470314/ |
How to add data augmentation with albumentation to image classification framework? | I am using pytorch for image classification using this code from github.
I need to add data augmentation before training my model,
I chose albumentation to do this.
here is my code when I add albumentation:
data_transform = {
"train": A.Compose([
A.RandomResizedCrop(224,224),
... | This Albumentations function takes a positional argument 'image' and returns a dictionnary. This is a sample to use it :
transforms = A.Compose([
A.augmentations.geometric.rotate.Rotate(limit=15,p=0.5),
A.Perspective(scale=[0,0.1],keep_size=False,fit_output=False,p=1),
A.... | https://stackoverflow.com/questions/71476099/ |
Why I get "RuntimeError: CUDA error: the launch timed out and was terminated" when using Google Cloud compute engine | I have a Google cloud compute engine with 4 Nvidia K80 GPU and Ubuntu 20.04 (python 3.8). When I try to train the yolo5 model, I get the following error:
RuntimeError: CUDA error: the launch timed out and was terminated
CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below m... | We are also running CUDA in the Google Cloud and our server restarted roughly when you posted your question. While we couldn't detect any changes, our service couldn't start due to "RuntimeError: No CUDA GPUs are available".
So there are some similarities, but also some differences.
Anyway, we opted for the g... | https://stackoverflow.com/questions/71491932/ |
can't import torchtext.legacy.data |
as i know, from torchtext 0.9.0, torchtext.data and torchtext.dataset are moved to torchtext.legacy
but my 0.12.0 torchtext can't import torchtext.legacy
while it can import torchtext.data
I tried if it moved to torchtext.data again but I can't find any document
torch.version == 1.11.0
| I also faced the same problem wtih the same versions. The only thing I was able to do about it is to install previous version of torchtext:
pip install torchtext==0.6.0
Only then was I wable to import the packs.
| https://stackoverflow.com/questions/71493451/ |
Pytorch RuntimeError: CUDA out of memory with a huge amount of free memory | While training the model, I encountered the following problem:
RuntimeError: CUDA out of memory. Tried to allocate 304.00 MiB (GPU 0; 8.00 GiB total capacity; 142.76 MiB already allocated; 6.32 GiB free; 158.00 MiB reserved in total by PyTorch) If reserved memory is >> allocated memory try setting max_split_size_... | I tried hours til i found out:
to reduce the batch size
and the resize my input image image size
| https://stackoverflow.com/questions/71498324/ |
How to train MLM model XLM Roberta large on google machine specs fastly with less memory | I am fine tuning masked language model from XLM Roberta large on google machine specs.
I made couple of experiments and was strange to see few results.
"a2-highgpu-4g" ,accelerator_count=4, accelerator_type="NVIDIA_TESLA_A100" on 4,12,672 data batch size 4 Running ( 4 data*4 GPU=16 data points)
&quo... | I was facing a similar dilemma some days ago when I came across this enlightening article from Hugginface.
I did the experiments myself and could see the improvements in training. As I'm working with a Tesla T4, the following configuration allows me to resume training:
training_args = TrainingArguments(
output_dir=f'... | https://stackoverflow.com/questions/71500193/ |
Why, using Huggingface Trainer, single GPU training is faster than 2 GPUs? | I have a VM with 2 V100s and I am training gpt2-like models (same architecture, fewer layers) using the really nice Trainer API from Huggingface. I am using the pytorch back-end.
I am observing that when I train the exact same model (6 layers, ~82M parameters) with exactly the same data and TrainingArguments, training ... | Keeping this here for reference. The cause was "gradient_checkpointing": true,. The slowdown induced by gradient checkpointing appears to be larger on 2 GPUs than on a single GPU. I don't really know the cause of this issue, if anyone knows I would really appreaciate someone telling me.
| https://stackoverflow.com/questions/71500386/ |
pip does not find the cudatoolkit that conda has installed | I'm trying to install torch_scatter with pip. However it gives me an error message:
File "/home1/huangjiawei/miniconda3/envs/lin/lib/python3.8/site-packages/torch/utils/cpp_extension.py", line 404, in build_extensions
self._check_cuda_version()
File "/home1/huangjiawei/miniconda3/envs... | This error is complaining that your system CUDA compiler (nvcc) version doesn't match. cudatoolkit you installed in conda is CUDA runtime. These two are different components.
To install CUDA compiler, you need to install the CUDA toolkit from NVIDIA
| https://stackoverflow.com/questions/71502107/ |
Pytorch loss is nan | I'm trying to write my first neural network with pytorch.
Unfortunately, I encounter a problem when I want to get the loss.
The following error message:
RuntimeError: Function 'LogSoftmaxBackward0' returned nan values in its 0th output.
So I tried debugging and found something strange.
The input has no nans and infs a... | Sorry, my reputation is not enough for me to comment directly. This may be caused by the exploding gradient due to the excessive learning rate. It is recommended that you reduce the learning rate or use weight_decay.
| https://stackoverflow.com/questions/71503683/ |
An error with Omegaconf when running continuous image generation code | I found this author's PiggybackGAN code on Github (about continuous learning image generation)
The link below: https://github.com/kaushik333/Piggyback-GAN-Pytorch
The github issue has this problem,but no one has solved.
I want to run this code in my Linux environment. After configuring the environment and data set, I g... | OmegaConf does not support assignment of non primitive types to the config. This have changed years ago.
There is a possibility that the author used a very old version of OmegaConf that did allow for this assignment, but based on his environment.yaml file he is using 2.0.6 which does not support it.
Contact the author ... | https://stackoverflow.com/questions/71506444/ |
How to handle hidden-cell output of 2-layer LSTM in PyTorch? | I have made a network with a LSTM and a fully connected layer in PyTorch. I want to test how an increase in the LSTM layers affects my performance.
Say my input is (6, 9, 14), meaning batch size 6, sequence size 9, and feature size 14, and I'm working on a task that has 6 classes, so I expect a 6-element one-hot-encode... | The hidden state shape of a multi layer lstm is (layers, batch_size, hidden_size) see output LSTM. It contains the hidden state for each layer along the 0th dimension.
In your example you convert the shape into two dimensions here:
hidden_1 = hidden_1.view(-1, self.hidden_size)
this transforms the shape into (batch_si... | https://stackoverflow.com/questions/71508824/ |
TypeError: DataLoader found invalid type: |
TypeError: DataLoader found invalid type: <class 'numpy.ndarray'>
Hi everyone, I have encountered difficulties, I can't find a solution, please help.
The program encountered an error at the train_fn () function.
train.py
from sklearn.preprocessing import StandardScaler
import joblib
from tqdm import tqdm
import... | Slightly late, but in case anyone else encounters a similar issue - torch_geometric.loader.DataLoader cannot handle numpy arrays, so you must convert them to torch.Tensor in your dataset first. Alternatively, you could pass a custom collate function to the dataloader.
In this particular case, your DKTDataset returns tu... | https://stackoverflow.com/questions/71512763/ |
How to use gather() in python to return values at specific indices of a tensor | I have a tensor which looks like this:
tensor([[-0.0150, 0.1234],
[-0.0184, 0.1062],
[-0.0139, 0.1113],
[-0.0088, 0.0726]])
And another that looks like this:
tensor([[1.],
[1.],
[0.],
[0.]])
I want to return the values from the first tensor, for each row, that corresponds to the indice fro... | You are missing the dim argument.
You can see an example here: https://pytorch.org/docs/stable/generated/torch.gather.html
For your case I think that return torch.gather(tensor1, 1, tensor2) should work
| https://stackoverflow.com/questions/71526425/ |
Fast GPU computation on PyTorch sparse tensor | Is it possible to do operations on each row of a PyTorch MxN tensor, but only at certain indices (for instance nonzero) to save time?
I'm particularly interested in the case of M and N very large where only a few elements on each row aren't null.
(Toy example) From this large tensor:
Large = Tensor([[0, 1, 3, 0, 0, 0],... | You might be interested in the Torch Sparse functionality. You can convert a PyTorch Tensor to a PyTorch Sparse tensor using the to_sparse() method of the Tensor class.
You can then access a tensor that contains all the indices in Coordinate format by the Sparse Tensor's indices() method, and a tensor that contains the... | https://stackoverflow.com/questions/71531822/ |
Convert nn.Linear to nn.Conv1d | The format I want to output my model to doesn't support nn.Linear, so I'd like to change it to do the exact same thing but with nn.Conv1d.
My input is of shape (N, A, B) and I'd like to have a linear layer that transforms that into an output of shape (N, A, C). Previously, I was doing this with the layer nn.Linear(B, C... | Yes this is essentially doing the same thing.
Instead of transposing you could just add a trailing dummy dimension by doing
t1 = t1.unsqueeze(-1)
...
t2 = t2.squeeze(-1)
This has the advantage that the data doesn't have to be reordered, but the effect is probably negligible.
| https://stackoverflow.com/questions/71532599/ |
open and read PT. file using python code by pytorch | I want to read a PT file with python and I don't know how, I want to open it with python
can you help me please, any ideas?
| If your .PT file is related to the weight and bias of a model.
You must first install pytorch in your pc.
for more information install go to this
then use this :
model = torch.load(PATH)
saving_loading_models
You could iterate the parameters to get all weight and bias params via:(see weitht and bias)
for param in m... | https://stackoverflow.com/questions/71533654/ |
How to evaluate a trained model in pytorch? | I have trained a model and save model using torch.save. Then after training I have loaded the model using train.load but I am getting this error
Traceback (most recent call last):
File "/home/fsdfs.py", line 219, in <module>
test(model, 'cuda', testloader)
File "/home/fsdfs.py", line ... | Like @jodag has said. you probably have saved a state_dict instead of a model, which is recommended by the community as well.
This link explains the difference between two. To keep my answer self contained, I copy the snippet from the documentation. Here is the recommended way:
Save:
torch.save(model.state_dict(), PATH... | https://stackoverflow.com/questions/71534943/ |
For pytorch RNN model, can we inference the input by its output results? | all,
I wonder, torch.nn.rnn(~). If I know the final output, does it possible, I could inference its input value? For example:
myrnn = nn.RNN(4, 2, 1, batch_first=True)
expected_out, hidden = myrnn(input)
expected_out: tensor([[[-0.7773, -0.2031]],
[[-0.4129, -0.1802]],
[[ 0.0599, -0.0151]],
[[-0.9273, ... | What you are asking is theoretically impossible
Neural networks in general represent functions that are impossible to inverse as they are not guaranteed to be byjective regardless of the underlying architecture.
This means that neither rnn nor any other neural network are invertible.
| https://stackoverflow.com/questions/71538973/ |
Temporal Fusion Transformer (Pytorch Forecasting): `hidden_size` parameter | The Temporal-Fusion-Transformer (TFT) model in the PytorchForecasting package has several parameters (see: https://pytorch-forecasting.readthedocs.io/en/latest/_modules/pytorch_forecasting/models/temporal_fusion_transformer.html#TemporalFusionTransformer).
What does the hidden_size parameter exactly refer to? My best g... | After a bit of research on the source code provided in the link, I was able to figure out how hidden_size is the main hyperparameter of the model. Here it is:
hidden_size describes indeed the number of neurons of each Dense layer of the GRN. You can check out the structure of the GRN at https://arxiv.org/pdf/1912.09363... | https://stackoverflow.com/questions/71555080/ |
How to correctly combine LSTM with Linear layer | I got and LSTM that gives me output (4,32,32) i pass it to the Linear Layer(hidden size of LSTM, num_classes=1) and it gives me an output shape (4,32,1). I am trying to solve a wake word model for my AI assistant.
I have 2 classes i want to predict from. 0 is not wake up and 1 is the wake up AI.
My batch size is 32. Bu... | Not quite. You need to reshape your data to (32, 1) or (1, 32) in order for your linear layer to work. You can achieve this by adding a dimension with torch.unsqueeze() or even directly with torch.view(). If you use the unsqueeze function, the new shape should be (32, 1). If you use the view function, the new shape sho... | https://stackoverflow.com/questions/71566905/ |
Pytorch dist.all_gather_object hangs | I'm using dist.all_gather_object (PyTorch version 1.8) to collect sample ids from all GPUs:
for batch in dataloader:
video_sns = batch["video_ids"]
logits = model(batch)
group_gather_vdnames = [None for _ in range(envs['nGPU'])]
group_gather_logits = [torch.zeros_like(logits) for _ in range(en... | Turns out we need to set the device id manually as mentioned in the docstring of dist.all_gather_object() API.
Adding
torch.cuda.set_device(envs['LRANK']) # my local gpu_id
and the codes work.
I always thought the GPU ID is set automatically by PyTorch dist, turns out it's not.
| https://stackoverflow.com/questions/71568524/ |
Inspect signature of a python function without the __code__ attribute (e.g. PyTorch) | I am trying to determine the signature of a PyTorch function at runtime (e.g. torch.empty or torch.zeros). But something like inspect.signature(torch.empty) doesn't work here:
>>> import inspect
>>> import torch
>>> def add(a,b):
... return a+b
...
>>> inspect.signature(add)
<... | May be not best option, but workaround, - parse torch.empty.__doc__
print(torch.empty.__doc__)
empty(*size, *, out=None, dtype=None, layout=torch.strided, device=None, requires_grad=False, pin_memory=False, memory_format=torch.contiguous_format) -> Tensor
Returns a tensor filled with uninitialized data. The s... | https://stackoverflow.com/questions/71572847/ |
Pytorch AttributeError: can't set attribute | I'm using pytorch lightining and I have this error but I'm non really understanding what is the problem. I create a Deep Learning pipeline to run with hyperparameters searching and I think that the problem is in.
I omitted some part of the code because I think they are irrelevant for this issue (due to stackoverflow re... | pip install pytorch-lightning==1.2.10
| https://stackoverflow.com/questions/71584409/ |
Find index where a sub-tensor does not equal to a given tensor in Pytorch | I have a tensor, for example,
a = [[15,30,0,2], [-1,-1,-1,-1], [10, 20, 40, 60], [-1,-1,-1,-1]]
which has the shape (4,4).
How can I find the index where a specific sub-tensor
[-1,-1,-1,-1]
that doesn't appear using PyTorch. The expected output I want to get is
[0,2]
| You can compare the elements for each row of the tensor using torch.any(), and then use .nonzero() and .flatten() to generate the indices:
torch.any(a != torch.Tensor([-1, -1, -1, -1]), axis=1).nonzero().flatten()
For example,
import torch
a = torch.Tensor([[15,30,0,2], [-1,-1,-1,-1], [10, 20, 40, 60], [-1,-1,-1,-1]... | https://stackoverflow.com/questions/71595684/ |
Reproducibility issue with PyTorch | I'm running a script with the same seed and I see results are reproduced on consecutive runs but somehow running the same script with the same seed changes the output after a few days. I'm only getting a short-term reproducibility which is weird. For reproducibility my script includes the following statements already:
... | PyTorch is actually not fully deterministic. Meaning that with a set seed, some PyTorch operations will simply behave differently and diverge from previous runs, given enough time. This is due to algorithm, CUDA, and backprop optimizations.
This is a good read: https://pytorch.org/docs/stable/notes/randomness.html
The ... | https://stackoverflow.com/questions/71600683/ |
ValueError: num_samples should be a positive integer value, but got num_samples=0 | I have data organized as follows: /dataset/train_or_validation/neg_or_pos_class/images.png
So, inside train or validation I have 2 folders, 1 for negative and 1 for positive.
I have the error of the title ValueError: num_samples should be a positive integer value, but got num_samples=0 because basically I am inside /da... | The problem is that the dataset is empty. The datapath may be wrong or preprocessing might be causing problems ending up with no object in Dataset object.
| https://stackoverflow.com/questions/71615089/ |
PytorchStreamReader failed reading zip archive: failed finding central directory | I am trying to learn pytorch from a book, but it seems not a straight line for me.
I coped the code below and pasted in my jupyter notebook for running but it gave me an error I am not able to interpret at my level!
from torchvision import models
model = models.alexnet(pretrained=True)
# set the device
device = 'cuda'... | I think this issue happens when the file is not downloaded completely.
| https://stackoverflow.com/questions/71617570/ |
Monai : RuntimeError: Sizes of tensors must match except in dimension 1. Expected size 7 but got size 8 for tensor number 1 in the list | I am using Monai for the 3D Multilabel segmentation task. My input image size is 512x496x49 and my label size is 512x496x49. An Image can have 3 labels in one image. With transform, I have converted the image in size 1x512x512x49 and Label in 3x512x512x49
My Transform
# Setting tranform for train and test data
a_min=67... | Your images have a depth of 49, but due to the 4 downsampling steps, each with stride 2, your images need to be divisible by a factor of 2**4=16. Adding in DivisiblePadd(["image", "label"], 16) should solve it.
| https://stackoverflow.com/questions/71618942/ |
Deep Smote error : RuntimeError: mat1 and mat2 shapes cannot be multiplied (51200x1 and 512x300) | I am trying to run deep Smote on cifar10 and Dont have much experience with pytorch as I code in tensorflow. It works fine when I run it on MNIST and FMNIST keeping channles = 1 there
However, the moment i try it on cifar10, i dosent behave well.
The code given in the paper says that it works for Cifar10 too,
All the h... | I have the same issue on pytorch, can you try to uncomment the following line below inside nn.sequential() of decoder.
#3d and 32 by 32.
nn.Conv2d(self.dim_h * 4, self.dim_h * 8, 4, 1, 0, bias=False)
| https://stackoverflow.com/questions/71626362/ |
Convert list of PNGImageFile to array of array | I have a dataset organized in this way: /dataset/train/class/images.png (the same for test) (and I have 2 classes, positive and negative).
I want to obtain x_train, y_train, x_test and y_test, so I am using this python script:
x_train = []
y_train = []
x_test = []
y_test = []
base_dir_train = 'Montgomery_real_splitted/... | Before appending imt to x_train, do this:
imt = np.array(imt)
The following also can help:
from torchvision import transforms
imt = transforms.ToTensor()(imt)
| https://stackoverflow.com/questions/71626985/ |
ResNet doesn't train because of differences in images' sizes | So ho I have 30 folders with images inside them, and I wanted to train ResNet50 on them. I created a CustomDataset, and inside I put a Resize(224, 224) so that every image had the same size.
Here's what I did:
class CustomImageDataset(Dataset):
def __init__(self, annotations_file, img_dir, transform=None, target_tr... | As noted in the comments, the error suggests that your dataset contains both gray scale and RGB (color) images. Although all images have indeed been resized to 224 pixels, color images have 3 channels, whereas gray scale images only have a single channel, so a batch cannot be created.
If you insist on training a networ... | https://stackoverflow.com/questions/71628697/ |
How to simplify function for standardising images? | I have a function to calculate the mean and standard deviation of my dataset.
Is there a simpler way to do this? As it takes a while to compute.
def get_mean_std(loader):
sum = 0
sum_sq_err = 0
for data, _ in loader:
sum += torch.mean(data, dim=[0,2,3])
sum_sq_err += torch.mean(data**2, dim=[0,2,3])
me... | Note that this approach is not even correct in general, as the mean of a set is not the mean of the means of some subsets in general (it is when all the subsets have the same length, but that may or may not be the case here).
Provided that every batch is of the same size, what I would do is to call torch.sum in the loo... | https://stackoverflow.com/questions/71631292/ |
how to package my python pytorch program for android? | my codes is python pytorch.
I build it to .exe, it can work at windows.
How to package the codes for android.
I hope it can work at android.
Thank you.
| Sorry, I don't know how to call an exe program in android, but I can give you some other advice. According to your needs, maybe you can learn about Chaquopy.
Chaquopy provides everything you need to include Python components in an Android app, including:
(1)Full integration with Android Studio’s standard Gradle build s... | https://stackoverflow.com/questions/71634616/ |
Sagemaker inference : how to load model | I have trained a BERT model on sagemaker and now I want to get it ready for making predictions, i.e, inference.
I have used pytorch to train the model and model is saved to s3 bucket after training.
Here is structure inside model.tar.gz file which is present in s3 bucket.
Now, I do not understand how can I make predic... | Here's detailed documentation on deploying PyTorch models - https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#deploy-pytorch-models
If you're using the default model_fn provided by the estimator, you'll need to have the model as model.pt.
To write your own inference script and deploy the ... | https://stackoverflow.com/questions/71637112/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.