user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
bfeeny
I am trying to apply Class Weights to BCEWithLogitsLoss. I felt I had read every post on this and was well prepared to do so but apparently not.I have two classes.print(class_weights) [ 0.50897302 28.36130137] criterion = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(class_weights, device=device))Each batch is 136 item...
KFrank
Hello bfeeny! Yes, I think that is what I am saying. But, to be concrete, let’s take an extreme example: Let’s say that your entire training set consists of 1,000 samples, 990 class-“0” samples, and 10 class-“1” samples. If you want to reweight the classes in your loss function to fully accou…
ayadav01
I am slightly confused on using weighted BCEWithLogitsLoss. My input data shape is : 1 x 52 x 52 x 52 (3D Volume) and label for each volume is either 0 or 1 and i am using a batch size of 5. So, at each epoch, input is 5 x 1 x 52 x 52 x 52 and label is 1 x 5. The way i am calculating weights is:weight_0 = count_of_lbl1...
KFrank
Hello Anil! I prefer calculating the weight based on the entire dataset, rather than on a per-batch basis, although it shouldn’t matter if your batches are of reasonable size. The point is that the weights aren’t magic numbers that have to be just right. They are approximate numbers that are…
hiepnguyen034
I was a bit confused when testing thenn.NLLLoss()today. For example, let’s say I haveloss = nn.NLLLoss() y_hat = torch.FloatTensor([[0.7,0.1,0.2]]) y=torch.LongTensor([0])Then,loss(y_hat,y)returns-0.7. Isn’t it true that by definition, the NLL in this case should be-log(0.7) = 0.35.Is there something that I am missing...
KFrank
Hi Hiep! The issue is that NLLLoss expects log-probabilities, rather than probabilities, as its input. From the documentation forNLLLoss: The input given through a forward call is expected to contain log-probabilities of each class. If you calculate log (y_hat) yourself, you will get the e…
abdeljalil
I made a very simple 3-layered fully-connected network for binary classification (using NASA C-MAPSS dataset to classify healthy and faulty turbofan engines). the input is vector of length 26 and the output is a sigmoid activation. The task is pretty easy (a basic logistic regression model gives me 100% test accuracy),...
KFrank
Hello Abdeljalil! It’s probably not the issue, but please also try SGD with no momentum (momentum = 0.0). Some comments based on your edited post: First, get rid of the sigmoid() at the end of your model. Thus: output = self.fc3(x) return output And use BCEWithLogitsLoss (ra…
zhenhua-wang
Hi everyone,I am working on a classification question, where the outcomes contain more than one categorical variable. Each of them has multiple classes. For example, y could be [y1, y2, y3, y4, y5] and each y_i is a categorical variable with multiple classes.The only solution that I could think of is to have separate o...
KFrank
Hello Zhenhua! Let me tell you how I understand your question. I don’t see the use case you describe as being a multi-label, multi-class problem. I guess I would call it something like “multiple multi-class.” That is (and to make things simpler, let me speak of just y_1 and y_2), let’s say y…
Bled_Clement
Hi there,I’m trying to create a function in a network with trainable parameters. In my function I have an exponential that for large tensor values goes to infinity. What would the best way to avoid this be?The function is as follows:step1 = Pss-(k*Pvv) step2 = step1*s step3 = torch.exp(step2) step4 = torch.log10(1+ste...
KFrank
Hello Clement! Please feel free to post a short, complete, runnable script that has the original code you posted (that fails when the tensor values become to large), together with your improved attempt (using logsumexp() or whatever). If you show us what fails or what the discrepancy is, some…
sakuraiiiii
Hi, I want to do a constrained optimization withPyTorch. I want to find the minimum of a function $f(x_1, x_2, \dots, x_n)$, with \sum_{i=1}^n x_i=5 and x_i \geq 0. I think this could be done viaSoftmax. So I follow theHow to do constrained optimization in PyTorchimport torch from torch import nn x = torch.rand(2) x.r...
KFrank
Hiiiii Sakuraiiiii! The short answer is that Softmax isn’t the right way to enforce your constraint. The medium-short answer is that you’re getting almost the right answer, but for the wrong reason. The somewhat longer short answer is that Softmax isn’t the right way to enforce your constrain…
Julio
I currently have a trained system with a Softmax as the activation function, which returns a vector of probabilities of each class, all together suming 1 (example: [0.6. 0.1, 0.15, 0.05, 0.1])I was using this model to perform a multi class classification, but i’d like to try it with a multi label approach, and i was wo...
KFrank
Hi Julio!sigmoid()should do what you want. A couple of points: I imagine that you have a Linear layer feeding your activation function. The Linear layer produces a set raw-score logits. softmax() converts these to a set class probabilities that sum to one. sigmoid() converts each logit in…
RyanPatterson
Im trying to train the model using a UNet framework to detect cracks in roads. My images are grayscale between 0-1.0 with shape (batchsize,#classes, image height, image width). My masks are binary with 0 for background(I dont care about) and 1 for the crack sections. My first question is can I get away with using only ...
KFrank
Hello Ryan! You’re basically on the right track. Let me make some suggestions (but, note, you can usually do more-or-less the same thing in a couple of different ways). You are working on a binary segmentation problem. (This is a binary classifier, where you classify individual pixels.) You…
pytorcher
I am trying to convert code from an old pytorch version on an old computer to a new one. I have it very close, but it is still not getting quite the same results. Im having trouble determining where actual changes are happening and where it is just tiny floating point differences. I already have converted my entire ...
KFrank
Hi Py! My conclusion is that your use of .data() is the cause of “does not work at all in 1.3.1.” Note, what you show below does not replicate the "does not work at all " problem – it replicates the “agrees up to expected floating-point round-off” so-called problem. I assume that this is ru…
pytorcher
I am trying to convert a program way back from pytorch 0.3 to 1.3.1. I have it very close to doing the same thing when I debug batch by batch, but over time the floating point changes make it impossible to tell where my actual functions are different and where it is just floating point errors. I know there is double(...
KFrank
Hi Py! No. There is neither a built-in way to do this, nor any practical way to do it “by hand.” But you speak as if you are convinced that your “actual functions are different,” even though the computational evidence you cited in your earlier thread shows that your “actual functions” agree …
pytorcher
I am using cross entropy loss on two computers and one of them is returning different numbers. I believe I have tracked it down to one of the computers returning slightly wrong values for softmax. Any reason why this would be? The computer which is wrong, with numbers displayed here, is running pytorch 1.3.1.(Pdb) (...
KFrank
Hi py! This is floating-point round-off error. First cast X to a dtype = torch.double tensor, and then redo your test. Your “right” numbers and “wrong” numbers will now agree to about twice as many decimal places. Best. K. Frank
Mainul
As the title says, for example,torch.tensor(0.83257929)tensor(0.83257931)why the value changes. how to stop this behaviour?
KFrank
Hello Mainul! This is due to floating-point round-off error. It can’t be avoided. If you need greater precision, create your tensor as dtype = torch.double. Note, with double precision, you will still have round-off error, just less of it. Best. K. Frank
jhmenke
My process looks similar to this:https://fluxml.ai/assets/2019-03-05-dp-vs-rl/trebuchet-flow.pngI have some features and some labels. From these labels, i can invoke a custom function to check whether some target criteria match. I don’t care about the labels per se, only that the target criteria are met. Now, similar t...
KFrank
Hi Jan-Hendrik! It is not unreasonable to compute your gradients numerically (although suboptimal if you can compute them analytically). So, in your forward pass you might compute: loss_np = numpy_stuff (x, y) <loop over x_i>: xdelt_i = x_i + delta grad_i = (numpy_stuff …
John_J_Watson
I am quite new to pytorch, and I am going through the [transfer learning tutorials] on resnet(https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html), and I notice this line (which is also there in the inference mode):outputs = model(inputs) _, preds = torch.max(outputs, 1)which, when I go through the d...
KFrank
Hello John! It depends on what you are trying to do, and what your loss function is. It sounds as if you might be working on a twenty-class classification problem. In such a case, you would typically use CrossEntropyLoss as your loss function. Your model would output directly the results of …
m3tobom_M
Hello. I am working on this tutorial:TorchVision Object Detection Finetuning Tutorial — PyTorch Tutorials 2.2.0+cu121 documentation. I trained model and made predictions with py file below:from PIL import Image import torch import numpy as np from torchvision import transforms from torch.autograd import Variable import...
KFrank
Hi m3! A common approach for this issue is non-maximal suppression. I don’t know of a single, best reference for this, but it is discussed broadly. Best. K. Frank
dongsup_kim
Hi. I’m trying to build a loss function for regression over each pixels of classes given classes and target values of pixels.Input arguments are y_pred [N,C,H,W], classes[N,H,W], y[N,H,W].each pixels belong to certain class which is second argument and calculate the mse loss of y_pred and y.What I’d like to know is thi...
KFrank
Hello Dongsup! Yes, it is (but the requires_grad=True for s is unnecessary, and might cause problems). Also, note that you can get rid of the loop by using gather() to line up the desired elements of y_pred, as specified by classes, with y. This is illustrated by the following pytorch version…
Cici1
I’m training a CNN model and got this error:Screen Shot 2020-05-10 at 10.20.48 AM973×218 35.9 KBThis is my code for training the model:def train_cnn(log_interval, model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.t...
KFrank
Hi Cici! The short answer is that your target contains a value of 23, but you are training a 10-class classifier for which your class labels must run from 0 to 9. (As an aside, please don’t post screen-shots of textual information. They can’t be searched or copy-pasted.) Your output has shap…
Masilive_Sifanele
I need your help. Running the code below throws:RuntimeError: size mismatch, m1: [5 x 10], m2: [5 x 32] at /pytorch/aten/src/TH/generic/THTensorMath.cppI looked at similar questions but they are image related and suggest flattening the input, I tried them with no luck.I’m using Python 3.6.8 and torch 1.1.0**code sample...
KFrank
Hi Masilive! The short answer is that you have the dimensions of your input swapped. You would want something like, for example, “m1: [10 x 5]”. Pytorch will interpret state as a batch of 5 samples, each of which is a vector of 10 values. But the first layer of your Sequential is a Linear t…
Ali_Amiri
Hi,I have a model with output shape: (batch_size, N, M) and target shape: (batch_size, N, M)this is a classifier.so I should use NLL or CrossEntropy as the loss function.but torch gives me1D target tensor expected, multi-target not supportederrorhow can I fix this?
KFrank
Hi Ali! Well, you should tell us what “output” means, what “target” means, and what “N” and “M” are. Otherwise, we will have to guess. But let me guess a little bit, and make the following comment: If you are performing a multi-class classification problem (but not a multi-label problem), the…
John_J_Watson
I am quite new to pytorch and I am looking to apply L2 normalisation to two types of tensors, but I am npot totally sure what I am doing is correct:[1]. type 1 (in the forward function) has shapetorch.Size([2, 128])and I would like to normalise each tensor (L2 norm).for this case, I do:F.normalize(tensor_variable, p=2,...
KFrank
Hi John! Yes, your use of normalize() is correct. Just compute the (square of the) norm: (torch.nn.functional.normalize (tensor_variable, p = 2, dim = 1)**2).sum (dim = 1) and check that you get 1 for each row of tensor_input. You can find the documentation here:normalize. Best. K. Frank
ilya_L
Hi everyone,I’m trying to use a custom loss function which is something like:torch.dist(torch.argmin(predictedData).double(), actualData, p=2)loss.backward()This function outputs a tensor with requires_grad = False and therefore when I try to backprop I get:RuntimeError(‘element 0 of tensors does not require grad and d...
KFrank
Hi Ilya! First off, I suspect that you don’t* really want to do what you think you want to do. However, making some guesses about what (you think) you want, you could try something like this. The key issue is that argmin maps onto discrete integers, and so, is not usefully differentiable. So…
Mainul
I was trying to understand howweightis inCrossEntropyLossworks by a practical example. So I first run as standard PyTorch code and then manually both. But the losses are not the same.from torch import nn import torch softmax=nn.Softmax() sc=torch.tensor([0.4,0.36]) loss = nn.CrossEntropyLoss(weight=sc) input = torch.t...
KFrank
Hello Mainul! When using CrossEntropyLoss (weight = sc) with class weights to perform the default reduction = 'mean', the average loss that is calculated is the weighted average. That is, you should be dividing by the sum of the weights used for the samples, rather than by the number of sampl…
yash1994
Hi,I have got a task (video analysis) where I have to divide the last fully connected layer of(1+2)D ResNetinto multiple chunks and perform classification loss calculation on each individual chunk usingCrossEntropyLoss. With more context, I’ve reshaped my model’s last layer (FC) to generate the output of shape (64, 4, ...
KFrank
Hello Yash! As an aside, you can use the “K-dimensional case” feature of CrossEntropyLoss (if you’re using a recent enough version of pytorch) to eliminate your for loop. output.size (1) * torch.nn.CrossEntropyLoss() (output.transpose (1, 2), target) should yield the same result as your calcul…
FahadAslamCS
I am facing a problem with my own data dimensions. I am completely new to PyTorch I will be grateful if one can help me here.I am getting error of “Target (10)(this no changes between my class name) is out of bounds”I have 6 classes denoted by 0, 5,20,40, 2.5, 10I do not know how to handle it.np_target = pd.read_csv('...
KFrank
Hello Fahad! When you use CrossEntropyLoss, your target y that you pass in to criterion must be integer class labels that take on values running from 0 to nClass - 1 (in your case, (0, 1, 2, 3, 4, 5)). If your class labels are originally (0, 5, 20, 40, 2.5, 10), you will have to remap them bef…
victorc25
Hello,Is it possible to multiply a trained model by a single scalar that is trainable and backpropagate the loss to that scalar?I want to do this for two networks, so the idea is to train those two scalars to find how to ideally combine the two models’ weights (not the outputs).Thanks in advance for any guidance.
KFrank
Hi Victor! I was imagining that you had two models with the same architecture, that is, that all of the layers and activations match up. The only difference is that they have been trained (or fine tuned) differently, so that the trained weights differ. In this case, model A’s activation1 and …
Muppet
Hi guys,How efficient is the following?rewards = torch.as_tensor(rewards).to(self.device).float()vsrewards = torch.as_tensor(rewards).float().to(self.device)What is the best way to benchmark that given all the randomness with GPU?Lastly, if a tensor x on the GPU is already a float and then applying another x = x.float(...
KFrank
Hi Muppet! Speaking as a non-expert, I would think that rewards = torch.as_tensor (rewards, dtype = torch.float, device = torch.device('cuda')) would be the way to go. I believe that pytorch will “no-op” any unneeded casts. Note, if rewards starts out as, for example, a numpy double array (a…
tonyr
I know the basics of PyTorch and I understand neural nets.I have a set of observations and they go through a NN and result in a single scalar. I want to maximise that scalar (i.e. perform gradient ascent so that the expectation is maximised). Is there a torch.nn.*Loss function for this? I can’t see it. One hack would b...
KFrank
Hi Tony! Just use pytorch to minimize the negative of your scalar. That is: my_single_scalar = model (input) my_negative_scalar = -my_single_scalar optim.zero_grads() my_negative_scalar.backwards() optim.step() (Pytorch optimizers minimize their objective functions. To maximize, you just flip…
dallonsi
Hi !Say I want to use sort this list with torch:[1, 5, 3, 4].The following code in Python 3.x:from torch import tensor import torch t = tensor([1,5,3,4]) t = torch.sort(t, descending=True) print(t)returnstorch.return_types.sort( values=tensor([5, 4, 3, 1]), indices=tensor([1, 3, 2, 0]))The listindicesfrom the output ...
KFrank
Hi Damien (and Alex)! In my mind, the cleanest approach is to take the argsort of the permutation: import torch torch.__version__ t = torch.LongTensor ([1, 5, 3, 4]) perm = torch.sort (t, descending = True)[1] perm inverse = torch.sort (perm)[1] # invert permutation inverse perm[inverse] #…
SubhankarHalder
Hello, I am a beginner in Deep Learning and PyTorch. If my question is not relevant or does not follow the community guidelines, please pardon me.I am studying the following Kaggle kernel and trying to replicate it:https://www.kaggle.com/piantic/plant-pathology-2020-pytorch-for-beginnerIn the section titled, “PreTraine...
KFrank
Hi Subhankar! Pytorch’s CrossEntropyLoss takes as its target (labels) a single integer class label for each sample in the batch (i.e., a tensor of shape [nBatch]). That is, target == 2 means that class “2” is the right answer with 100% certainty. The notion of cross-entropy is more general, …
JohanR
Hey, I’m attempting to run this pix2pix PyTorch implementation (https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix) on my old GeForce GTX 660 Ti that uses Driver Version: 340.107. As far as I’ve understood from other posts and websites my driver can only run CUDA 6.0 or 6.5. Is there any PyTorch that can run with ...
KFrank
Hello Johan! I went through a similar issue, and was helped greatly by the answers I got in this thread (thanks, in particular, to@ptrblckand@peterjc123): In particular, one of thesepytorch legacy buildsworked for me. Note, going this route pushed me back to pytorch version 0.3.0. I sup…
Absurd
Supporting that I have a N × 4 tensor which is N rectangular ROIs of a mask(C × H × W), and I want to sum up all value of each channel inside a ROI to get a tensor of size N × C, the only way I can figure out is using a for loop. But this method is very slow, so I want to ask if there are faster way to do this?The for...
KFrank
Hi Absurd! There are two issues here: First, using for-loops generally slows pytorch down because they prevent pytorch from performing operations on entire tensors using its built in (and hopefully optimized) tensor operations. Second, in your method you sum over each rectangular ROI separatel…
jafioti
Hi,I’m working on a system in which I want the network to predict one of the classes with a very high score and the others a very low score. These scores are attention weights, and they select different sections of the network downstream, so I want the network to choose a single downstream section at once and not a mix...
KFrank
Hello Joe! Part of me wonders whether this is a good idea. You’re not able to train your network to make these predictions with confidence, so you want to fake it, and I wonder if this isn’t a little fishy. Having said that: I would have thought that tweaking the softmax temperature would he…
AlJazari
I am working on a simple architecture, LeNet, with the following architecture:class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 32, 3, 1) self.conv2 = nn.Conv2d(32, 64, 3, 1) self.dropout1 = nn.Dropout2d(0.25) self.dropout2 = nn.D...
KFrank
Hello Al! When you create new_model it doesn’t know about the detailed structure of your class Net. In particular, it doesn’t know about Net’s forward() function. (It does know about model.children()). So I don’t think any of the torch.nn.functional functions used in model (an instance of yo…
abhi8569
I am trying to train a model for image segmentation. I have 3 different class to segment whihc is denoted by [0,1,2] in the ground truth image. These are the output from different steps:Model Output : torch.Size([5, 3, 120, 160]) #batch,channel,height,width Argmax Output : torch.Size([5, 120, 160]) #check maximum along...
KFrank
Hi Abishek! I assume that criterion_seg is something you wrote yourself that basically forwards its arguments to F.cross_entropy(). You most likely should pass Model Output in place of x as the first argument of criterion_seg, and don’t use argmax() at all. This is (most likely) telling you …
fyy
this is my train.pyI use crosssentropy loss for my network ,outputssize is [4,2,224,224] where 4 means batchsize, 2 means channels, 224 means h and w .output_c1 size is [4,224,224] ,labels size is [4,224,224] too.import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from...
KFrank
Hello fyy! At this point, the best I can offer you is some general advice. First: Independent of u-net or pytorch or machine learning, you need to understand the problem you are trying to solve. You should look at the data you are working with. Print out some images and try to segment them …
abhi8569
I am using a custom model based on SegNet to do segmentation for 3 different objects. Model is returning a tensor of size “[5, 3, 120, 160] (batch size, channel, height, width)” and I have a label where each channel contain information of a particular object, something like this:[[ [1, 0, 0, 0], [1, 1, 0, ...
KFrank
Hello Abishek! I’m not sure that you’re describing what you are doing consistently. However, here are some comments based on some of the things you say. This is backwards. For CrossEntropyLoss you do not use a one-hot-encoded label vector. Rather, you use a single integer class label (per p…
Valiox
I realized I had a bug in my model with multiple optimizers, because some optimizers had overlapping param groups (I assume that is never supposed to happen).I’ve been debugging things around and I noticed this weird (somewhat unrelated) behaviour:Here I take one parameter from one optimizer:In[25]: optim.param_groups[...
KFrank
Hello Valiox! One possibility – this would depend on the details of what you’re doing – is that some optimizers have memory, e.g., SGD with momentum or Adam. Therefore, even though the current gradient is zero, the optimizer might be remembering previous steps with a non-zero gradient, and th…
Yolkandwhite
Hi I’ve been struggling so long time doing Image segmentation.specifically I want to get predicted brain cancer mask out of brain MRIs and Brain cancer masks image file.brain MRI has shape of 1x3x256x256(RGB) and mask has shape of 1x1x256x256(Black and white).At first I tried to use nn.CrossEntropyLoss(), It failed may...
KFrank
Hello Yoonho - Let me try to answer part of your question. (I haven’t looked at your dataloader or model code, so I won’t comment on it.) Let me try to give you some general context here. The shape of your input doesn’t really matter to your loss function – it just has to match what your mode…
ppmt
I am trying to train a binary classifier with Pytorch v1.3.1 on time series data using a LSTM with CrossEntropyLoss as loss function. Since the dataset is very unbalanced (~98% Class 0, ~2% Class 1), I want to apply weights [1., 55.] in the loss function. The training is done in batches of 24. Using a random example, w...
KFrank
Hello Peppermint! Actually, everything looks good here. According to my calculator, 24* 0.7963 = 19.1112. (As an aside, 24 * 0.79 = 18.96.) Yes. CrossEntropyLoss computes a weighted average using your weights. In your example, you have 23 weights of value 1, and 1 weight of value 55. So …
theairbend3r
My laptop automatically shuts without warning (sometimes) during training.Machine config -Lenovo y540,RTX 2060,Ubuntu 18.04,PyTorch 1.4. I tried training a simple binary image classification model (4 conv layers with batchnorm and Dropout). The model trained for 20 epochs (batch size = 8) and then my laptop shut down.O...
KFrank
Hello Mr. Air! Your laptop is overheating and shutting itself down to prevent permanent damage. When your cpu and/or gpu is running full tilt – and pytorch tries to make it run as fast as it can – that creates a lot of heat. (So pytorch is doing its job here!) Some things you can try: Make…
ykukkim
Hey all,I am trying to utilise BCELoss with weights, but I am struggling to understand. I currently am using LSTM model to detect an event in time-series data. My output from the model and true_output are as follows[batch_size, seq_length].Currently, I think I have managed to do hard code it but it’s not the best way ...
KFrank
Hello Yong Kuk! The most straightforward way to do this (and also better for numerical reasons) is to adjust your network so that it outputs raw-score logits for its predictions, rather than probabilities. (For example, if the last layer of your network is a Sigmoid – that converts a logit to …
Ameen_Ali
hello,Given a tensor of shape Original = [A , B , C]I want to build a list of tensors (target) in the following way:the first element (a) = Original.the second element (b), b = same as Original but the tensors are shifted by 1, meaning b[0 , : , :] = a[1 , : , : ]the third element ©, c = same data as Origial but the t...
KFrank
Hi Ameen! Doestorch.roll()do part of what you want? Best. K. Frank
amity137
Hey folks, have been haunted by this for some time. Now have an isolated repro. c1 and c2 below should be absolutely equal below but that’s not the case. Can anyone please explain why? The behavior is same on CPU and GPU.import torch d1=10 d2=2 d3=50 d4=150 torch.set_printoptions(20) e=torch.rand((d1,d2,d3)) f=torch...
KFrank
Hi Amity! Yes, this is true (for any reasonable definition of “do a series of flops in the same order,” and excluding perverse hardware implementations). Consider this: Mathematically, addition is commutative, i.e. x + y = y + x. It is also associative: x + (y + z) = (x + y) + z. Floating-po…
Bendrien
Hello there.First of all, im having a great time playing around with PyTorch - thanks for thatNow to my question.Im building a CNN for sequential data usingCrossEntropyLoss. I have 3 classes as output of which two are of interest and the last is used if one of the two wasnt a fitt:Class 0: no fittClass 1: interest 1Cla...
KFrank
Hello Anyere! Unless there is something unusual about your classification problem, I think you should not use ignore_index for Class 0. Suppose you feed a Class-0 sample to your model (so target is 0), and your model incorrectly classifies it as Class 2. You do want to tell your model not to …
A_A
Hello,I need to have following operation:y[i] = w * \sum_{j=1}^{i} x[j] + x[i]Which is equivalent to torch.cumsum() if w := 1. However, in cases where we need to decay the summation by having 0 < w < 1, cumsum() won’t work. Any suggestions about how to go ahead in solving this problem?Thanks,Ahmed
KFrank
Hello Ahmed! As written, this doesn’t actually have a decay factor. (Each value of y only has at most a single power of w.) I think you mean to write something like y[i] = w * y[i - 1] + x[i] You can get what (I think) you want by pre-multiplying x with powers of the weight, and then using c…
flyaway
I have a matrix M in size of n*d, where n is the number of vectors and d is the dimension of each vector. Now, I want to find the closest pair of this n vectors. Be note, I only need the closest pair.I have two ways of doing this:Use thePairwiseDistanceandargminfunction. However, this method uses too much memory. Half ...
KFrank
Hi Fly! In practice, for reasonable values of n and d, I expect that pdist will do about as well as you can. However, the so-called computational cost of your pdist solution is a suboptimal O(d * n^2). If you search on closest-pair problem, you will see that your problem can be solved in O(d…
bing
I am solving a multi-class image segmentation problem.Classes are imbalanced.I am trying to calibrate weight parameter of nn.Cross_entropy() using the below weight -weights = torch.tensor([0.90,0.40,0.40,0.20]) criterion = torch.nn.CrossEntropyLoss(weights)Above number , I used were arbitrary.On calculating number of d...
KFrank
Hi Mr. Bing! There is no single right answer for choosing weights to reweight an unbalanced data set. But a good starting point is: weight_for_class = 1 / number_of_samples_in_class. The idea is that you might want each class to be making about the same overall contribution to the loss functi…
Yanhong_Zhao
data_transform = transforms.Compose([transforms.Resize((229,229)),transforms.RandomResizedCrop((229,229)),transforms.RandomHorizontalFlip(),transforms.ToTensor(),transforms.Normalize(mean=[unknown],std=[unknown])])In order to use Data Transforms like this on my own training set, I first need to calculate the mean and s...
KFrank
Hello Yanhong! It really doesn’t matter. There is nothing magic about normalizing your data to get exactly some mean and standard deviation – you just want to get the general scale of your data to be sensible. Unless there is something perniciously weird about your data, the augmentation you …
hash-ir
I have a classification problem where each sample output consists of four values each of which is one of the 6 classes, i.eyhas shape(batchsize, 4). So far, I have created a toy model which outputs a logits tensorouthaving the shape(batchsize, 6(=num_classes), 4). I am calculating the loss for each of the target value ...
KFrank
Hi Hashir! If I understand what you are trying to do here (and I am not at all sure that I do), thentorch.nn.CrossEntropyLossshould do what you want without further manipulation. (Look at the parts where the documentation talks about the “K-dimensional case.”) Let the output of your model b…
raouf_ks
hello everyone ,I’m coding the dropout as a variational inference as [ Gal et al 2016 ] explain itI have a problem regarding “BCE With Logits Loss”My simple neural net isdef __init__(self, hidden_size, input_size=1, dropout_p=0.25 ): super().__init__() self.dropout_p = dropout_p self.hi...
KFrank
Hi Raouf! I don’t follow in detail what you are doing, but be aware that the output of a model with a final sigmoid() layer will, of course, be different than the output of the analogous model that lacks that layer. With the sigmoid() layer your model returns probabilities. Without the sigmoid…
hunar
i following the facenet in timesler , there is a lineworkers = 0 if os.name == ‘nt’ else 8whatos.name ==‘nt’meaning
KFrank
Hello Namo! It means that the operating system (“os”) is a microsoft operating system of the NT lineage, such as windows 10 or windows 7 (or windows NT), as distinct from the older dos and semi-dos windows systems such as windows 3.1 or windows 95 (and also distinct from other operating syste…
Raphikowski
Dear all,I am trying to do the following: Given I have some column vector of shape (5 x 1) I want to calculate the inverse of (q @ q.t()). This actually shouldn’t be such a difficult task, however, it seems that the inverse of this expression, torch.inverse(q @ q.t()) is way off:In [358]: q = torch.randn(5,1) ...
KFrank
Hi Raphikowski! Yes, your suspicion is correct. By construction, your matrix is mathematically non-invertible. (Numerically, it is likely technically invertible, but singular within round-off error, so you get nonsense results when you try to invert it numerically.) Your matrix – by construct…
MrRobot
QuestionThe key difference ofnn.CrossEntropyLoss()andnn.BCEWithLogitsLoss()is the former uses Softmax while the latter uses multiple Sigmoid when computing loss. I have confusion about thisDoes usingnn.BCEWithLogitsLoss()and setting a threshold (say 0.5)implicitlyassume we are doing multi-label classification?If it is ...
KFrank
Hello Mr. Robot! I’ve haven’t done the experiment, but I very much expect that if you train a network on reasonably clean multi-class data (say, MNIST digits) with both CrossEntropyLoss and BCEWithLogitsLoss you will get better performance using CrossEntropyLoss. It’s worth saying a few words…
titoniubo
I’d like to prepare variables to run a multi class classification.Note I try replicating the model shown in thispost, where@Oli,@tymokvo,@god_sp33dand@Rojincontributed.I have 10 variables split as (X_train,X_test) and 1 target variable split as (Y_train, Y_test).My target/label is a 3 class (1,2,3)I thought I would pre...
KFrank
Hi Josep! First, could you clarify what version of pytorch you are using? What type of data structure are your X_train, Y_train, etc., before you wrap them in numpy arrays? Just to clean things up a little, I would (try to) convert directly from your original X_train, etc., to pytorch tensors…
titoniubo
Hello,My question is regarding theinput sizeof the classification/regression when we use n columns instead of images.Let’s say I have a classification problem, for which I have 20 numerical variables (500 raws each) and 1 label with 5 possible classes. I understand the output size is 5.However, I do not know what is th...
KFrank
Hi Josep! I’m not sure what you are trying to do here. First, you need to package your input data as a pytorch tensor. (That’s what pytorch works with.) You need a batch size. It can be 1, if you want to work with a single sample, but let’s say you use a batch size of 7. Then a single batch …
chunchun
Just as the title, I must use the result of softmax,then I want to use a loss.I found that NLLLoss must be after log_softmax,if I just compute a log for the result of softmax,is that right?As for nn.CrossEntropyLoss(),there can’t be a softmax.Could you please tell me which loss should I choose?
KFrank
Hello Chunchun! In general, there is no particular need to use probabilities to feed into your loss function. If your use case requires probabilities for some other reason, perhaps you could explain why you need them and what you need to use them for. For training, you should use (based on w…
Alex_Luya
Hello,I haveoutputs like [B,C,H,W]andtargets like [B,H,W] ,where each pixel may be the one of [0,1,2,3,4] for background+4 classesand BCEWithLogitsLoss(outputs,targets) gives meValueError: Target size (torch.Size([32, 224, 416])) must be the same as input size (torch.Size([32, 4, 224, 416]))Is one-hot encoding target t...
KFrank
Hello Alex! You say in your title “multiclass+multilabel,” but you say in your post itself “where each pixel may be the one of [0,1,2,3,4].” To clarify the terminology: Yes, I would call this “multiclass” because you have five different classes (one background plus four non-background). (If y…
Leon_Lang
Hello,class Subspace_model(nn.Module): """ Wraps a model in order to train it in a subspace """ def __init__(self, model, E): super(Subspace_model, self).__init__() self.model = model self.register_buffer("E", E) self.d_dim = E.shape[1] self.params_d = nn.Paramete...
KFrank
Hi Leon! I don’t really follow your embedding scheme, and I can’t comment on your code. But if I understand goal correctly, perhaps you can project your gradients onto your desired subspace after an unmodified backward() step. The common optimizers use some variant of gradient descent where p…
VikasRajashekar
I have a classifier that has to predict whether a given sentence is positive or negative or Neutral.This is my forward pass:Sentiment_LSTM( (embedding): Embedding(19612, 400) (lstm): LSTM(400, 512, num_layers=2, batch_first=True, dropout=0.5) (dropout): Dropout(p=0.5, inplace=False) (fc): Linear(in_features=512...
KFrank
Hi Vikas! Yes. Your output, the first argument to CrossEntropyLoss, being the output of your linear layer, are triples of values that range from -infinity to infinity, and can be understood as logits (in contrast to probabilities, that would range from zero to one). Your labels are single va…
cclover
Hello,everyone.out = net(input) Target = Variable(t.arange(0,10)) Criterion = nn.MSELoss() Loss = Criterion(out,Target) Print(Loss)when i run it ,which give me a mistake.image1130×566 13.7 KBAnd i know how to correct it ,just replace Target = Variable(t.arange(0,10)) with Target = Variable(t.arange(0,10)).float()why fl...
KFrank
Hello Clover! There are two things going on: First, many pytorch tensor functions that act on two (or more) tensors require the tensors to be of the same type. So MSELoss() doesn’t want you to mix tensors of differing types. Second, many pytorch tensor functions require arguments of specific…
Maria_Fernanda_De_La
I want to get the two highest values from a number. I am thinking of getting the max, removing it, and then get the max again. Does anyone have a link to the code implementation for this function?Thank you in advance
KFrank
Hi Maria! Doestorch.topk()do what you want? I would expect it to be the most efficient approach. Good luck. K. Frank
Umang_Sharma
I am working on a network that uses a LSTM along with MDNs to predict some distributions. The loss function I use for these MDNs involve trying to fit my target data to the predicted distributions. I am trying to compute the log-sum-exp for the log_probs of these target data to compute the loss. When I use standard log...
KFrank
Hi Umang! I haven’t checked your weighted, stable log-sum-exp implementation carefully, but, at first glance, it looks correct to me. If your issues really do show up first with probs = m.log_prob(target), then your log_sum_exp() is likely not the problem. Note that the log in log_prob() itse…
Mainul
Regarding binary Classification, I have two question,Lets say, I only care about one class, If my model gives one output (using sigmoid) rather than two (using softmax), will it be a better idea. If so, could you please explain the reason?For one output, what loss function should I use? It seems that the PyTorch implem...
KFrank
Hi Mainul! It will be better to use a single output for a binary-classification problem, rather than two (which you could logically do). By doing so you eliminate one redundancy, and the parameters that go along with it, from your network. This will provide at least a modest advantage. The…
Mehran_Ziadloo
The cross-entropy loss function intorch.nn.CrossEntropyLosstakes in inputs of shape(N, C)and targets of shape(N). This means that targets are one integer per sample showing the index that needs to be selected by the trained model.In my case, I’ve already got my target formatted as a one-hot-vector. And also, the output...
KFrank
Hi Mehran! Let me draw a distinction between two different problems. When I say “multiclass” I mean more than two classes, that is, not binary. (So, for example, classes A, B, C, and D, rather than just “yes” or “no.”) But each sample is of exactly one of the classes. When I say “multilabel”…
blackbirdbarber
Here is the code I have:import torch import torch.nn as nn import torch.nn.functional as F from torchvision import transforms from torch.utils.data import DataLoader, Dataset, TensorDataset bs=1 from torchvision.models import resnet18 model = resnet18(pretrained=False) optimizer = torch.optim.SGD(model.parameters(), l...
KFrank
Hi Barber! I assume that by “got this error” you mean the error message in your post title, “Expected object of scalar type Long but got scalar type Float.” This was to be expected. CrossEntropyLoss takes integer class labels for its target, specifically of type LongTensor. In your code you …
ArmanMazdaee
Hi,I’m trying to implement a music transcription system. Each of the labels has a shape of [88 x num_frames]. Each element represents the activation of the corresponding piano key on the corresponding frame. So the problem can be considered a binary classification problem. For making a batch each label gets pads with z...
KFrank
Hello Arman! The function version ofbinary_cross_entropy(as distinct from the class (function object) version,BCELoss), supports a fine-grained, per-individual-element-of-each-sample weight argument. So, using this, you could weight the loss contribution of each frame separately, and, in pa…
SU801T
Hi All,I have a 4 dimensional numpy input array that was created from extracting features using ResNet50.With a batch size of 5, I have created tensors of:torch.Size([5, 2048, 1, 1])I’m not really sure what to do if I want to feed this into a simple autoencoder. Would anyone be able to clarify how I should reshape this...
KFrank
Hi Taran! I assume that your problem is the last two length-1 dimensions of your tensor. If so, you can usetorch.squeeze()to get rid of them. You could then feed your (now torch.Size([5, 2048])) tensor to, for example, a nn.Linear (2048, 256) layer. (Note, if you ever have a batch size of …
l4zyf9x
Hi all, I have tensor 2D data.size=[4,8]. For each row in data, i want create a mask from begin_index to end_index, eg:pair_index = torch.LongTensor([[0,2],[2,7],[1,3],[0,5]]) tensor([[0, 2], [2, 7], [1, 3], [0, 5]])So my expected mask output will be:tensor([[1, 1, 0, 0, 0, 0, 0, 0], [0,...
KFrank
Hello Trinh! There might be a cleaner way, but here’s the best I could do: import torch print (torch.__version__) pair_index = torch.LongTensor([[0,2],[2,7],[1,3],[0,5]]) cols = torch.LongTensor (range (8)).repeat (4, 1) beg = pair_index[:,0].unsqueeze (1).repeat (1, 8) end = pair_index[:,1].unsq…
aszmul
Hello Everyone,I am facing a problem of semantic segmentation of 2D data. I would like to apply 5 classes.The dataset is sparsely labelled, in each image just a small portion of it is labelled, usually with just one class. It is common that in the same image more regions should have that label, and other parts of the i...
KFrank
Hello Adam! Let me speak as if you have images that are labelled on a per-pixel basis, and that have only a small fraction of their pixels actually labelled. Each pixel is either unlabelled, or is labelled with one of five classes. (My comments apply more generally to unlabelled / labelled da…
anxu
Hi, I am using the floor function and found this strange behavior:a=torch.tensor(1-5.9605e-8)a.floor()=>tensor(0.)(a+1).floor()=>tensor(2.)How is floor computed and why does not (a+1).floor() output 1.0?
KFrank
Hello An! I haven’t checked the arithmetic precisely, but I believe the following is going on: A torch.tensor by default uses single-precision (32-bit) floating point numbers. These have approximately 7 decimal places of precision. Your small number, 5.9e-8, is (relative to 1) just on the e…
mese79
HiI have a simple binary classifier model, but I didn’t useSigmoidat the end so I’ve trained my model withBCEWithLogitsLosscriterion.My targets(true labels) is created based on a value likeif value >= 0then target is1else0.The question is in testing what should I set as threshold?0.5or0.0?
KFrank
Hi Mehdi! You should use 0.0 as your threshold for class “1”. Here are the details: A logit is a sort of score that runs from -infinity to +infinity. When you run it through the sigmoid function, you get a probability that runs from 0 to 1. (BCEWithLogitsLoss has, in effect, a sigmoid functio…
Dementiy
Hello, everyone. I can’t understand why is softplus backward pass not equal to sigmoid?>>> x = torch.tensor(np.array([ [-0.4578739 , -0.57322363, -0.85933977], [ 0.9095323 , 0.78346789, 0.47258139], [-0.54425339, -0.92374175, -0.56345292] ]), requires_grad=True) >>> out = torch.nn.Softplus()(x) >>> out.ba...
KFrank
Hi Dmitriy! You are perfectly correct that the derivative of softplus is sigmoid, and that calling backward() should give you this derivative as the gradient with respect to x. Your problem is that, for comparison, you are not calculating sigmoid (x) (but, rather, sigmoid (out)). Here is a (p…
ruian1
Hi Pytorch Community! I was using BCEWithLogintsLoss to train a multi-label network and getting negative loss as shown below. As mentioned in the class documentation, this loss function combines sigmoid and BCELoss…But actually as it shows. I also checked its definition in pytorch/torch/nn/functional.py and I was not a...
KFrank
Hello Rui An! It appears that you have switched the order of your inputs to BCEWithLogitsLoss. BCEWithLogitsLoss (like binary_cross_entropy_with_logits()) expects to be called with predictions that are logits (-infinity to infinity) and targets that are probabilities (0 to 1), in that order. …
phdproblems
Hi,There have been previous discussions on weighted BCELoss here but none of them give a clear answer how to actually apply the weight tensor and what will it contain?I’m doing binary segmentation where the output is either foreground or background (1 and 0). But my dataset is highly imbalanced and there is way more ba...
KFrank
Hi phdproblems! Let me add some hypothetical context to your question to make it more concrete: As you say, you have a batch size of one. Each batch tensor is of torch.Size([1, 1, 60, 40, 40]), so each sample is of torch.Size([1, 60, 40, 40]). Let me imagine that each sample represents, say,…
mnauf
I am working on a toy dataset to play with. I am trying to calculate loss via BCEWithLogitsLoss(), but loss is decreasing very slowly. And prediction giving by Neural network also is not correct.model = nn.Linear(1,1) input_tensor = th.tensor([[5.8],[6.0],[5.5],[4.5],[4.1],[3.5]],requires_grad=True) target_tensor = th....
KFrank
Hi Mnauf! I suspect that you are misunderstanding how to interpret the predictions made by this network. First, you are using, as you say, BCEWithLogitsLoss. Therefore you are training your predictions to be “logits.” These are “raw scores,” if you will, that are real numbers ranging from -i…
smonsays
While tinkering with theofficial code example for Variational Autoencoders, I experienced some unexpected behaviour with regard to the Binary Cross-Entropy loss. When I useF.binary_cross_entropyin combination with thesigmoidfunction, the model trains as expected on MNIST. However, when changing to theF.binary_cross_en...
KFrank
Hi Simon! Okay, this makes more sense. The input and target passed to binary_cross_entropy() are both supposed to be probabilities, that is, numbers between 0 and 1 (with singularities occurring at 0 and 1). Your target contains negative numbers, which are not valid probabilities. (Because y…
John_Deterious
I looked @https://pytorch.org/docs/stable/_modules/torch/nn/modules/loss.htmlAnd I failed to find what I wanted. I basically have multiclass problem, and the targets for each instance is a vector of soft classes.To be concrete:nueral net output [0.1, 0.5, 0.4]correct label [0.2, 0.4, 0.4]It should be standard in libra...
KFrank
Hello John! I believe that you are correct. As far as I am aware, all of the pre-packaged pytorch cross-entropy loss functions take class labels for their targets, rather than probability distributions across the classes. Looking at your numbers, it appears that both your predictions (neura…
Aww
Hello, I have a database of images where every image is represented by a number, eg. color entropy calculated for that image. I am trying to train a CNN by giving to the network an image and the corresponding number to it and I’m expecting after the train is done to have a CNN that will see an image and predict me a nu...
KFrank
Hi Public! Let’s say your images are 256x256 pixels, and each pixel is given by an rgb value made up of three 8-bit bytes. Therefore each image is given by 196608 numerical (8-bit) values. Convert these to floats. Because your example of color entropy doesn’t care about the structure of the…
sh0416
Hello,I am curious about the fft built-in function.Is this function calculate the DFT coefficient directly?What is the time complexity of fft function if we do not use GPU?Is this function use divide-and-conquer algorithm for calculating fft?Thanks,
KFrank
Hello 성현! It looks like the gradient is supported. Try: >>> import torch >>> t = torch.randn (1, 8, 2) >>> t.requires_grad = True >>> torch.fft (t, 1) tensor([[[-2.7232, 3.8741], [-2.9743, -2.1404], [ 1.1234, 4.4275], [ 1.7661, 1.6113], [-3.6401, 3.6872], …
hiepnguyen034
I was followingthis tutorialand was confused by the way we make final prediction. Let’s say the model is defined asloss_func = F.cross_entropy def get_model(): model = Mnist_Logistic() return model, optim.SGD(model.parameters(), lr=lr) model, opt = get_model() print(loss_func(model(xb), yb)) for epoch in ran...
KFrank
Hi Hiep! The short answer is that nn.functional.cross_entropy one-hots your class labels for you. The number-one rule is that the output of your network means whatever you train it to mean. More directly to your question: You are using nn.functional.cross_entropy as your loss function. Your…
n0obcoder
Let’s say i have to train an image classifier an a highly unbalanced dataset. Then I would like to penalize the losses belonging to the dominating classes less and vice versa !Can you pls show with a few lines of code how exactlyweightsin nn.BCEWithLogitsLossis passed ?Imagine we have a dataset in which we have three c...
KFrank
Hello Gurgaon! You are correct that the named weight argument is the way to provide class weights to nn.CrossEntropyLoss. But the weights you use in your example don’t make a lot of sense to me. The weights you give for classes B and C are not very different – they are 0.91 and 0.99, respecti…
Maria_Fernanda_De_La
I was looking through the documentation and I was not able to find the standard exponential loss function. Is there a simple way to implement my own exponential function.Thank you in advance!
KFrank
Hello Maria! Sure. And if you use normal tensor operations, autograd will work for you. Let’s say you have a binary classification problem and logits are your predictions for a batch (running from -infinity to +infinity) and labels are your known class labels for that batch (equal to 0 or 1)…
auyer
I am running a Transfer Learning scenario with a ResNet model. The original work was a classifier with hundreds of classes, and it used the CrossEntropyLoss functionnn.CrossEntropyLoss().Athreadhere suggest BCELoss, but there is BCEWithLogitsLoss that also seems fit.In a confusion matrix, I want to optimize for the lea...
KFrank
Hi Rafael! For a binary classification problem, BCEWithLogitsLoss should be your go-to loss function. (You would only want to use BCELoss if your network naturally emits probabilities, which it almost certainly doesn’t.) Consider carefully the trade-off that you are implying here. As an ex…
ljj7975
Based on my understanding of back prop and gradient descent,Loss is multiplied to gradient when taking a step with gradient descent.So when gradient becomes negative, gradient descent takes a step in the opposite direction.Such idea is well captured when implementing gradient ascent,as it can simply be implemented by m...
KFrank
Hello Brandon! This isn’t true. All common optimization algorithms I’m aware of – and in particular, gradient descent – only care about the gradient of the loss, and not the loss itself. Plain-vanilla gradient descent takes the following optimization step: new weights = old weights - lea…
Yuerno
Hey all! I’m working with a dataset for segmentation that has your typical RGB images as well as index-based masks (so the pixel values in the mask represent the classes at those positions), and I’m wondering what the best way to train this dataset would be with a simple U-Net. Would it be better to do standard CrossEn...
KFrank
Hello Yuerno - Conventional wisdom and common practice suggest that you should use CrossEntropyLoss for a multi-class classification problem. Reading between the lines, I understand your segmentation problem to be a straightforward (multi-label) classification problem, so I would think that C…
ljj7975
This idea comes to be randomly.One of the advantage of CNN is the fact that it captures the locality in the input space through receptive fields.If the input data does not have such relationship among features,Would DNN provide better results?Is there any previous study on this? I would like to take a look
KFrank
Hi Brandon! First, by “CNN” I assume you mean a “convolutional neural network,” that is, a network whose first few layers consist of convolutions. And by “naive DNN” I assume you mean a network consisting of fully-connected layers. Yes, your expectation is correct – a CNN will not work well …
smani
Capture836×369 35.6 KB
KFrank
Hello smani - First, could you please post text rather than screenshots? (It makes things searchable, lets screen readers work, etc.) If you need to post an equation that you can’t format adequately using the forum’s markdown, you could post a screenshot of that, but do then refer to and descr…
mahsa
I’m reading a code which has a class for Model and a class for Layer definition. The BaseClass of the Model is nn.Module and the BaseClass of Layer is Module from nn.modules.module. What is the difference?This is thelayer codeand this is themodel codeThanks
KFrank
Hi Mahsa! Thanks for the link to the layer code. That clears things up. Yes, the two Module classes are indeed one and the same. Look specifically at this line in layers.py from torch.nn.modules.module import Module So let me go back to a version of my first reply to you – there is a class t…
inquest
I am a newbe and i am stumped … probably simply because i am missing something obvious.Trying to show images of the kernels in a cnn layer.The following works fine:kernels = model.cnn1.weights.detach().clone().cpu().view(-1, 3, 3) #max = torch.max(kernels) #min = torch.min(kernels) #range = max - min #kernels = (kerne...
KFrank
Hi Marc! This is really a python issue – not specific to pytorch. range = max - min This line (when uncommented) sets range to (refer to) max - min, which, in this case, is a pytorch tensor. Then when you try to execute for j in range(16): range no longer refers to the built-in python “range…
Niki
I am looking for drawing krandombatches of 2 objects from test dataset, CIFAR10. Let’s say for batch_size=128, k=64, any ideas how can I do that?
KFrank
Hello Niki! Here are ways to draw two different kinds of random batches. Let nTest be the total number of test data items you have. I will assume that nTest > 2 * k (because this will matter for one of the kinds of random batches). First (ba in the example code below) we can construct random …
NightMachinery
To profile the memory usage, I want to list all tensors with their name and size.I have a function that can show all tensors with their size:def pretty_size(size): """Pretty prints a torch.Size object""" assert isinstance(size, torch.Size) return " x ".join(map(str, size)) def dump_tensors(gpu_only=True):...
tom
Tensors don’t know their names, and they might not all have names. What you can do - at the expense of speed - if your tensors require gradients is to use the anomaly mode to get the lines of the instantiations: with torch.autograd.detect_anomaly(): a = torch.randn(5, 5, requires_grad=True) …
Sohrab_Samimi
Hi everyone,i am having some trouble with torch.einsum.Basically i am trying to mutliply two tensors in a certain way:first = torch.rand(12,8192,2) weights1 = torch.rand(12,8192,2) torch.einsum('bix,iox->box',first,weights1)But i get the following error:einsum() operands do not broadcast with remapped shapes [origina...
tom
Something is up with the i dimensions: in the first tensor it is 8192, in the second 12. I must admit the error message isn’t as clear as it could be, so I took the liberty to file an issue with your example:Clarity of error message in einsum regressed in performance improvements · Issue #58380 · …
LewsTherin
Hello! I want to fine-tune the I3D model for action recognition from torch hub, which is pre-trained on Kinetics 400 classes, on a custom dataset, where I have 4 possible output classes.I’m loading the model and modifying the last layer by:model = torch.hub.load("facebookresearch/pytorchvideo", "i3d_r50", pretrained=Tr...
tom
From the pooling + conv layers, CNNs typically have a minimum viable input size. The error says that an intermediate input is too small. This is because the inputs don’t meet I3D’s minimal input size, and it seems to be that the third (T) dimension is the problem. Best regards Thomas
BearBiscuit05
When performing the prefix sum operation, it appears that there is an abnormal time overhead. Subsequent operations on the calculated results of the prefix sum incur significantly high additional time costs. I am unsure about the reason of this thing and how to resolve the issue.code:binAns = torch.bincount(dstList) cu...
tom
You want to call torch.cuda.synchronize() before all timetaking in order to have the GPU finish all queued work. The print (or .cpu(), .item(), .tolist()) does implicitly do such a sync. Python’s documentation suggests using time.perf_counter() instead of time.time() for benchmarking. Best regards …
cokespace2
I create a empty tensor byat::Tensor tensor = at::empty({}, options.device(kCUDA).dtype(dtype));but thetensorhas attributes like:tensor.numel() == 1 // true tensor.data_ptr() == nullptr // falseand I tried withTensor tensor = at::Tensor().to(dtype).to(kCUDA);, which fails of a Runtime error: tensor does not have a devi...
tom
This is a scalar (and thus 1-element) tensor. As Piotr mentions, you would want to provide a size-0 dimension to get a 0 element tensor: at::Tensor tensor = at::empty({0}, options.device(kCUDA).dtype(dtype)); Best regards Thomas
alibharwani
Hi, I’m debugging why my project is unable to properly/send receive CUDA tensors on windows. I tried to create a minimal repro, but in the minimal repro I ended up getting a different bug. In my main project, the first batch that the producer process sends to the consumer is correct, and the rest are corrupted (all 0s)...
tom
At least in the documentation, CUDA Tensors cannot be sent (link below). I’m not entirely sure why you’re not getting an error, but I do believe that it’s an inherent (of Windows/CUDA rather than PyTorch) limitation. Best regards Thomashttps://pytorch.org/docs/stable/notes/windows.html#cuda-ipc-…
aatg
I have read several blog articles to get an idea of how CTCLoss works algorithmically, and the PyTorch documentation seems straightforward. All the examples I have seen online conform to my understanding, but I am having trouble getting it to work in practice. Here’s a minimal working example where the losses should be...
tom
A loss of inf (likelihood of 0) means the input sequence cannot produce the target. Here, you would need to predict at least 1-blank-1-blank-1, which needs T>=5. Best regards Thomas
kgblitz
We can install pytorch’s CPU version viapip install torch==2.1.1 --index-url https://download.pytorch.org/whl/cpu.How can I add this to requirements.txt so I can install CPU version of it usingpip install -r requirements.txt?
tom
This is more Python than PyTorch, but you can either use --index-url (but this is global, so a bit tricky for requirements.txt) or give specific packages (whl archives) with @. Best regards Thomas Here are the details:https://pip.pypa.io/en/stable/reference/requirements-file-format/
nahso
I created a c++ function and registered it as follow:void to_csr_index(torch::Tensor &row_ptr, const torch::Tensor &edge_index_i, int64_t num_rows) { auto *prow_ptr = row_ptr.data_ptr<int32_t>(); for (uint32_t i = 0; i < edge_index_i.size(0); ++i) { prow_ptr[edge_index_i[i].item<int32_t>() + 1]++; }...
tom
The problem is not that the int64_t parameter, but that you pass a int64 tensor row_ptr and/or edge_index_i and then access it with the incompatible .data_ptr<int32_t>() and .item<int32_t>(). Either cast the tensors to torch.int32 aka torch.int or use int64_t in the template parameter. Best regard…