instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
How to shrink a 2D tensor to another 2D tensor using boolean mask? | Say I have a 2D pytorch tensor and a 2D numpy boolean as follows,
a = torch.tensor([[ 0., 1., 2.],
[ 3., 4., 5.],
[ 6., 7., 8.],
[ 9., 10., 11.],
[12., 13., 14.]])
m = numpy.array([[ False, True, False],
[ True, False, Tr... | In my benchmarks a jitted numba solution is the fastest, I could find
My benchmarks for a, m with shape (10000,200)(equal result tensors)
1
@numba.jit
13.2 ms (3.46x)
2
list comprehension
31.3 ms (1.46x)
3
baseline
45.7 ms (1.00x)
Generation of sufficiently large sample data for benchmarking
import t... | https://stackoverflow.com/questions/71641977/ |
How to resolve the error: RuntimeError: received 0 items of ancdata | I have a torch.utils.data.DataLoader. I have created them with the following code.
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
trainset... | I was facing a similar issue with my code and based on some discussions (check #1, #2, #3). I used ulimit -n 2048 to increase the maximum number of file descriptors a process can have. You can read more about ulimit here.
About the issue - The discussions suggest that it has to do something with pytorch’s forked multip... | https://stackoverflow.com/questions/71642653/ |
PyTorch: How to calculate output size of the CNN? | I went through this PyTorch CNN implementation available here: https://machinelearningknowledge.ai/pytorch-conv2d-explained-with-examples/
I am unable to understand how they replace the '?' with some value. What is the formula for calculating the CNN layer output?
This is essential to be calculated in PyTorch; not so i... | I assume you calculation is wrong because:
Pytorch support images in format C * H * W (e.g. 3x32x32 not 32x32x3)
First dimension always batch dimension and must be omitted in calculation because, all nn.Modules handle it by default
So if you want calculate input size for first Linear layer, you can use this trick:
c... | https://stackoverflow.com/questions/71647309/ |
Difference in the order of applying linear decoder and average pooling for sequence models | I am working with sequence modelling in pytorch and trying to determine if the order of the pooling and linear decoding layer matters. Given that I have a sequence with the shape (Batch, Seqlen, dim_model) and I want to transform it into (Batch, dim_output) I will need a pooling layer for reducing the second dimension ... | A linear layer does x -> Ax+b for some matrix A and vector b.
If you have a bunch of x (x1, x2, x3, ..., xn) then A[(x1+...+xn)/n] = (Ax1 +... +Axn)/n, so for mean pooling, applying pooling first and then doing the linear layer results (up to floating point errors) in the same value as applying the linear layer firs... | https://stackoverflow.com/questions/71650951/ |
How to insert a value in a fixed positon of pytorch | I have a PyTorch tensor
x = [[1,2,3,4,5]]
Now I want to add a value to a fixed position of the tensor x, for example, I want to add 11 in position 3 then the x will be
x= [[1,2,3,11,4,5]]
How can I perform this operation in Pytorch?
| Dynamically extending arrays to arbitrary sizes along the non-singleton dimensions, such as the ones you mentioned, are unsupported in PyTorch mainly because the memory is pre-allocated during tensor construction and set to fixed size depending on the data type. The only way to grow non-singleton dimension size is to c... | https://stackoverflow.com/questions/71669183/ |
RuntimeError: only batches of spatial targets supported (3D tensors) but got targets of dimension: 4 | I am having a hard time understanding image segmentation. I have implemented Unet model for image segmentation. I am using PASCAL VOC dataset and I am trying to train my model. However, I got stuck when calculating the loss. I am unsure of what should be the expected shapes of the output and target classes. Can someone... | For starters, your label and outputs have different dimension. (32 vs 3 channels). Cross Entropy Loss expects them to either have the same number of channels, or for the target to have only one channel with integer values indicating the relevant class.
Let's work with the latter case. In this case, we need to reduce th... | https://stackoverflow.com/questions/71674595/ |
Stable Baselines3 - Setting "manually" the q_values | What I have done
I'm using the DQN Algorithm in Stable Baselines 3 for a two players board type game. In this game, 40 moves are available, but once one is made, it can't be done again.
I trained my first model with an opponent which would choose randomly its move. If an invalid move is made by the model, I give a nega... | I recently had a similar problem in which I needed to directly alter the q-values produced by the RL model during training in order to influence its actions.
To do this I overwritten some methods of the library:
# Imports
from stable_baselines3.dqn.policies import QNetwork, DQNPolicy
# Override some methods of the cla... | https://stackoverflow.com/questions/71678249/ |
My model memory size keeps decreasing and isn't clearing. And as a result, I get a CUDA memory issue | I'm trying to run a deep network in CUDA/Pytorch. But I keep getting a GPU issue that tells me I'm out of memory in in my GPU as follows:
CUDA out of memory. Tried to allocate 16.00 MiB (GPU 0; 11.17 GiB total capacity; 10.62 GiB already allocated; 14.81 MiB free; 10.63 GiB reserved in total by PyTorch) If reserved me... | Maybe typo, but there should be loss.backward() like method calling and loss.backward by itself makes nothing. Also when computing running_loss call .item() method on loss, so full line looks like this running_loss += loss.item(). In discussion there is an answer on why it should reduce memory usage (...cumulative loss... | https://stackoverflow.com/questions/71683934/ |
Cuda:0 device type tensor to numpy problem for plotting graph | as mentioned in the title, I am facing the problem of
TypeError: can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
I found out that that need to be a .cpu() method to overcome the problem, but tried various ways and still unable to solve the problem
def plot(val... | I guess during loss calculation, when you try to save the loss, instead of
train_loss.append(loss)
it should be
train_loss.append(loss.item())
item() returns the value of the tensor as a standard Python number, therefore, train_loss will be a list of numbers and you will be able to plot it.
You can read more about it... | https://stackoverflow.com/questions/71686820/ |
Django web Deployment Failed on azure | 10:47:19 AM django-face-restore: ERROR: Could not find a version that satisfies the requirement torch==TORCH_VERSION+cpu (from versions: 1.4.0, 1.5.0, 1.5.1, 1.6.0, 1.7.0, 1.7.1, 1.8.0, 1.8.1, 1.9.0, 1.9.1, 1.10.0, 1.10.1, 1.10.2, 1.11.0)
10:47:19 AM django-face-restore: ERROR: No matching distribution found for torch=... | To resolve this ERROR: No matching distribution found for torch==TORCH_VERSION+cpu error:
You need to install the specific version of torch, try either of the following ways:
Add the following to your requirements.txt file:
--find-links https://download.pytorch.org/whl/torch_stable.html
torch==1.7.0+cpu
OR
python -m ... | https://stackoverflow.com/questions/71687284/ |
How can I implement a simple dot counting problem using a regression instead of a classification approach in Pytorch? | I'm trying to figure out how to solve the really simple problem of counting how many pixels in an image are white.
I have 20x20 pixel images (zeros matrix) with 1 to 20 pixels randomly set to 1.
Checking some tutorials Im able to solve this problem via a classification approach with the model using CrossEntropyLoss() a... | Keep in mind that you probably have to normalize the outputs. So your model should still output something between 0 and 1 where 0 means 0 white pixels, 1 means 20 white pixels and 0.5 means 10 and so on. Therefore use sigmoid on the output neuron and mulltiply it by 20 to get the estimated amount of white pixels.
| https://stackoverflow.com/questions/71694867/ |
PyTorch adapt binary classification model to output probabilities of both classes | My dataset has 14 features and a target containing {0,1}.
I have trained this binary classifier:
class SimpleBinaryClassifier(nn.Module):
def __init__(self,input_shape):
super().__init__()
self.fc1 = nn.Linear(input_shape,64)
self.fc2 = nn.Linear(64,32)
self.dropout = nn.Dropout(p=0.... | According to nn.CrossEntropyLoss description it expects target as long and not float, while in your train_dataset you clearly convert it to float
| https://stackoverflow.com/questions/71696991/ |
What is the significance of 1.000000015047466e+30? | I was attempting to do JIT compilation on a pytorch-based module from an NLP library and I saw that one of the generated fused CUDA kernel code implementations mentions the number 1.000000015047466e+30:
#define NAN __int_as_float(0x7fffffff)
#define POS_INFINITY __int_as_float(0x7f800000)
#define NEG_INFINITY __int_as_... | 1.000000015047466e+30f is 1030 rounded to the nearest value representable in float (IEEE-754 binary32, also called “single precision”), then rounded to 16 decimal digits, then formatted as a float literal.
Thus, it likely originated as 1e30 or another representation of 1030 that was subsequently converted to float and ... | https://stackoverflow.com/questions/71699232/ |
Object detection from synthetic to real life data with Yolov5 | Currently trying yolov5 with custom synthetic data. The dataset we've created consists of 8 different objects. Each object has a minimum of 1500 pictures/labels, where the pictures are split 500/500/500 of normal/fog/distractors around object. Sample images from the dataset is in the first imgur link. The model is not ... | There are couple of things to improve results.
After training your model with synthetic data, fine tune your model with real training data, with a smaller learning rate (1/10th maybe). This will reduce the gap between synthetic and real life images. In some cases rather than fine tuning, training the model with mixed ... | https://stackoverflow.com/questions/71711521/ |
Input and Output to the lstms in pytorch | I want to implement lstms with CNN in pytorch as my data is a time series data i.e. frames of video for heart rate detection, I am struggling with the input and output dimensions for lstms what and how i should properly configure the dimensions/parameters/arguments at input of lstms in pytorch as its quite confusing wh... | Generally, the input shape of sequential data takes the form (batch_size, seq_len, num_features). Based on your explanation, I assume your input is of the form (2, 256), where 2 is the batch size and 256 is the sequence length of scalars (1-dimensional tensor). Therefore, you should reshape your input to be (2, 256, 1)... | https://stackoverflow.com/questions/71714857/ |
TypeError: forward() missing 1 required positional argument in a method | I use the following model:
model = DeepGraphInfomax(128, pos_summary_t).to(device)
which looks like:
class DeepGraphInfomax(torch.nn.Module):
def __init__(self, hidden_channels, pos_summary):#, encoder):#, summary, corruption):
super().__init__()
self.hidden_channels = hidden_channels
#self.encoder = GC... | model is an object since you instantiated DeepGraphInfomax.
model() calls the .__call__ function.
forward is called in the .__call__ function i.e. model().
Have a look at here.
The TypeError means that you should write input in forward function i.e. model(data).
Here is an exmaple:
import torch
import torch.nn as nn
... | https://stackoverflow.com/questions/71717638/ |
How to Reverse Order of Rows in a Tensor | I'm trying to reverse the order of the rows in a tensor that I create. I have tried with tensorflow and pytorch. Only thing I have found is the torch.flip() method. This does not work as it reverses not only the order of the rows, but also all of the elements in each row. I want the elements to remain the same. Is ther... | According to documentation torch.flip has argument dims, which control what axis to be flipped. In this case torch.flip(tensor_a, dims=(0,)) will return expected result. Also torch.flip(tensor_a) will reverse all tensor, and torch.flip(tensor_a, dims=(1,)) will reverse every row, like [1, 2, 3] --> [3, 2, 1].
| https://stackoverflow.com/questions/71723788/ |
ConvNeXt torchvision - specify input channels | How do I change the number of input channels in the torchvision ConvNeXt model? I am working with grayscale images and want 1 input channel instead of 3.
import torch
from torchvision.models.convnext import ConvNeXt, CNBlockConfig
# this is the given configuration for the 'tiny' model
block_setting = [
CNBlockConf... | You can rewrite the whole input layer, model._modules["features"][0][0] is
nn.Conv2d(3, 96, kernel_size=(4, 4), stride=(4, 4))
Then, you only need to change the in_channels
>>> model._modules["features"][0][0] = nn.Conv2d(1, 96, kernel_size=(4, 4), stride=(4, 4))
>>> model(im)
ten... | https://stackoverflow.com/questions/71728710/ |
Float64 Normalisation in pytorch | So when I want to do normalization to float64 in deep learning, I need to make float64_max to be 1 or just every image’s max value as 1?
I read a .nii file to get a 3D array with type float64 and its value is very big. I need to normalize it into 0-1 and float32 type to input my deep learning model. So I was wondering ... | No, you should normalize the max possible value of all images to 1 not the maximum value of each image separately.
For a general image RGB 8-bit image, the maximum value for a pixel channel is 255, so you could divide the entire image's channel value by 255.
In this way, you will obtain a new image of type float32 (or ... | https://stackoverflow.com/questions/71747126/ |
CUDA 11.3 not being detected by PyTorch [Anaconda] | I am running Ubuntu 20.04 on GTX 1050TI. I have installed CUDA 11.3.
nvidia-smi output:
Wed Apr 6 18:27:23 2022
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 465.19.01 Driver Version: 465.19.01 CUDA Version: 11.3 |
|-------------------------------+-------... | The solution:
Conda in my case installed cpu build. You can easily identify your build type by running torch.version.cuda which should return a string in case you have the CUDA build. if you get None then you are running the cpu build and it will not detect CUDA
To fix that I installed torch using pip instead :
pip3 in... | https://stackoverflow.com/questions/71770438/ |
why does pytorch's utils.save_image() change the color of my image | I am saving two images with pytorch's utils.save_image() function here. one is the real image and the other, the perturbed image (just a patch). However, the latter image lost its real appearance when saved with save_image().
# save source image
utils.save_image(data.data, "./%s/%d_%d_org.png" % ("log&qu... | So, I managed to solve this by adding make_grid() to the save method and clipping the image to [0,1] without normalizing.
utils.save_image(utils.make_grid(torch.clip(noised_data.data, 0, 1)), "./%s/%d_%d_adv.png" % ("log", batch_idx, target_class))
| https://stackoverflow.com/questions/71770745/ |
Combine multiple DataLoaders sequentially | I'm interested in how I'd go about combining multiple DataLoaders sequentially for training. I understand I can use ConcatDataset to combine datasets first, but this does not work for my use case. I have a custom collate_fn that is passed to each dataloader, and this function depends on an attribute of the underlying D... | I ran into the same problem and found a workaround. I overrided the epoch training loop using the Loops API from PytorchLightning, defining a class CustomLoop which inherits from pytorch_lightning.loops.TrainingEpochLoop, and overrided the advance() method. I copy pasted the source code from pytorch_lightning and repla... | https://stackoverflow.com/questions/71774659/ |
pytorch Error: module 'torch.nn' has no attribute 'ReLu' | i am working in google colab, so i assume its the current version of pytorch.
I tried this:
class Fc(nn.Module):
def __init__(self):
super(Fc, self).__init__()
self.flatt = nn.Flatten()
self.seq = nn.Sequential(nn.Linear(28*28, 512),
nn.ReLU(),
... | You got a typo regarding casing. It's called ReLU not ReLu.
import torch.nn as nn
class Fc(nn.Module):
def __init__(self):
super(Fc, self).__init__()
self.flatt = nn.Flatten()
self.seq = nn.Sequential(nn.Linear(28*28, 512),
# TODO: Adjust here
... | https://stackoverflow.com/questions/71796137/ |
Inputing a torch 3d tensor into a keras.Sequential model | Here I have a pytorch tensor object which I need to use for training a neural network. Can pytorch tensors be used for training a keras neural network and if so, what will be the value of the input_shape parameter when the training data has 3 dimensions?
Here's the code:
image, label = val_dset.__getitem__(20)
print(im... | You can get .numpy() then convert to tensor like below:
>>> torch_image = torch.rand(3, 224, 224)
>>> torch_image.shape
torch.Size([3, 224, 224])
>>> tf_image = tf.convert_to_tensor(torch_image.numpy())
>>> tf_image
<tf.Tensor: shape=(3, 224, 224), dtype=float32, numpy=
array([[[... | https://stackoverflow.com/questions/71797688/ |
How can I sum parts of pytorch tensor of variable sizes? | Let's consider example.
I have a tensor of size (10, 3).
I want to sum first 3 rows, next 2 rows and 5 next rows by 0 axis.
For example from:
t = torch.ones([10, 3])
I want to get:
[
[3.0, 3.0, 3.0],
[2.0, 2.0, 2.0],
[5.0, 5.0, 5.0],
]
I want to specify a tensor with values and a tensor with part sizes an... | Following the great idea of @ben-grossmann I modified it a little to use sparse tensor and make it more efficient. And implemented it as a function:
def sum_var_parts(t, lens):
t_size_0 = t.size(0)
ind_x = torch.repeat_interleave(torch.arange(lens.size(0)), lens)
indices = torch.cat(
[
t... | https://stackoverflow.com/questions/71800953/ |
How To Return Incorrectly Predicted Images | I am having trouble figuring out how to create a list containing the first 10 image IDs that were incorrectly predicted.
import os
import torch
import torchvision
from torch.utils.data import random_split
from torchvision.datasets import ImageFolder
from torchvision.transforms import ToTensor
from torch.utils.data.data... | def invalid_predictions(n=10, images, labels):
invalid_ids = []
image_count = 0
invalid_count = 0
while invalid_count < n:
prediction = predict_image(images[image_count], model)
if prediction != labels[image_count ]:
invalid_ids.append(image_count )
invalid_cou... | https://stackoverflow.com/questions/71813347/ |
how to overfit a model on a single batch in keras? | I am trying to overfit my model on a single batch to check model integrity. I am using Keras and TensorFlow for the implementation of my model and coding style for this project.
I know how to get the single batch and overfit the model in PyTorch but don't have an idea in Keras.
to get a single batch in PyTorch I used:
... | Thank you everyone for coming here. I found a solution and here it is:
datagen = ImageDataGenerator(rescale=1 / 255.0,
rotation_range=20,
zoom_range=0.2,
width_shift_range=0.05,
height_shift_range=0.05,
... | https://stackoverflow.com/questions/71823551/ |
How can I use 2 images as a training sample in PyTorch? | I just begin learning deep learning and my first homework is to finish an leaves-classification system based on convolutional neural networks.I built a resnet-34 model with the code on github to do it.However,my teacher told me that the basic training unit in his dataset is an image pair.I should use 2 images(photos of... | You have several issues to tackle:
You need a Dataset with a __getitem__ method that returns 2 images (and a label) instead of the basic ones that returns a single image and a label. You'll probably need to customize your own dataset.
Make sure the augmentations you apply to your images are applied in the same manner ... | https://stackoverflow.com/questions/71852199/ |
Combination of features of convolutional layers channel-by-channel in a multi-branch model | The convolutional model presented below, has two branches and each branch (for example) has two stages (convolutional layers).
My aim is to combine the weighted feature maps (channels) of the first convolutional layer from the second branch with the channels of the first convolutional layer from the first branch.
I wa... | In your main_class the second branch is not receiving additional arguments, it's only the first one that needs to be executed as second (in order). You could just add a parameter to the forward method of that branch like so:
class first_branch(nn.Module):
...
def forward(self, x, weighted_x: list = []):
... | https://stackoverflow.com/questions/71872584/ |
Reduce multiclass image classification to binary classification in Pytorch | I am working on an stl-10 image dataset that consists of 10 different classes. I want to reduce this multiclass image classification problem to the binary class image classification such as class 1 Vs rest. I am using PyTorch torchvision to download and use the stl data but I am unable to do it as one Vs the rest.
trai... | For torchvision datasets, there is an inbuilt way to do this. You need to define a transformation function or class and add that into the target_transform while creating the dataset.
torchvision.datasets.STL10(root: str, split: str = 'train', folds: Union[int, NoneType] = None, transform: Union[Callable, NoneType] = No... | https://stackoverflow.com/questions/71889622/ |
Training a u-net for multi-landmark heatmap regression producing the same heatmap for each channel | I’m training a U-Net (model below) to predict 4 heatmaps (gaussian centered around a keypoint, one in each channel). Each channel is for some reason outputting the same result, an example is given of a test image where the blue is ground truth for that channel and red is the output of the u-net. I have tried using L1, ... | Hard to see how this is a UNet. The only components that will modify the spatial shape of your input is your MaxPool2d's. You have two of these, so for a given input with size [B, 1, H, W], your output will have the shape [B, 256, H/4, W/4].
I think you need to give a more complete code snippet (don't have enough rep t... | https://stackoverflow.com/questions/71910583/ |
attempting to manually download MNIST pytorch dataset in databricks | I've attempted a couple different iterations now to get the dataset manually loaded into databricks's DBFS.. so that PyTorch can load it.. however the MNIST dataset seems to just be some binary file.. is it expected I unzip it first or just.. point to the GZipped tarball? So far all my trials have gotten this error
t... | My code and dir:
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../colabx/data', train=True, download=False,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
....\colabx\data\MNIST\raw>l... | https://stackoverflow.com/questions/71923061/ |
Assigning weights to the feature maps of a convolutional layer | I'm using a class SE_Block (squeeze and excitation block) and give N feature maps (channels) of a convolutional layer as the input to this SE_Block. My goal is that after using the SE_Block, each of its input feature maps obtain their own weight. In other words, the SE_Block aims to assign a weight for each of the feat... | When you're creating the SE_block you're not passing the c (channel) argument.
You need to add:
class myclass(nn.Module):
def __init__(self, in_channel=1024, out_channel=512, out_sigmoid=False):
...
self.SEBlock = SE_Block(out_channel) # Adding argument here
...
You also have some erro... | https://stackoverflow.com/questions/71935848/ |
How define the number of class in Detectron2 bounding box predict Pytorch? | Where should i define the number os classes ?
ROI HEAD or RETINANET ?
Or both should have the same value ?
cfg.MODEL.RETINANET.NUM_CLASSES =int( len(Classe_list)-1)
cfg.MODEL.ROI_HEADS.NUM_CLASSES=int( len(Classe_list)-1)
| It depends on the network architecture you choose to use. If you use the "MaskRCNN", then you should set the cfg.MDOEL.ROI_HEADS.NUM_CLASSES.
The deep reason is that ROI_HEAD is the component used by MaskRCNN. If you use different network, you may need to change different things dependent on their implementat... | https://stackoverflow.com/questions/71940944/ |
Automatically check available GPU on Google Colab | Is there an automatic way to check which GPU is currently available on Google Colab (Pro).
Say I would like to use a Tesla P100 instead of the Tesla T4 to train my model, is there a way to periodically check with a python script in Colab whether the P100 is available?
I have tried eliminate the kernel periodically but ... | There is no way to check what GPU is available. Add the line:
!nvidia-smi
to the beginning of your code and then keep on disconnecting and reconnecting the runtime until you get the GPU that you want.
| https://stackoverflow.com/questions/71952532/ |
Curious loss in a CNN | in my CNN for image classification, I get a curious loss and I don't know what's wrong. I'm lucky, if you help me to find the failure.
Here is a cutout of my print output and at the end there is my code:
Train Epoch: 1 [0/2048 (0%)] Loss: 0.654869
Train Epoch: 1 [64/2048 (3%)] Loss: 0.271722
Train Epoch: 1 [128/20... | I might also suggest that the network needs to be initialized with random parameters for the convolutional layer weights. By default these weights are 0, which probably means that you end up predicting all one class. This might explain the very low (0) or very high losses (based on the makeup of the particular batch).
| https://stackoverflow.com/questions/71955542/ |
Fine tune/train a pre-trained BERT on data with no sentences but only words (bank transactions) | I have a lot of bank-transactions which I want to classify into different categories. The issue is that the text is not a sentence as such but consists only of words e.g "private withdrawal", "payment invoice 19234", "taxes" etc.
Since the domain is so specific, I think we might get a bett... | Your problem is a sequence classification problem. If you want to use a pre-trained model, you want to do transfer learning. Basically you want to use the Bert base model and add a layer of classification.
You can check huggingface for that https://huggingface.co/docs/transformers/model_doc/bert#transformers.BertForSeq... | https://stackoverflow.com/questions/71967595/ |
Training multiple pytorch models on GPUs | I'm trying to implement something with pytorch.
I have 2 GPUs and I want to train 2 models as below:
model0 = Mymodel().to('cuda:0')
model1 = Mymodel().to('cuda:1')
opt0 = torch.optim.Adam(model0.parameters(), lr=0.01)
opt1 = torch.optim.Adam(model0.parameters(), lr=0.01)
# 1.Forward data into model0 on GPU0
out = mod... | You have a strong dependency between the 2 models, the 2nd one always needs the output from the previous one, so that part of the code will always be sequential.
I think you might need some sort of multiprocessing (take a look at torch.multiprocessing) or some kind of queue, where you can store the output from the firs... | https://stackoverflow.com/questions/71970110/ |
While training BERT variant, getting IndexError: index out of range in self | While training XLMRobertaForSequenceClassification:
xlm_r_model(input_ids = X_train_batch_input_ids
, attention_mask = X_train_batch_attention_mask
, return_dict = False
)
I faced following error:
Traceback (most recent call last):
File "<string>", line 3, in <mo... | As per this post on github, there can be possibly many reasons for this. Below is the list of reasons summmarised from that post (as of April 24, 2022, note that 2nd and 3rd reasons are not tested):
Mismatching vocabulary size of tokenizer and bert model. This will cause the tokenizer to generate IDs that the model ca... | https://stackoverflow.com/questions/71984994/ |
Resize to 224×224 directly or resize to 256 ×256 then crop 224×224? | My images in training set are leaves like this.
enter image description here
Its size is 572*108 and my resnet network need 224×224 images as input.
I found most of the codes process the images with the second way(resize to 256 ×256 then crop 224×224) so I did that.
As a result,parts of my leaves were cut which may inf... | Running two experiments and compare their evalution results is the simplest solution.
A complete view is not neccessary for model to classify images, so as it to human. On the contrary, learning from cropped image normally can improve the generalization capacity of a model.
| https://stackoverflow.com/questions/71989157/ |
Is there a multi images to 1 image deep learning method? (pix2pix?) | I'm trying to build a video stabilization deep learning model.
I want to make the model predict how the frame should be stabilized depending on the last 10 frames
I have tried pix2pix, which is image to image, but I didn't get a good result
so, I want the same as pix2pix but multi images to 1 image
is there a method or... | So, I do not know if you actually need to build this video stabilization using deep learning or if you just want on off-the-shelves solution.
For the on-the-shelves solution, you can look into vidgear that has an awesome stabilisation system built-in: https://abhitronix.github.io/vidgear/latest/gears/stabilizer/overvie... | https://stackoverflow.com/questions/71995440/ |
Splitting a Tensor channelwise | I am dumping a tensor of size [1,3,224,224] to a file and would like to split into 3 tensors of size [1,1,224,224], one for each RGB channel and dump them into 3 separate files. How do I implement this?
| I think the simplest way is by a loop:
for c in range(x.shape[1]):
torch.save(x[:, c:c+1, ...], f'channel{c}.pth')
Note the indexing of the second (channel) dimension: you want the saved tensor to have a singleton channel dimension. If you were to index it using x[:, c, ...] you will get a tensor of shape [1, 224, 2... | https://stackoverflow.com/questions/71997364/ |
Unable to convert the pytorch model to the TorchScript format | Loaded the pretrained PyTorch model file, and when I try to run it with torch.jit.script I get the below error, When I try to run the inbuilt pretrained model from pytorch.org it works perfectly fine. (Ex. Link to example code) but throws error for custom built pretrained model (Git repo containing the pretrained model... | torch.jit.script create a ScriptFunction(a Function with Graph) by parsing the python source code from module.forward().
If your module contains some grammar cannot support by the python parser, it will failed. Especially for the object not contains a static type.
Using torch.jit.trace is able to avoid such problems. I... | https://stackoverflow.com/questions/72003175/ |
Cannot import name 'functional_datapipe' from 'torch.utils.data' | When I am running datasets_utils.py from '/usr/local/lib/python3.7/dist-packages/torchtext/data/datasets_utils.py' in Google Colab, the following error occurs even with the most updated versions of Python packages:
ImportError: cannot import name 'functional_datapipe' from 'torch.utils.data' (/usr/local/lib/python3.7/d... | It might be available only on torchdata.datapipes
| https://stackoverflow.com/questions/72009516/ |
What does Union from typing module in Python do? | I was looking the implementation of ResNet deep learning architecture in PyTorch from git-hub.
At line 167, inside the initializer of another class definition which defines ResNet and is also named ResNet, I saw the code below:
block: Type[Union[BasicBlock, Bottleneck]],
BasicBlock and Bottleneck are two classes defin... | To reinforce the previous answer. Python couldn't care less about types. They are ignored completely. Their sole purpose is for linters.
IDE's like PyCharm also have linters built into them. PyCharm has caught numerous bugs for me: "you said that function was supposed to take a two strings, but you're passing... | https://stackoverflow.com/questions/72017661/ |
Troubles while compiling C++ program with PyTorch, HElib and OpenCV | I'm trying to compile my C++ program that uses the libraries HElib, OpenCV and PyTorch. I'm on Ubuntu 20.04. The entire code is:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdint>
#include <memory>
#include <stdio.h>
#include <open... | I found the answer, but I can't really explain with my little experience what I've done, I'll just illustrate the passages.
I've re-downloaded PyTorch from its website, selecting the libtorch-cxx11-abi-shared-with-deps version (the one compiled with -D_GLIBCXX_USE_CXX11_ABI=1).
Then I had to add to the compilation comm... | https://stackoverflow.com/questions/72030738/ |
Pytorch: Having trouble understanding the inline replacement happening | This seems to be a common error people get, but i can't really understand the real cause.
I am having trouble figuring out where the inline replacement is happening.
My forward function:
def forward(self, input, hidden=None):
if hidden is None :
hidden = self.init_hidden(input.size(0))
out, hidden = sel... | Adding hidden = tuple([each.data for each in hidden]) after your optimizer.step() fix the error, but zeros the gradient on the hidden value. You can achieve the same effect with hidden = tuple([each.detach() for each in hidden])
| https://stackoverflow.com/questions/72038258/ |
Terminate called after throwing an instance of 'std::bad_alloc' from importing torch_geometric | I am writing in python and getting the error:
"terminate called after throwing an instance of 'std::bad_alloc'.
what(): std::bad_alloc.
Aborted (core dumped)"
After lots of debugging, I found out the source of the issue is:
import torch_geometric
I even created a file with just this line of code, and I stil... | This problem is because of mismatched versions of pytorch.
The current pytorch being used is 1.11.0, but when scatter and sparse were installed installed scatter and sparse, 1.10.1 were used:
pip install torch-scatter -f https://data.pyg.org/whl/torch-1.10.1+cu113.html.
pip install torch-sparse -f https://data.pyg.org... | https://stackoverflow.com/questions/72039582/ |
Pytorch Temporal Fusion Transformer - TimeSeriesDataSet TypeError: '<' not supported between instances of 'int' and 'str' | I'm following Temporal-Fusion-Transformer (TFT) tutorial in the PytorchForecasting (https://pytorch-forecasting.readthedocs.io/en/stable/tutorials/stallion.html#Demand-forecasting-with-the-Temporal-Fusion-Transformer) to train TFT model with custom dataset to predict "booking" value based on several static/ti... | You can check the values in the static_categoricals=["Region","Sub-Region","Sold TO Party Code","Customer Type","Customer Segment L1","Customer Segment L2"], maybe you are passing a value that have a str and this is trying to be compare with a int
| https://stackoverflow.com/questions/72041613/ |
Torchvision transforms.ToTensor show different range result. Dose not scale array to [0,1] as document says | I am converting the numpy array to tensor with the following code:
self.transform_1 = transforms.Compose([transforms.ToTensor()])
source_parsing_np = cv2.imread(source_parsing_path, cv2.IMREAD_GRAYSCALE) #The range is integer in the range [0,14]
source_parsing_tensor = self.transform_1(source_parsing_tensor)
As the do... | I found the reason: the conversion occurs only when the numpy.ndarray has dtype = np.uint8, but my dytpe is np.long, sorry for my carelessness.
| https://stackoverflow.com/questions/72041753/ |
Converting PyTorch Boolean target to regression target | Question
I have code that is based on Part 2, Chapter 11 of Deep Learning with PyTorch, by Luca Pietro Giovanni Antiga, Thomas Viehmann, and Eli Stevens. It's working just fine. It predicts the value of a Boolean variable. I want to convert this so that it predicts the value of a real number variable that happens to... | The example from the book is working but it has some redundant elements which confuse you.
Normally output size of 1 is enough for a binary classification problem. To bring it to 0 or 1, one may use sigmoid and then rounding, like in the example here: PyTorch Binary Classification - same network structure, 'simple... | https://stackoverflow.com/questions/72049566/ |
Which method should I use to sample from a normal distribution? | I'm trying to sample batch_size points from an N-dim standard Gaussian distribution. But I noticed there are two similar functions I can use, and I want to know which one is correct or both.
Assume I want to sample 8 points from a 2-dim standard Gaussian.
torch.distributions.MultivariateNormal(torch.zeros(2), torch.ey... | torch.randn gives you samples from a univariate standard normal distribution and reshapes them to the desired shape. So the mean of all the samples is 0 with unit variance.
x = torch.randn(1000000,2).numpy()
assert np.isclose(np.mean(x.flatten()), 0, atol=0.01)
plt.hist(x.flatten())
MultivariateNormal generates sampl... | https://stackoverflow.com/questions/72054349/ |
How to fix "initial_lr not specified when resuming optimizer" error for scheduler? | In PyTorch I have configured SGD like this:
sgd_config = {
'params' : net.parameters(),
'lr' : 1e-7,
'weight_decay' : 5e-4,
'momentum' : 0.9
}
optimizer = SGD(**sgd_config)
My requirements are:
Total epochs are 100
Every 30 epochs learning rate is decreased by a factor of 10
Decreasing learning rate w... | You have misunderstood the last_epoch argument and you are not using the correct learning rate scheduler for your requirements.
This should work:
optim.lr_scheduler.MultiStepLR(optimizer, [0, 30, 60], gamma=0.1, last_epoch=args.current_epoch - 1)
The last_epoch argument makes sure to use the correct LR when resuming t... | https://stackoverflow.com/questions/72058575/ |
UserWarning: Using a target size (torch.Size([1])) that is different to the input size (torch.Size([1, 1])) | I have this code:
actual_loes_score_g = actual_loes_score_t.to(self.device, non_blocking=True)
predicted_loes_score_g = self.model(input_g)
loss_func = nn.L1Loss()
loss_g = loss_func(
predicted_loes_score_g,
actual_loes_score_g,
)
where predicted_loes_score_g is tensor([[-24.9374]... | predicted_loes_score_g = tensor([[-24.9374]], grad_fn=<AddmmBackward0>)
which is size [1,1]
actual_loes_score_g = tensor([20.], dtype=torch.float64)
which is size [1]
You need to either remove a dimension from your prediction or add a dimension to your target. I would recommend the latter because that extra dim... | https://stackoverflow.com/questions/72061934/ |
Overlap two tensors of different size based on an offset in PyTorch | I have the following structure:
torch.Size([channels, width, height])
Let's say I have a tensor a
torch.Size([4, 512, 512])
And tensor b
torch.Size([4, 100, 100])
What I would like to do is to create a tensor c that is the result of "placing" tensor b on an arbitrary (width, height) coordinate offset of te... | This function would be fragile without a bunch of pre-conditions to catch for size mismatches, but I think this is basically what you're describing:
def place(a: torch.Tensor, b: torch.Tensor,
height: int, width: int,
channels: list[int]) -> torch.Tensor:
"""create a tensor `... | https://stackoverflow.com/questions/72069422/ |
torch_optimizer has no attribute 'SGD' | I am trying to import torch_optimizer on Google Colab. I have successfully !pip installed torch_optimizer and then imported it. However, every attribute I call with torch_optimizer gives an attribute error:
AttributeError: module 'torch_optimizer' has no attribute 'SGD'
This holds true for SGD, Adam, etc.
Here is a pho... | I have checked the documentation of pytorch-optimizer. The vanilla SGD is not there. There are small modifications of SGD as AccSGD, SGDW, SGDP etc. You can use the simple pytorch optimizer torch.optim.SGD. Check this visualization script where they are comparing the baseline SGD to other methods implemented by this li... | https://stackoverflow.com/questions/72070882/ |
pytorch layer input, output shape calculation | Can anyone help me to understand when I use conv1d and then a linear layer, What will be the inputs of the linear layer? How to calculate how many input features should I have to pass in pytorch
| In Pytorch, Linear layers operate using only the last dimension of the input tensor: [*features_in] -> [*,features_out].
However, Conv1D layers consider the last 2 dimensions of the input tensor: [batches,channels_in, length_in] -> [batches,channels_out, length_out].
Therefore, if no pre-processing is used, Linea... | https://stackoverflow.com/questions/72078299/ |
RuntimeError: output with shape [1] doesn't match the broadcast shape [10] | Hi I trying to make RBM Model code using pytorch module but got a issue in visible layer to hidden layer. Here is the problem part code.
h_bias = (self.h_bias.clone()).expand(10)
v = v.clone().expand(10)
p_h = F.sigmoid(
F.linear(v, self.W, bias=h_bias)
)
sa... | If you look at the pytorch functional.linear documentation it shows the weight parameter can be either 1D or 2D: "Weight: (out_features, in_features) or (in_features)". Since your weight is 2D ([1, 10]) it indicates that you are trying to create an output of size "1" with an input size of "10&q... | https://stackoverflow.com/questions/72081872/ |
How to install fastai on Mac m1 | I am trying to install fastai (version 1.0.61) on my new Mac m1.
I first tried:
pip install fastai==1.0.61
This gave me an error that I didn't have cmake, so I installed cmake successfully with brew install cmake.
Then, rerunning the fastai install command, I get this error:
Collecting fastai==1.0.61
Using cached fa... | fastai seems to need pyenv which needs CUDA to work. CUDA is available only on Nvidia GPUs and the MAC M1 has a completly differente SOC with no Nvidia GPU
You can read the actual error
CMake Error at /opt/homebrew/Cellar/cmake/3.23.1/share/cmake/Modules/FindCUDA.cmake:859
| https://stackoverflow.com/questions/72088567/ |
Access all batch outputs at the end of epoch in callback with pytorch lightning | The documentation for the on_train_epoch_end, https://pytorch-lightning.readthedocs.io/en/stable/extensions/callbacks.html#on-train-epoch-end, states:
To access all batch outputs at the end of the epoch, either:
Implement training_epoch_end in the LightningModule and access outputs via the module OR
Cache data across... | You can store the outputs of each training batch in a state and access it at the end of the training epoch. Here is an example -
from pytorch_lightning import Callback
class MyCallback(Callback):
def __init__(self):
super().__init__()
self.state = []
def on_train_batch_end(self, train... | https://stackoverflow.com/questions/72134203/ |
Improve Python (.exe) startup time | I created an exe with the PyInstaller. As soon as I enable the --onefile flag. The exe needs several minutes to start. When I build the application with the --onedir flag, the exe launches immediately after launch. In order to distribute the application better, it is important for me that the exe is created with the --... | Pyinstaller --onefile mode has to unpack all libraries before starting in a temporary directory, when you use --onedir they are already there. The problem is noticeable with big libraries like PyTorch ...
| https://stackoverflow.com/questions/72143729/ |
PyTorch distributed dataLoader | Any recommended ways to make PyTorch DataLoader (torch.utils.data.DataLoader) work in distributed environment, single machine and multiple machines? Can it be done without DistributedDataParallel?
| Maybe you need to make your question clear. DistributedDataParallel is abbreviated as DDP, you need to train a model with DDP in a distributed environment. This question seems to ask how to arrange the dataset loading process for distributed training.
First of all,
data.Dataloader is proper for both dist and non-dist t... | https://stackoverflow.com/questions/72154443/ |
torch.nn.BCEloss() and torch.nn.functional.binary_cross_entropy | What is the basic difference between these two loss functions? I have already tried using both the loss functions.
| The difference is that nn.BCEloss and F.binary_cross_entropy are two PyTorch interfaces to the same operations.
The former, torch.nn.BCELoss, is a class and inherits from nn.Module which makes it handy to be used in a two-step fashion, as you would always do in OOP (Object Oriented Programming): initialize then use. I... | https://stackoverflow.com/questions/72167344/ |
Which nvidia drivers version do I need? | I'm running on Ubuntu 20.04.4 LTS
I'm going to work with cuda 11.3 and torch 1.11 python 3.8
Which nvidia driver (version) do I need to install ?
How can I do it ?
| Download and install the latest version and you will be ok:
https://www.nvidia.com/download/index.aspx
| https://stackoverflow.com/questions/72181403/ |
my code couldn't find instance that was created initialized using pytorch | I implemented dataset class to use model, and When i strated train i get error
Traceback (most recent call last):
File "model.py", line 146, in <module>
train = Train()
File "model.py", line 70, in __init__
self.dataset.get_label()
File "model.py", line 61, in get_label... | This is happening because elif condition is not True during self.dataset object creation. Note that the self.path has a Train sub-string staring with an uppercase T, while elif is comparing it with lower-case train, which evaluates to False. This can be fixed by changing the elif as:
elif 'train'.lower() in self.path.l... | https://stackoverflow.com/questions/72181975/ |
Databricks notebook hanging with pytorch | We have a Databricks notebooks issue. One of our notebook cells seems to be hanging, while the driver logs do show that the notebook cell has been executed. Does anyone know why our notebook cell keeps hanging, and does not complete? See below the details.
Situation
We are training a ML model with pytorch in the Datab... | I figured out the issue. To solve this, adjust the parameters for the torch.utils.data.DataLoader
Disable pin_memory
Set num_workers to 30% of total vCPU (e.g. 1 or 2 for Standard_NC6s_v3)
For example:
train_loader = DataLoader(
train_dataset,
batch_size=32,
num_workers=1,
pin_memory=False,
shuffl... | https://stackoverflow.com/questions/72183733/ |
Normalization required for pre-trained model (PyTorch) | I am using a pre-trained model from pytorch:
model = models.resnet50(pretrained=True).to(device)
for param in model.parameters():
param.requires_grad = False
model.fc = Identity()
Should I normalize the data using my data mean and std or use the values used by the model creators?
class customDataset(torch.utils.da... | You must use the normalization mean and std that was used during training. Based on the training data normalization, the model was optimized. In order for the model to work as expected the same data distribution has to be used.
If you train a model from scratch, you can use your dataset specific normalization parameter... | https://stackoverflow.com/questions/72184771/ |
Exception when converting Unet from pytorch to onnx | I'm trying to convert a Unet model from PyTorch to ONNX.
Running the following code:
import torch
from unets import Unet, thin_setup
net = Unet(in_features=3, down=[16, 32, 64, 64, 64], up=[64, 64, 64, 128 + 1],
setup={**thin_setup, 'bias': True, 'padding': True})
net.eval()
inputs = torch.randn((1, 3, 768... | The problem is due to ONNX not having an implementation of the PyTorch 2D Instane Normalization layer.
The solution was to copy the relevant UNet code and implement the layer myself:
class InstanceNormAlternative(nn.InstanceNorm2d):
def forward(self, inp: Tensor) -> Tensor:
self._check_input_dim(inp)
... | https://stackoverflow.com/questions/72187686/ |
Extracting feature maps from ResNet | TLDR - what is considered best practice when extracting feature maps from ResNet?
I'm trying to feed the entire CIFAR10 dataset through ResNet18, to extract a new dataset that consists of some non-output activation of every sample in CIFAR10. I have implemented a code that generates this dataset, but the running time ... | What batch size are you using, and how much RAM do you have available? Resnet is a somewhat large model, and the layer you're extracting is quite large as well so storing all that in memory might be causing issues.
Try reducing your batch size, or storing intermediary results to disk and clearing them from memory.
You ... | https://stackoverflow.com/questions/72189867/ |
I was struggling build a lstm model during the model evaluation stage, bug shows different device, can anybody help me out |
for the model building stage
import torch
from torch import nn
import torch.nn.functional as F
from torch import utils
class LSTM(nn.Module):
def __init__(self, vocab_size, embed_dim):
super().__init__()
self.embedding = nn.EmbeddingBag(vocab_size, embed_dim) # embedding layer
self.l... | The error indicates that two tensors are on different devices (clear to understand).
Since you'd moved your input tensor to your GPU via sentence = sentence.to(device()) but not your model, the model's parameters are on the CPU which causes this error. Just add model.to(device()) before your training procedure starts.
| https://stackoverflow.com/questions/72199637/ |
How to access the save results of yolov5 in different folder? | I am using the below code to load the trained custom Yolov5 model and perform detections.
import cv2
import torch
from PIL import Image
model = torch.hub.load('ultralytics/yolov5', 'custom',
path='yolov5/runs/train/exp4/weights/best.pt', force_reload=True)
img = cv2.imread('example.jpeg')[:, :, ::-1] # OpenCV ima... | You can make changes in the function definition of results.save(), the function can be found in the file yolov5/models/common.py. By default the definition is:
def save(self, labels=True, save_dir='runs/detect/exp'):
save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # incr... | https://stackoverflow.com/questions/72207081/ |
PyTorch - FineTuning bert - Oscillating loss - Very bad accuracy | I have been trying to train a model on vulnerability detection through source code. And, after a little bit of searching, I thought a very good starting point could be using a pre-trained transformer model from HuggingFace with PyTorch and pl.lightning torch. I chose DistilBert because it was the fastest one.
I have an... | Here,
def finetune(self):
self.fine_tune = True
for name, param in self.bert.named_parameters():
if 'layer.5' in name:
param.requires_grad = True
try to unfreeze more layers at the end of the neural net, maybe the weights are saturated and not learning enough. Also, pay att... | https://stackoverflow.com/questions/72207543/ |
TypeError: backward() got an unexpected keyword argument 'variables' | I am using the recurrent Gaussian Process library. I believe the code is developed by older versions of python and pytorch. I ran one of the experiments of the model after cloning the repository
python ./testing/rnn_rgp_test.py
I got this error message from this line of the rnn_encoder.py script:
./RGP/autoreg/rnn_enc... | Version 0.3.1 of PyTorch seems to be the last version with the variables parameter. Ideally, the RGP library should have documented which version of their dependencies they use but they didn't. Given that their Git repo seems to be inactive, you have several choices:
Use old versions of whatever libraries they require... | https://stackoverflow.com/questions/72208333/ |
Why is RandomCrop with size 84 and padding 8 returning an image size of 84 and not 100 in pytorch? | I was using the mini-imagenet data set and noticed this line of code:
elif data_augmentation == 'lee2019:
normalize = Normalize(
mean=[120.39586422 / 255.0, 115.59361427 / 255.0, 104.54012653 / 255.0],
std=[70.68188272 / 255.0, 68.27635443 / 255.0, 72.54505529 / 255.0],
)
... | The padding is applied to the input image or tensor before applying the random crop. Ultimately, the output image has a spatial size equal to that of the provided size(s) given to the T.RandomCrop function since the operation is performed after.
After all, it makes more sense to pad the input image rather than the crop... | https://stackoverflow.com/questions/72208865/ |
TypeError: forward() takes 1 positional argument but 2 were given while inferencing of PyTorch model | My mode likes the following:
class RankingModel(nn.Module):
def __init__(self, conf: Dict[Text, Any], **kwargs: Any):
super(RankingModel, self).__init__()
self.conf = deepcopy(conf)
......
def forward(self, **_features): # the model input is a torch.utils.data.Data... | Your forward expect argument with key like forward(data=myarray) because you used double asterix when defining it and didn't give positional argument.
either use def forward(self, input, **kwargs)which would read the first argument of the call and then use other argument as kwargs
or call it with:
model(keyword=x_test... | https://stackoverflow.com/questions/72211429/ |
Why won't PyTorch RNN accept unbatched input? | I'm trying to train a PyTorch RNN to predict the next value in a 1D sequence. According to the PyTorch documentation page, I think I should be able to feed unbatched input to the RNN with shape [L,H_in] where L is the length of the sequence and H_in is the input length. That is, a 2D vector.
https://pytorch.org/docs/st... | I would recommend turning your input into a 3d array by adding a batch size of one with:
torch.unsqueeze(x1_input, dim=0).
| https://stackoverflow.com/questions/72234859/ |
How do I calculate the mean of values with the same label given by a mask for multi-dimensional data? | My input x is a tensor of [B, C, H, W] dim. B is batch size, C number of channels, H height and W width. I have a mask m of [H, W] dim. For each batch size and each channel I want to use the mask m to calculate the mean of all values in [H, W] with the same label.
For example:
B = 2
C = 2
H = 2
W = 3
x = torch.tensor([... | I figured out how to get the mean values for multi-dimensional data. I flatten H and W and then call scatter_mean from torch_scatter. That gives me the mean values per label for each channel and batch.
x = x.view(B, C, H*W)
m = m.view(B, 1, H*W)
mean = torch_scatter.scatter_mean(x, m, dim=-1)
| https://stackoverflow.com/questions/72255702/ |
Steps for Machine Learning in Pytorch | When we define our model in PyTorch. We run through different #epochs. I want to know that in the iteration of epochs.
What is the difference between the two following snippets of code in which the order is different? These two snippet versions are:
I found over tutorials
The code provided by my supervisor for the pro... | The only difference is when the gradients are cleared. (when you call optimizer.zero_grad()) the first version zeros out the gradients after updating the weights (optimizer.step()), the second one zeroes out the gradient after updating the weights. both versions should run fine. The only difference would be the first i... | https://stackoverflow.com/questions/72262608/ |
pytorch: simple recurrent neural network for image classification | I am making a simple recurrent neural network architecture for CIFAR10 image classification. I am not interested not use pre-defined RNN class in PyTorch because i am implementing from scratch according to figure. I am getting input tensor errors in the same device. I am not sure whether my code is right or wrong. Any... | You need to make sure the tensors are on the same device (cpu/gpu) before you are contacting them
you can add a device parameter to your class and use it:
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size, num_classes, device='cuda'):
super(RNN, self).__init__()
self.... | https://stackoverflow.com/questions/72267262/ |
Transforms.Normalize returns values higher than 255 Pytorch | I am working on an video dataset, I read the frames as integers and convert them to a numpy array float32.
After being loaded, they appear in a range between 0 and 255:
[165., 193., 148.],
[166., 193., 149.],
[167., 193., 149.],
...
Finally, to feed them to my model and stack the frames I do the "ToTe... | The behavior of torchvision.transforms.Normalize:
output[channel] = (input[channel] - mean[channel]) / std[channel]
Since the numerator of the lefthand of the above equation is greater than 1 and the denominator of it is smaller than 1, the computed value gets larger.
The class ToTensor() maps a tensor's value to [0, ... | https://stackoverflow.com/questions/72275297/ |
No CMAKE_CUDA_COMPILER could be found when installing pytorch | I am trying to install pytorch from source. The reason why I am doing this (instead of just pip install pytorch) is because I need the sm_86 support for my GPU (NVIDIA GTX 3060 Ti) and so I have set the TORCH_CUDA_ARCH_LIST=8.6 variable. I've read that this variable affects only the source installation.
Basically I am ... | My guess is that the CUDA installation is somehow messed up / invisible - otherwise CMake should have noticed it. You can overcome the issue more "manually" by running CMake like so:
CUDACXX=/usr/local/cuda-11.7/bin/nvcc cmake -S /path/to/source/dir -B /path/to/build/dir
(as you have installed CUDA under /us... | https://stackoverflow.com/questions/72278881/ |
Massive neural network training time increase by inverting images in a data set | I have been working with neural networks for a few months now and I have a little mystery that I can't solve on my own.
I wanted to create and train a neural network which can identify simple geometric shapes (squares, circles, and triangles) in 56*56 pixel greyscale images. If I use images with a black background and ... |
Color inversion
You have to essentially “switch” WxH pixels, hence touching every possible pixel during augmentation for every image, which amounts to lots of computation.
In total it would be DxWxH operations per epoch (D being size of your dataset).
You might want to precompute these and feed your neural network wi... | https://stackoverflow.com/questions/72286749/ |
AttributeError: 'Upsample' object has no attribute 'recompute_scale_factor' | I get error on line x_stats = dec(z).float().
import torch.nn.functional as F
z_logits = enc(x)
z = torch.argmax(z_logits, axis=1)
z = F.one_hot(z, num_classes=enc.vocab_size).permute(0, 3, 1, 2).float()
x_stats = dec(z).float()
x_rec = unmap_pixels(torch.sigmoid(x_stats[:, :3]))
x_rec = T.ToPILImage(mode='RGB')(x_re... | Install Torch version, this will solve the issue
pip install torchvision==0.10.1
pip install torch==1.9.1
| https://stackoverflow.com/questions/72297590/ |
Pytorch-forecasting:: Univariate AssertionError: filters should not remove entries all entries | I tried to do univariate forecasting with Pytorch-Forecasting.
But I got following error on TimeSeriesDataSet
AssertionError: filters should not remove entries all entries - check
encoder/decoder lengths and lags
I have tried googling for the error, read the suggestion and make sure my training_df has sufficient numb... | After some experiment, it seems that the training_df length (196) should be larger
than or equal to (context_length + prediction_length).
So for example above it works once I update the context_length to 27 * 7 instead of 28 * 7.
Since 27 * 7 + 7 = 196.
While 28 * 7 + 7 > 196.
| https://stackoverflow.com/questions/72302786/ |
Google Colab: torch cuda is true but No CUDA GPUs are available | I use Google Colab to train the model, but like the picture shows that when I input 'torch.cuda.is_available()' and the ouput is 'true'. And then I run the code but it has the error that RuntimeError: No CUDA GPUs are available.
| Try to install cudatoolkit version you want to use
"conda install pytorch torchvision cudatoolkit=10.1 -c pytorch"
| https://stackoverflow.com/questions/72303759/ |
Pytorch: Dataloader shuffle=False producing same batches | class DataSet(torch.utils.data.Dataset):
def __init__(self,dataframe,n_classes=3,w=384,h=384,apply_aug=False):
self.data=dataframe
self.n_classes=n_classes
self.apply_aug=apply_aug
self.w=w
self.h=h
self.transform=A.Compose([A.Rotate(limit=30,p=0.8),
A.Horiz... | You use iterator incorrectly:
next(iter(dataloader))
Every step you create a new iterator and take the first element (hence it's always the same because the iterator is actually the same). Instead you should create the iterator before for-loop and call next() in every step.
But why not simply iterate over your datalo... | https://stackoverflow.com/questions/72314135/ |
How to calculate mutual information in PyTorch (differentiable estimator) | I am training a model with pytorch, where I need to calculate the degree of dependence between two tensors (let's say they are the two tensors each containing values very close to zero or one, e.g. v1 = [0.999, 0.998, 0.001, 0.98] and v2 = [0.97, 0.01, 0.997, 0.999]) as a part of my loss function. I am trying to calcul... | Mutual information is defined for distribution and not individual points. So, I will write the next part assuming v1 and v2 are samples from a distribution, p. I will also take that you have n samples from p, n>1.
You want a method to estimate mutual information from samples. There are many ways to do this. One of t... | https://stackoverflow.com/questions/72323285/ |
How to require gradient only for some tensor elements in a pytorch tensor? | I like to use a tensor with only a few variable elements which are considered during the backpropagation step. Consider for example:
self.conv1 = nn.Conv2d(3, 16, 3, 1, padding=1, bias=False)
mask = torch.zeros(self.conv1.weight.data.shape, requires_grad=False)
self.conv1.weight.data[0, 0, 0, 0] += mask[0, 0, 0, 0]
pri... | You can only switch on and off gradient computation at the tensor level which means that the requires_grad is not element-wise. What you observe is different because you have accessed the requires_grad attribute of conv1.weight.data which is not the same object as its wrapper tensor conv1.weight!
Notice the difference:... | https://stackoverflow.com/questions/72325827/ |
How can I change my environment architecture to arm64 from x86-64? | I am an MacBook M1 user and I am trying to use M1 GPU (MPS) supported by Pytorch. I read that I need to make sure my system is arm64 rather than x86 so I created my env as below:
CONDA_SUBDIR=osx-arm64 conda create -n nlp2 --clone nlp
(nlp2) twang20@C02G82XRQ05N ~ % python --version
Python 3.9.7
(nlp2) twang2... | Cloning is going to copy/link the packages from the previous environment, which is already x86_64. Instead, you would need to recreate the environment. Something like:
## dump previous environment
conda env export -n nlp --from-history > nlp_x86.yaml
## create new one with temp subdir
CONDA_SUBDIR=osx-arm64 conda e... | https://stackoverflow.com/questions/72343472/ |
Input Shape of Deep learning model | I have created deep learning models in different input shapes.
For Testing , I am resizing the images according to the model's input shape manually
I need to resize the image with input shape of the deep model
Any Command to find the input shape of the model in PYTORCH
model = torch.load(config.MODEL_PATH).to(config.D... | This is a tricky question because your input size will can depend on several components of your model. The short answer is you can't.
Concerning the number of channels in your input tensor, you can infer this solely based on the first convolutional layer. Assuming your model is a two dimensional convolutional network,... | https://stackoverflow.com/questions/72346720/ |
Why does a call to torch.tensor inside of apply_async fail to complete (seems to block execution)? | I'm trying to understand why the following simple example doesn't successfully complete execution and seems to get stuck on the first line of really_simple_func (on Ubuntu machines, but not Windows). The code is:
import torch as t
import numpy as np
import multiprocessing as mp # I've tried both multiprocessin... | Unfortunately, I cannot provide any answers to your questions.
I can, however, share experiences with seemingly the same issue. I use a Linux machine with torch 1.8.1 and numpy 1.19.2.
When I run the following code on my machine:
with Pool(max_pool) as p:
pool_outputs = list(
tqdm(
p.imap(lambda... | https://stackoverflow.com/questions/72348083/ |
the same pretrained model with same input , running multiple times gives different outputs | I load a pretrained Resnet152 from torchvision. I evaluate the model multiple times with the same input image, but each time the output is different. It's very strange. Anyone knows what is the reason? My code is
from torchvision import transforms
import torch
from torchvision import models
from PIL import Image
# loa... | The model torchvision.models.resnet152 contains batch normalization layers with track_running_stats set to True. This means that whenever the model is called in training mode (i.e., when model.train() is set), the running_mean and running_var parameters of such batch normalization layers get updated to include the data... | https://stackoverflow.com/questions/72357323/ |
Detect Apple silicon GPU core count | Similar to this question, I am interested in detecting the exact GPU inside a Mac equipped with Apple silicon.
I am interested in knowing the exact GPU core count.
sysctl -a | grep gpu
or
sysctl -a | grep core
does not seem to provide anything useful.
| You can use ioreg like this:
ioreg -l | grep gpu-core-count
You can also look up an object with class that's named something like AGXAcceleratorG13X and see all of its properties, gpu-core-count will also be there.
| https://stackoverflow.com/questions/72363212/ |
How to not break differentiability with a model's output? | I have an autoregressive language model in Pytorch that generates text, which is a collection of sentences, given one input:
output_text = ["sentence_1. sentence_2. sentence_3. sentence_4."]
Note that the output of the language model is in the form of logits (probability over the vocabulary), which can be co... | Okay solved it. Posting answer for completion.
Since the output is in the form of logits, I can take the argmax to get the indices of each token. This should allow me to know where each period is (to know where the end of the sentence is). I can then split the sentences in the following way to maintain the gradients:
s... | https://stackoverflow.com/questions/72368294/ |
How to write many and similar python scripts at once? | I need to have 100 of those similar python scripts that have MyData class from MyData_1 to MyData_100.
import torch
import numpy as np
from torch_geometric.data import InMemoryDataset, Data
from torch_geometric.utils import to_undirected
class MyData_1(InMemoryDataset):
def __init__(self, root, transform=None):
... | I didn't fully understand the reason why you need to create 100 different classes.
Is it because you need to return mydata_1.npz to mydata_100.npz? If then, You can create a single class like this:
class Myclass:
def __init__(self, index):
self.index = index
def raw_file_names(self):
return "mydata_{}... | https://stackoverflow.com/questions/72371704/ |
How to free all GPU memory from pytorch.load? | This code fills some GPU memory and doesn't let it go:
def checkpoint_mem(model_name):
checkpoint = torch.load(model_name)
del checkpoint
torch.cuda.empty_cache()
Printing memory with the following code:
print(torch.cuda.memory_reserved(0))
print(torch.cuda.memory_allocated(0))
shows BEFORE running checkp... | It probably doesn't. Also, it depends on what you call memory leak. In this case, after the program ends all memory should be freed, python has a garbage collector, so it might not happen immediately (your del or after leaving the scope) like it does in C++ or similar languages with RAII.
del
del is called by Python a... | https://stackoverflow.com/questions/72380592/ |
Torch neural network does not train | I have implemented a very simple neural network in the torch framework
def mlp(sizes, activation, output_activation=torch.nn.Identity):
layers = []
for j in range(len(sizes)-1):
act = activation if j < len(sizes)-1 else output_activation
layers += [torch.nn.Linear(sizes[j], sizes[j+1]), act()]
return torch.n... | I am not sure if this is the main cause, but the statement
act = activation if j < len(sizes)-1 else output_activation
appears to be logically incorrect. In the loop, j can take values from 0 to len(sizes)-1, so the condition is always true. This means that your network has a ReLU right at the end, and so can only ... | https://stackoverflow.com/questions/72383323/ |
How to apply differential privacy on list of data? | How to apply differential privacy on a list of data.
OpenMined release a differential privacy project called PyDP 2 years ago.
On the examples provided, they showed how to compute the PyDP on the data by computing some statistical features such as the mean, Max, Median.
Is there a way to apply a differential privacy t... | Here are my two cents on the question,
The idea of differential privacy is to publish aggregated information of sensitive values only if noise is added to the aggregated info. This will in terms make it infeasible to match sensitive values to their owners, and also make the dataset not highly dependent on any particula... | https://stackoverflow.com/questions/72390974/ |
Adding in the weight parameter for PyTorch's cross-entropy loss causes datatype RuntimeError | I'm currently using PyTorch to train a neural network. The dataset that I'm using is a binary classification dataset with a large number of 0's.
I decided to try and use the weight parameter of PyTorch's cross-entropy loss. I calculated the weights via sklearn.utils.class_weight.compute_class_weight and got weight valu... | You can create a tensor from your weights as follows.
Also, remember to match the devices between the weights and the rest of your tensors.
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
weights = torch.tensor([0.58479532, 3.44827586],dtype=torch.float32).to(device)
| https://stackoverflow.com/questions/72400142/ |
How to train pytorch model using large data file while using Dataloader? | I am using pytorch Dataset class and Dataloader to load data. The class and loader looks like the following.
class Dataset(Dataset):
def __init__(self):
self.input_and_label = json.load(open(path_to_large_json_file)) # Large file
self.dataset_size = len(self.input_and_label)
def __getit... | You get a CUDA OOM error, it is not related to the file itself being large, but single example being large.
JSON file loads correctly to RAM, but 8 examples cannot fit on your GPU (which is often the case for images/videos, especially with high resolution).
Solutions
Use a larger GPU (e.g. cloud provided)
Use a smalle... | https://stackoverflow.com/questions/72410553/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.