user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
Joe_Lorentz
Hello,I am currently playing around with using class weights in the cce loss and noticed that I get different results from using the reduction “mean” between using one-hot encoded targets vs a sparse label tensor.It seems to me that the class weights are not used in case of mean reduction and label targets.Please check...
KFrank
Hi Joe! This is not exactly true – both cases use the class weights, but use them a little differently. (But your basic observation that the two approaches give different results is correct.) The missing piece is that the two approaches compute the weighted mean in reduction = mean somewhat …
Omnia_Al-wazzan
Hi all!I have a question regarding Softmax.suppose I have two tensors with a batch size like thisimport torch import torch.nn.functional as F A = torch.Tensor([[1] ,[2] ,[3]]).float()[None] , # tensor shape >> (1,3,1) B = torch.Tensor([[5], [2], [6]]...
KFrank
Hi Omnia! This is to be expected. softmax() converts “unnormalized” log-probabilities to probabilities, and in the process normalizes them. That is why softmax() can map different inputs to the same outputs. Consider: >>> import torch >>> torch.__version__ '2.0.0' >>> t1 = torch.arange (5.) >…
quang
I have to real-valued matrix matrices A and B with shape (m,n) and (n,p) respectively and a pre-defined constant K. The goal is to calculate the new “topk multiplication” function, where entry (i,j) in the output is calculated as follows:Perform element-wise multiplication between the i-th row of A and the j-th column ...
KFrank
Hi Quang! If you align the indices correctly and use broadcasting, you can replace the loops with a single element-wise tensor multiplication: >>> import torch >>> print (torch.__version__) 2.0.0 >>> >>> _ = torch.manual_seed (2023) >>> >>> a = torch.rand(2,3,5) >>> b = torch.rand(2,5,2) >>> K =…
Jun_Park
I’m trying to stack GRUCell but got an error as above. I didn’t use GRU because the input for each sequence comes from the output (actually, modification of ) previous sequence.class Stacked_GRU_Cells(nn.Module): def __init__(self, input_size, hidden_size): super(Stacked_GRU_Cells, self).__init__() ...
KFrank
Hi Jun! Assigning into a tensor using indexing is an inplace operation, and this is likely the cause of your error. Try replacing the code I quoted with h_0 = self.gru_0(x, h_in[0]) h_out = torch.stack (h_0, self.gru_1(h_0, h_in[1]) If that doesn’t fix your problem, take a look at this post th…
rao
Hi,New here. This may be silly but I am unsure about the default value of requires_grad for parameters of a nn object.For example:linear = nn.Linear(10,10) linear.train() for params in linear.parameters(): print('requires_grad of parameters -',params.data.requires_grad) print('requires_grad of output of layer -...
KFrank
Hi Rao! Get rid of .data and try params.requires_grad. .data has been deprecated for quite some time and can break things so you shouldn’t be using it. (.data, in effect, digs, the raw – without requires_grad = True – tensor out of its wrapper tensor that carries requires_grad = True.) Best. …
sus
I’m trying to write a PyTorch Function for some black box function we’ll call f(x,y,z), where x,y,z are vectors of varying length and f returns a vector of length 4. I’m confused on the dimensions that I should be returning for the backward function. For example’s sake, we’ll say that x is a tensor with a single dimens...
KFrank
Hi Sus! In short, your backward function should return a tuple of tensors that individually have the same shapes as the tensors input to your custom (forward) function. Quoting fromExtending torch.autograd:backward() (or vjp()) defines the gradient formula. … It should return as many tens…
jimjimjimjimjimjimji
I want to reproduce on two different platforms. I fixed the random seed with the following code:def FixedSeed(seed: int = 1122) -> None: random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(se...
KFrank
Hi Jim! This is to be expected. Pytorch does not offer any assurance that computations will be exactly reproducible across platforms. As long as your results agree within reasonable round-off error (say, after a single forward and backward pass – deviations may accumulate if you train for man…
vadimkantorov
Hi!Is it possible in vanilla eager PyTorch (without Inductor) to express the following inplace without allocating the output ofx < 0.5?:x = torch.empty(1000).uniform_(-10, 10) y = torch.where(x < -1.5, 0, x, out = x)torch.clamp, torch.hardswish, torch.hardtanh don’t cut it in an easy way
KFrank
Hi Vadim! Use: torch.nn.functional.threshold (x, -1.5, 0.0, inplace = True) Best. K. Frank
Cyber_punk
The following is my loss curve. It includes the training batch loss and validation loss.image1002×619 29.2 KBI also checked the F1 Score and AUROC on the validation data. Both of them seems performing well:image953×558 29.2 KBHowever I’m confused about two things:(1) Both training loss and validation loss are decreasin...
KFrank
Hi Cyber! This is not overfitting (by my definition) and the general structure of your results does not surprise me. Your validation loss continues to decrease (albeit slowly) and your validation performance metrics continue to increase. So (as long as your are happy investing in further trai…
Cyber_punk
I’m using a Transformer encoder with a binary cross entropy loss for CTR prediction. The training batch loss is at around 0.693 constantly for the beginning several thousand steps (batches). I’m using Noam learning rate schedule and ascaling factorfor setting the learning rate used by Adam. The first 3000 steps are the...
KFrank
Hi Cyber! Okay, this makes good sense. The initial value and early values of your loss are not “almost exactly” log (2), but an amount away that is consistent with the size of the initial value of Linear (256, 1).bias, which itself is more or less the value of the initial predicted logit. Not…
WhaleFallOf52Hz
Meet the error while trying function backward() in IRM.RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [500, 1]], which is output 0 of AsStridedBackward0, is at version 2; expected version 1 instead. Hint: the backtrace further above shows...
KFrank
Hi Whale! This use of retain_graph = True is likely the immediate cause of your problem. This occurs within the loop over batches within an epoch. penalty accumulates the result of calculate_penalty(), so it depends not only on the current batch, but on previous batches as well. When you cal…
kfshr
I’m working on a project where I want to train a model to predict a sequence of tokens. For a given input sequence, the size of the output sequence can be between 1 and 4 tokens. As the size is variable, I use an “empty” token, here index 0, as padding.The following lists show four sequences of length 3, 1, 2, 4 padded...
KFrank
Hi kfshr! Sorry, I misread your original post. Just speculation: -100 looks sufficiently out of place as an integer categorical class label that one would likely suspect that it is some sort of sentinel value. You wouldn’t want to use, say, 17 or 99 or even 999 as a sentinel value as these c…
Brooklyn_Amaro
I am messing with my neural network code trying to make it as accurate as possible but I feel like my numbers are not looking right. I have plotted a Loss vs Epoch graph to find out the perfect number of epochs to use for my training loop but that graph doesn’t look right. The loss seems to be spiking every now and the...
KFrank
Hi Brooklyn! The short story is that your “Loss vs Epochs” graph is actually plotting the loss for each batch of the final epoch. To my eye, your “Loss vs Epochs” graph appears to contain eight points (even though the x-axis label goes up to 1400). Your code has a number of issues, but let’s …
dragonHyeon
Hello.I was training CycleGAN.When I train discriminator,case 1.loss_D_A.backward() loss_D_B.backward()case 2.loss_D = loss_D_A + loss_D_B loss_D.backward()Without thinking of retain_graph=True stuff, assuming this code doesn’t occur any error, are both case have same effects?My question is that for case 2., does loss ...
KFrank
Hi Hyeon! Yes, this is correct (with the proviso that you might need to use retain_graph = True in case 1). You can easily test that cases 1 and 2 produce the same gradients. Run case 1 and clone() the .grads of all of the parameters that affect either loss_D_A or loss_D_B for future compariso…
Brooklyn_Amaro
For my neural network I noticed that my predictions were coming out to be ‘nan’ in my training loop. To overcome this problem I have tried downgrading my PyTorch from 11.8 to 11.7 but that only changed the device from using cpu to gpu. I don’t know if this is a bug with PyTorch or if my code is just not working. Any ad...
KFrank
Hi Brooklyn! Check that your input data is free of nans. Try a single forward pass. Are the outputs of your network free of nans? Try a single backward pass. Are your gradients free of nans? Try a single optimization step. Are your model weights free of nans? If you pass these tests, your t…
David_Gomez
I’ve seen similar posts but their problem is different than mine and their solutions don’t seem to apply.I have 3 models: source_generator, target_generator and a classifier (discriminator). The generators are feature extractors that process images and output an embedding. Each generator is intended to process only ima...
KFrank
Hi David! There are a couple of different things going on here. Most importantly, it looks like you are training your target_generator backwards, see below. First,@ptrblck’s explanation of the inplace-modification error is almost certainly correct. discriminator_optimizer.step() pe…
yiftach
In the following toy example:import torch data = torch.randn(10, 1024) indices = torch.tensor([0, 1, 7, 0]) selected_data = data[indices]Is there a way to avoid a copy by havingselected_databe a view ofdataand share the same underlying storage?In my real case, as in this toy example, the indices inindicesmay have repea...
KFrank
Hi Yiftach! No, not with general index values. Pytorch tensors requires that their elements be stored contiguously (although you can “stride” through the contiguous elements), so when you index into a tensor you have to create a new contiguous tensor, rather than an indexed view into the origi…
Fei_Liu
E.g. I have this code snippetx = torch.rand(1000, 1000) # this will allocate a memory block of 4M in bytes x1 = x[0:1] # only selecting the first row. x1 itself contains only 1K floats, but for now it shares the underlying memory array with x torch.save(x1, 'some/disk/file') # after this, `some/disk/file` will be of...
KFrank
Hi Fei! Try some_tensor.untyped_storage() and some_tensor.data_ptr(). Best. K. Frank
jakelevi1996
I’m looking at 2 different ways of backpropagating through the log-probability of samples from a Gaussian RV WRT to its parameters:Withtorch.distributions.MultivariateNormalandtorch.diag_embedWithtorch.distributions.Normal, broadcasting and summing over the last dimension of the resultThe calculated log-probability is ...
KFrank
Hi Jake! When you instantiate d1, you pass MultivariateNormal the covariance matrix (the diagonal elements of which are variances) that defines your distribution. Normal, in contrast, takes the standard deviations (which are the square roots of the variances). Try: d1 = torch.distributions.M…
M_J
hi everyonecan we obtain the BCEWithLogitsLoss as weightingor it just BCE loss function combined with a sigmoid activation function?
KFrank
Hi M! No. They take different inputs – logits vs. probabilities – and you can’t compensate for that difference with weighting. Mathematically yes. In its numerical implementation, BCEWithLogitsLoss uses the (mathematically-equivalent) logsigmoid() instead of log (sigmoid()) for reasons of n…
hwaseem04
I am trying to implement balanced binary focal loss(Paper:[1708.02002v2] Focal Loss for Dense Object Detection) , where I need to give different weight (ratio of negative to negative class) based on each input tensor.So if I have batch size as 6, I would create a weight tensor of size 6 that is passed as below,loss_fn ...
KFrank
Hi Muhammad! You will not be able to backpropagate through the computation of ratio (for three reasons) – however, I expect that you don’t want to. Assuming that final_pred is the output of some properly differentiable model, you will be able to backpropagate through bce_criterion and final_pr…
hongkai-dai
I would like to use torch.autograd.grad to compute the Jacobian matrix for a batch of input.Say I have a functiony=f(x)whereyhas the same dimension asx. If I have a batch of inputx, denoted as x₁, x₂, …, xₙ, where the batch size isn, I want to compute the quantity∑ᵢ trace(∂f(xᵢ)/∂xᵢ)Namely for each n x n Jacobian matri...
KFrank
Hi Hongkai! y_flat is a function of x (as is y). However, y_flat is not a function of x_flat in the sense of the chain of computations recorded by pytorch’s computation graph. (Because x_flat is an invertible function of x, we can understand y_flat to be implicitly a function of x_flat, but a…
louisbzk
Hello,I am trying to train a model in the following fashion:# in a training loop, getting a batch x and a target y_true output = model(x) output_processed = process_output(output) loss = criterion(output_processed, y_true) loss.backward() optimizer.step()I am facing issues implementing theprocess_outputfunction. Some p...
KFrank
Hi Louis! Just implement process_output() using (differentiable) pytorch tensor functions and everything should work automatically. (Note, slicing counts as a differentiable tensor function.) As far as autograd and updating a model’s weights are concerned, there is nothing different about ten…
Jazzy66
Hi, guys, I am new of using torch and such error gets raised in a simple loop.To be concise, the loop aims to compute the gradient of a loss function, L, with respect to a vector, V, and update V till convergence. Here is a simple fake code helps to understand my problem.import torch import torch.nn.functional as F imp...
KFrank
Hi Jazzy! Yes, this is the cause of your problem. There are two things going on here: First, this line of code creates a new tensor (and then sets the name V to refer to it). You almost certainly don’t want this. Second, V_grad depends on (the original) V (as well as on I and U), and therefo…
Sascha_Frolich
I just came upon this:$ idx_long = torch.tensor(2).type('torch.LongTensor') $ idx_byte = torch.tensor(2).type('torch.ByteTensor')$ torch.eye(4)[idx_long,:] tensor([0., 0., 1., 0.])while$ torch.eye(4)[idx_byte,:] tensor([[[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]]...
KFrank
Hi Sascha! The short story is that indexing with a ByteTensor (dtype = torch.uint8) is (although deprecated) boolean indexing, which works differently than indexing with positional integer indices. Three things are going on: Your ByteTensor gets cast (at least in effect) to bool; boolean inde…
Moslem_Yazdanpanah1
How to set the Conv2d layer to convolve one common filter (one filter per kernel) over all input channels rather than creating one per each input channel?
KFrank
Hi Moslem! If I understand your use case correctly, you can reshape your input tensor to “move” the channels dimension into the batch dimension, pass it into a convolution with a single input channel, in_channels = 1, and then reshape the output to restore the initial batch dimension. Somethin…
CallMeMisterOwl
Hi there.I currently have following setup:nn.Conv1d(IN_SIZE, IN_SIZE, WING * 2 + 1, padding=WING, groups=IN_SIZE)Now I want to implement something I coined partially dilated convolution, in essence I want a convolutional layer that has a “dense island” in the middle. Something like this, where 0: represents a gap due t...
KFrank
Hi Mister Owl! I wasn’t imagining doing anything with the gradients (like masking them after they’ve been computed). Maybe you could make such a scheme work, but it would seem quite roundabout to me. I was suggesting encoding, say, the “left wing” in a trainable parameter, torch.tensor ([a, b…
Yashika
I’m noticing that initializing any random model, and not using that random model anywhere further in the code, is causing variations in the loss and AUC as compared to not initializing that random model.For instance, in the below code snippet, just initializing the unused auxiliary modelmodel_auxis causing variations i...
KFrank
Hi Yashika! Almost certainly you are using some sort of randomization in your training and initializing model_aux is consuming some random numbers, putting your training at a different point in the (pseudo)random-number stream. I know you said that you’ve set shuffle = False, but there could be…
xinbai
I have built an LSTM net work.But I find when the model is doing prediction,the same tensor data has different outputs.For example, when the output of the last hidden layer istensor([[0.0150], [0.0150], [0.0150], [0.0150], [0.0151], [0.0151], [0.0151], [0.0151], ...
KFrank
Hi Xinbai! The values you think are the same are almost certainly different. By default, pytorch prints out tensors with four digits, while a float has about seven or eight digits of precision. Try torch.set_printoptions (precision = 8) and then print out your tensors. Best. K. Frank
ArchieGertsman
The following example does not result in an autograd error:lin = nn.Linear(2,2) y = lin(torch.rand(2)) y[1] = 0 # in-place operation y.sum().backward()I’m just curious, how come this works? When, in general, do in-place operations not interfere with autograd? Thanks!
KFrank
Hi Archie! Here is a post with some examples that illustrate when inplace operations will and won’t break autograd: Best. K. Frank
Sam-gege
Hi, the following piece of code:import torch x=torch.tensor([-1.2, 0.6], requires_grad=True) y=1+x y[0]=torch.abs(y[0]) y.sum().backward()gives error that says:RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor []], which is output 0 of AsStr...
KFrank
Hi Sam (and Suho)! This requires a few words of explanation. The short story is that abs() requires an unmodified copy of its input tensor in order to compute its gradient during backward() (as does abs_()). abs() relies on its input still being available in unmodified form during backward, w…
Mohamed_Farag
I started to learn aboutpytorch lately after usingtensorflowfor almost 1 year, i am confused about something:InTensorflowwhen we have multiclassification problem we set at the last activation layer the number of classes and thetype of activation function which is "Softmax" and using“Cross-entropy loss”so inPytorchwhen ...
KFrank
Hi Dwight and Mohamed! I would like to offer two clarifications: If by “predicting values” you mean predicting class labels, this is not true. To get a predicted class label from the probabilities returned by softamx() you take argmax(). But softmax() does not change the order of the values,…
KAISER1997
I have a 3-dimentional pytorch array (rows x Column x K) .Lets name the array as ‘X’. I have a list of tuples , ‘L’ . For every tuple (a,b) in ‘L’, I want to swap the values at X[a,b,a] and X[a,b,b]. Is there a fast pytorch operation for this?(Here rows=Column=K)
KFrank
Hi Kaiser! You may use pytorch tensor indexing to both access and set the values of the desired elements, together with a helper tensor to temporarily store the values being swapped: Thus: >>> import torch >>> print (torch.__version__) 1.13.1 >>> >>> _ = torch.manual_seed (2023) >>> >>> K = 10…
shrbrh
I have the following Discriminator class for my GAN model:class Discriminator(nn.Module): def __init__(self, image_size, conv_dim, output_dim, repeat_num): super(Discriminator, self).__init__() layers = [] layers.append(nn.Conv2d(3, conv_dim, kernel_size=4, stride=2, padding=1)) layers.append(nn.LeakyReLU(0.01...
KFrank
Hi shrbrh! This is your problem. This line of code instantiates (creates an instance of) Discriminator (but is being called with invalid initialization arguments). You don’t want to define dLoss() inside of (as a method of) Discriminator. (Note, dLoss() never uses the self argument you pass it…
core-not-dumped
I made a simple model like below. It seems weird but it has one convolutional layer and two maxpooling layer.class simple_model(nn.Module): def __init__(self): super(simple_model, self).__init__() self.maxpool2D = nn.MaxPool2d(kernel_size=2, stride=2, padding=0) self.conv1 = nn.Conv2d(3,...
KFrank
Hi Core! My speculation (assuming that built-in pytorch functions work the same way as docustom autograd functions): Because MaxPool2D downsamples, it loses some information about the shape of its input. When its static backward() method is called, the only thing it knows is grad_output (and…
kpullela10
I’m a high schooler who’s (very!) new to machine learning and PyTorch, so I’ve been trying to build a DCGAN following the PyTorch official tutorial to replicate samples of melanoma lesions from the SIIM-ISIC Melanoma Classification dataset. However, I keep getting this error when trying to compute my discriminator loss...
KFrank
Hi kpullela! 14400 is 64 * 15**2, so I expect that your discriminator is returning batches of “images” of shape [nBatch = 64, nChannels = 1, H = 15, W = 15]. Your Discriminator is fully convolutional, so the height and width of its output will depend on the height and width of its input. Look…
qiminchen
Suppose I have a tensora, are there any pytorch (binary)erosionoperations that can give tensor likeb, so basically similar toscipy.ndimage.binary_erosionprint(a) tensor([[0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [1, 1, 1, 1,...
KFrank
Hi Qimin! If I understand your example tensors correctly, you want the following: If a pixel and its 4-connected (NSEW) pixels are all 1, the resulting pixel value should be 1 and 0 otherwise. Build a 3x3 convolution kernel with zeros in the corners and ones for the center and 4-connected entr…
rohil
Hi there,There have beenquestions in the pastthat reveal that under the hood, thecross_entropycalculation uses the natural log rather thanlog_2. I’m curious if anyone knows why that choice was made?On the one hand, the loss distributions are still similarly shaped, although they are now scaled slightly differently. On ...
KFrank
Hi Rohil! That is indeed the only difference. To get the log-2 version of cross entropy from pytorch’s cross entropy, multiply by 1 / log (2). This has almost no effect. For example, with plain-vanilla SGD as your optimizer, this rescaling can be absorbed into the learning rate. My guess w…
medvisioner
Suppose we have a neural network f_\theta(x), where x is the input and \theta is the network’s parameters.For each \theta, we can minimize f_\theta(x) w.r.t. x and obtain the minimum point x*(\theta):=argmin_x f_\theta(x).My question is: how to estimate the gradient: dx*(\theta) / d\theta ?I did some surveys and found ...
KFrank
Hi Med! First note that you haven’t converged to a minimum. Your first derivative, although smallish, is not zero. (Also your second derivative is relatively small, so if you were at a minimum, it would be pretty flat.) The formula I used for the gradient of argmin relies on x_star actually …
FrankiePoon
I would like to use a 1-Lipschitz continuous function as an activation function in my network, such as ReLU and LeakyReLU (with negative slop between 0 and 1).I also would like to use an activation function similar to PReLU with a learnable parameter while having the 1-Lipschitz continuous property. Are there any ways ...
KFrank
Hi Frankie! Probably the best way is to train an unbounded parameter, but transform it into a bounded prelu-weight with sigmoid(): >>> import torch >>> torch.__version__ '1.13.1' >>> _ = torch.manual_seed (2023) >>> wt = torch.randn (1, requires_grad = True) # learnable unbounded weight >>> wt…
Phungie
I am usingnn.CrossEntropyLoss()in as my optimizer in a model that I am developing. The problem that I am having is that the model outputs a vector of size(batchsize, #classes)when it is supposed to output a(batchsize)vector.Isn’tCrossEntropyLosssupposed to applyLogSoftmax?Here’s my Dataset:class DatasetPlus(Dataset): ...
KFrank
Hi Mohsen! Just to be clear about terminology, we would typically call CrossEntropyLoss your “loss criterion” or “loss function.” In your case, Adam is what we would call your “optimizer.” To confirm: CrossEntropyLoss does call LogSoftmax internally. This is your problem. CrossEntropyLoss …
TatianaACJ
Hi!I’m working on A2C algorithm for similar enviroments. A2C has learned the optimal solution for 2 error-free environments. But, while training some of the other environments the error is thrown:RuntimeError: one of the variables needed for gradient computation has been modified by inplace operation: [torch.LongTensor...
KFrank
Hi Tatiana! In the screenshot you posted, “line 198, in get_action” and “line 127, in log_prob” suggest to me that the action you pass to action.distribution.log_prob (action) gets modified (inplace) somewhere before the associated backward pass is performed. (As an aside, please don’t post scr…
Nyakov
Hi, I have binary classification model for detecting anomalies i data.The problem is, it outputs low probabilities (0.2 at maximum) when I expect from it to output 0.5 and more for related events.Events that I looking for is sparse so they appear rarely in train data. Can it be “unbalanced data” problem (I read somewhe...
KFrank
Hi Nyakov! Yes, it very well could be. If you train on a lot of negative samples and very few positive samples, your network can get trained to (almost) always predict “negative” without really “learning” anything about how your “negative” and “positive” samples differ and still get a low loss …
moth
Hello, I was wondering which is the expected shape of a mask for a multilabel image segmentation task. My guess is that each mask’s shape is(channels = num_classes, height, width), since a segmentation model will output a tensor with as many channels as classes, but i am not entirely sure. Here is an example of a model...
KFrank
Hi Moth! This is basically right with the proviso that the mask tensor you pass to your loss function should have shape [nBatch, num_classes, height, width]. Your batch size (nBatch) can be one, but the nBatch dimension is still required. Each element of your mask tensor will be a floating poi…
technick
Hello, I would appreciate if somebody could confirm that my understanding about autograd and inplace operations is correct and my code does not run into issues.I train a transformer model based on DETR. When I sample tensors from my dataset and do preprocessing, they have:requires_grad=FalseI do not change that field b...
KFrank
Hi Nick! Correct. Correct. But to clarify, you have a named “variable” in your python script that refers (as a python reference) to some tensor that autograd needs (and autograd also keeps its own reference to this tensor). You clone the tensor and your reference (the named “variable”) and …
sodlqnf123
A = torch.tensor([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) B = torch.tensor([[7,8,9],[4,5,6]]) some_function(A, B) -> torch.tensor([2, 1])What I want to do is that get indices of A based on each tensor of B.The reason why output is [2,1] is that each index of [7,8,9] is 2, and of [4,5,6] is 1.It looks quite simple, but is ...
KFrank
Hi Minhyuk! Try torch.where ((A == B.unsqueeze (1)).prod (dim = 2))[1]. Best. K. Frank
akshay_23
So I was going through the documentation of the cross entropy loss and I noticed that while taking the probabilities they have performed softmax , but softmax is internally performed again in cross entropy loss so confused why its is mentioned again in the Example of target with class probabilities>>> # Example of targ...
KFrank
Hi Akshay! When using CrossEntropyLoss with probabilistic (sometimes called “soft”) targets, the input (the predictions) are unnormalized log-probabilities, but the target are probabilities. Generating target by applying softmax() to a tensor is a convenient way to get legitimate probabilities…
Directorsim
Hello everybody,I have a video dataset. I extract one video image frame and extract on audio spectrum as image of the video. I have two main folders -one includes video image frames and the other contains audio spectrums of each videos-. Each two main folder have 8 subfolders - which are the classes.My model has two in...
KFrank
Hi Director! The short story is that concatenating feature vectors from your image frame and audio spectrum and then training a final classifier on the combined features is a reasonable approach. But I have concerns about using the same (pretrained) vgg16 on the audio spectrum as on the image …
Garry_Santana
class FocalLoss(nn.Module):def __init__(self, weight=None, gamma=2., reduction='none'): nn.Module.__init__(self) self.weight = weight self.gamma = gamma self.reduction = reduction def forward(self, input_tensor, target_tensor): target_tensor = torch.argmax(target_tensor ,axis=1) ...
KFrank
Hi Garry! Because you use reduction = 'none' in nll_loss(), it will (most likely) return a batch of loss values and therefore loss will be a tensor that contains more than one element. The purpose of .item() is to convert a single-element tensor into a regular python scalar, hence the error. …
cyberguli
Hello, can I ask the difference between the implementations of torch.svd and torch.linalg.svd?I have a laptop with 8GB of ram.If I do:X=torch.rand([600, 154875, 3]) X=X.reshape(-1,1) U,S,V=torch.svd(X)all the commands compute fine.Instead if I tryX=torch.rand([600, 154875, 3]) X=X.reshape(-1,1) U,S,V=torch.linalg.svd(X...
KFrank
Hi Guglielmo! From the documentation for the two versions of svd(),torch.svd()andtorch.linalg.svd(), torch.svd() computes, by default, the “reduced” SVD: If some is True (default), the method returns the reduced singular value decomposition. while torch.linalg.svd() computes, by default, t…
sbht_sbht
I’m trying to build cnn that will classify images of differences between cats and dogs. I wrote such a neural network:import torch import torch.nn as nn device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') def conv2d(in_channels, out_channels, kernel_size): return nn.Sequential( nn.Conv2d...
KFrank
Hi sbht! As you’ve seen, the sigmoid() you are using can easily saturate, after which useful training stops. This is a well-known numerical problem with using BCELoss. Instead use BCEWithLogitsLoss (without the sigmoid() as BCEWithLogitsLoss has logsigmoid() built into it). If you still have…
telias
Hey everbody!I’m trying to minimize a function in order to better understand the optimizer process. As an example I used the Eggholder-Function (https://www.sfu.ca/~ssurjano/egg.html) which is 2d. My goal is to get the values of my parameters (x and y) after every optimizer iteration so that i can visualize it afterwar...
KFrank
Hi Telias! You are appending the same (reference to a) tensor, params, to list_params with every iteration of the loop. You do change the contents of the tensor with every iteration, but when you display list_params, it’s just the same single tensor – with its final value – displayed multiple…
qiminchen
Suppose I have a tensoraand I want to fill the inner with all 1 like tensorbprint(a) tensor([[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.], [0., 0., 1., 1., 1., 1., 1., 0., 0., 0.], [0., 1., 0., 1., 1., 1., 1., 1., 0., 0.], [0., 1., 0., 0., 1., 0., 0., 0., 1., 0.], [0., 1., 0., 1., 0., 0., 0....
KFrank
Hi Qimin! You may use cumsum() to mark those entries that appear to the right of a 1.0 and similarly use flip() with cumsum() to mark those entries that appear to the left of a 1.0. You may then use arithmetical (or logical) operations to combine those pieces together to get your final result: …
Andreas_Binder
Hi everyone,I want to create tensor with shape (N*N,2) from a tensor of shape (N,1) that contains all possible combinations (with duplicates). It is part of a bigger pipeline but I realised that the gradients do not flow; this is how the code looks like:x_graph = torch.tensor([[-1], [0], [1]], dtype=torch.float, requir...
KFrank
Hi Andreas! In this line of code, n and i are indeed pytorch tensors. However, the Tensor factory function, torch.tensor(), is expecting python scalars, so pytorch (helpfully) converts the tensors you pass in to python scalars. This “breaks the computation graph,” backpropagation fails, and ad…
kenseehart
I want to share the same set of weights across several nodes in a layer, somewhat like a convolutional neural net, but where the weight sharing does not reduce to a simple slicing operation, but instead require indirection through a permutation array.A graphic view of what I have in mind:Game of Y ANN$$ B_i = \phi(\sum...
KFrank
Hi Ken! Pytorch tensor indexing should let you use a tensor of your permuted indices to index into your A and w tensors. I don’t follow the details of your use case, but here is an example where the permutation indices are packaged as 1d tensors: >>> import torch >>> print (torch.__version__) …
Zwei
Hi all,I have a multiclass classification problem and there are some inter-class relationship. Then a modified version of Cross-Entropy Loss Function is used., wherePis the probability andMis the label.For short, in addtion to log_softmax(), I need to implement log(1 - softmax(X)), let’s call itlog1m_softmax(). However...
KFrank
Hi Zhengwei! As noted by Mert: That is, 1 - softmax (X)_i is (sum_j (exp (X_j)) - exp (X_i)) / sum_j (exp (X_j) = (sum_(j != i) (exp (X_j)) / sum_j (exp (X_j) This is also discussed in the stats.stackexchange thread you linked to. You can implement your numerically-stable log1m_softmax() “by …
Maryam_Khaliji
A balanced dataset allows us to detect overfitting or under fitting by comparing train and validation error. But is this comparison meaningful for imbalanced dataset when we use class-weight in binary cross entropy loss calculation?How we can find the best model?
KFrank
Hi Maryam! It would be reasonable to use AUC to select your “best” model. The idea would be that AUC is “the metric you care about” and that binary cross entropy is the proxy for that metric that you use for training. Again, this would also be reasonable. Now you would be using some combina…
laro
I have data with the shape: (512, 20, 32) and I want to useAvgPooland get the shape of: (512, 10, 32).I have tried with no success:pool = nn.AvgPool1d(kernel_size=2, stride=2) data = torch.rand(512, 20, 32) out = pool(data) print(out.shape)output:torch.size([512, 20, 16])How can I run pool on the horizontal data ?
KFrank
Hi Amit! Use .transpose() to make your “horizontal” dimension the last dimension of your tensor, apply AvgPool1d, and transpose back: out = pool (data.transpose (1, 2)).transpose (1, 2) Best. K. Frank
HeMuling
when I put animageinside a CNN networknetbynet(image), it gives two different answers by two different ways, I wonder if it is a bugresult = net(image) softmax_result1 = F.softmax(result, dim=1) print(softmax_result1) softmax_result2 = F.softmax(net(image), dim=1) print(softmax_result2)and the result istensor([[0.5803...
KFrank
Hi Muling! Dropout (when in training mode) pseudorandomly zeros out some elements of the tensor passing through it, and does so differently on every forward call. Try: result = net(image) softmax_result1 = F.softmax(result, dim=1) print(softmax_result1) softmax_result1 = F.softmax(result, dim=1…
momomo
My model architecture is defined as the following:class NN(torch.nn.Module): def __init__(self): super(NN, self).__init__() self.linear1 = nn.Linear(3, 9) self.act1 = nn.ReLU(inplace=False) self.linear2 = nn.Linear(9, 3) def forward(self, x): x = self.linear1(x) ...
KFrank
Hi Momo! As@soulitzernoted, using retain_graph = True can often lead to inplace-modification errors. (Based just on the code you posted, I don’t see why you would need retain_graph = True, so you should try to get rid of it.) However, I don’t think that this is your main issue. Using indi…
Rane90
Hi,I’ve been having trouble computing my desired loss: I have two input tensors <X, Y>, with shapes: (batch_size, num_rows, num_columns). The loss I want to compute is the correlation between the respective <X, Y> columns for each one of the samples.So far I’ve been iterating through each sample:def cov(x, y): x_ba...
KFrank
Hi Rane! It’s relatively straightforward to implement a loop-free batch version of your cov() function. Furthermore, torch.linalg.inv() (which torch.inverse() is an alias for) computes matrix inverses on a batch basis if you pass in a tensor with more than two dimensions. Together, these shou…
Chenoille
Hello,I want to train a neural network on some image dataset for a regression task. The output would be a probability, so a value between 0 and 1; I have targets that are also probabilities. I want to know what the best training strategy would be.Is is meaningful to set the last layer to be sigmoid such that the previo...
KFrank
Hi Chenoille! We would typically not use the term “regression task” when training a network to predict probabilities. If you believe that your use case is a classic regression task, please explain it in a little more detail. Based on what I think your use case is, you should use BCEWithLogits…
milan_kalkenings
i have two tensors:alpha.size() ->[3]image.size() -> [16, 3, 28, 28].I want to elementwise addalpha[i]to all elements inimage[16, i, 28, 28].what is the (in best case most efficient) vectorized way to do so?
KFrank
Hi Milan! Yes, you may use broadcasting to “vectorize” your element-wise addition. You just need to use unsqueeze() to add the singleton dimensions that will then get broadcast: image + alpha.unsqueeze (-1).unsqueeze (-1) Equivalently, I sometimes find the index-with-None syntax stylistically …
0x97
I am dealing with two modules, both of them contain different sub-modules and one of these must be the same, as follows:class Module1(nn.Module): def __init__(self, net1, net_shared): super(Module1,self).__init__() self.net1 = net1 self.net_shared = net_shared def forward(self, x): ...
KFrank
Hi 151! Yes and yes. No, nothing is being copied (other than the python references themselves). The line of code, net_shared = nn.Sequential(), instantiates a single instance of the class Sequential and sets the python reference net_shared to refer to it. When, instantiating instances of Mod…
samsja
Hey all. My question is in the title:What happened to a view of a tensor when the original Tensor is deleted? It seems that the view still hold its memory but does it hold a reference to the full tensor or only the part that concern it ?Let me gave you an exampleimport torch a = torch.zeros(10 ,100) b = a[0] del a p...
KFrank
Hi Samsja! Nothing. The “view” holds a reference to all of the data that comprised the original tensor. We can use Tensors’ .storage() method to probe its “storage” and _TypedStorage’s .data_ptr() method to see the actual location of the data itself. Consider: >>> import torch >>> print (t…
Kore_ana
Hi! I’m trying to freeze parts of the code and I tried the method of only putting in certain parameters when defining the optimizer, which seems to work but I couldn’t find this method anywhere else on the web so was not sure if this method is OK to use… the code is below. any help would be greatly appreciated!class m...
KFrank
Hi Kore! Yes, this is a sound way to freeze the weights of the other layers. It is true that calling .backward() on you loss will cause the gradients of all of the layers to be populated. But populating the gradients doesn’t, in and of itselt, cause the weights to change. It’s the optimizer…
abolfazl_saheban
Hello, I want to upsample a feature map by a scale factor=2 but with Transposed Convolution.Here is a code for this purpose but by using torch.nn.Upsamle.nn.Upsample(scale_factor=2, mode=‘nearest’)Is there any possibility to do this with Transposed Convolution and if it is possible, what parameter should I give totorch...
KFrank
Hi Abolfazl! Use kernel_size = stride = 2 (and for in_channels and out_channels, use whatever is appropriate for your use case): >>> import torch >>> torch.__version__ '1.13.0' >>> t = torch.ones (1, 1, 8, 8) >>> t.shape torch.Size([1, 1, 8, 8]) >>> convtran = torch.nn.ConvTranspose2d (in_channe…
vdw
I’m trying to implement my own Conv2d layer for self-study and educational purposes. I feel quite confident that I understand the basic idea and steps – images like the one below illustrate the steps pretty well:conv2d-illustration974×874 243 KBMy current implementations looks as follows:import torch import torch.nn as...
KFrank
Hi Chris! I would instantiate a pytorch Conv2d and then instantiate a VanillaConv2d. Then set filter_weights and filter_biases of your VanillaConv2d to be the same as those of Conv2d (or vice versa): with torch.no_grad(): vanillaConv.filter_weights.copy_ (conv.weight) vanillaConv.filter…
dluca12
I need to usetorch.einsumto do the convolution instead of usingtorch.nn.functional.conv2d.In short, I got 16 images with the size of (3, 4, 4) and 16 kernels with the size of (3, 4, 4). I need to apply one kernel to one corresponding image and get one output (one data point).import torch import torch.nn.functional as F...
KFrank
Hi Luca! For this computation, conv2d() and einsum() are equivalent. The difference* you see is due to numerical round-off error (because the two versions are performing the computations in different, but mathematically equivalent orders). Your two results agree to seven decimal digits, which…
slobodaapl
I’m trying to multiply a sparse matrix with a dense matrix, but I’ve encountered an error I can’t find mentioned anywhere on the forums or GitHub and I’m suspicious it is related to the current CUDA toolkit that I’m using, or perhaps the torch version, where the function is simply not implemented, but I’m not sure:def ...
KFrank
Hi Tibor! I can reproduce your issue on both pytorch 1.12.0 / cuda 11.6 and pytorch 1.14.0.dev20221014 / cuda 11.7. Thisgithub issuesuggests using torch.sparse.mm() as a replacement. Note that torch.sparse.mm() returns a dense tensor (on both the cpu and gpu), while torch.smm() returns a spa…
winchest
a = self.a a = a[:, :, None] a[:, j % 10] = bwhen I change the value ofa,I find that the value ofself.ais changed too. How can I keep the value ofself.a?
KFrank
Hi Zhao! This is a general python issue rather than an issue specific to pytorch. a and self.a are python references that both refer to the same object (in your case a pytorch tensor). Consider this pure-python illustration of how references work: >>> l = [1, 2, 3] # l is a reference tha…
SlimShadys
Hi everyone. I’m building a simple model for a binary classification task on theGerman Credit Numericdataset.I have a numpy array of inputs (24 features), followed by a numpy array of outputs {0,1} as follows:X:X[0]: [ 3 6 4 13 2 5 1 4 3 28 3 2 2 2 1 1 0 1 0 0 1 0 0 1] X shape: (750, 24)Y:y[0]: 1 Y...
KFrank
Hi Slim! This could be a significant issue. Scaling your training and validation data differently could certainly degrade inference on your validation data or cause it not to work at all. Input values that are naturally continuous (such as Salary and Age) could reasonably have some “noise” a…
AfonsoSalgadoSousa
I have a tensorAof sizeB x 4and another tensorBof sizeH x N.Ahas integer values and many are -1 like:tensor([[ 2.2640e+03, -1.0000e+00, -1.0000e+00, -1.0000e+00], [ 3.5400e+02, -1.0000e+00, -1.0000e+00, -1.0000e+00], [ 6.2700e+02, 6.2900e+02, -1.0000e+00, -1.0000e+00]I want a new tensor of sizeB x Hwith...
KFrank
Hi Afonso! Because you want to average multiple entries of B, trying to use index_select() won’t fit your use case. Use A to pluck the desired values out of B with pytorch tensor indexing and then compute the average “manually.” Here is an illustration of such a scheme with a version of B that…
hiru
I have a stack of feature maps as given below. (my batch size is 32 and I have 64 feature maps with each with size 64x64)out0 = self.selection[0](x)#output=[32,64,64,64] out1 = self.selection[1](x)#output=[32,64,64,64] out2 = self.selection[2](x)#output=[32,64,64,64] out=torch.stack([out0,out1,out2]).permute(1, 0, 2, ...
KFrank
Hi Hiru! Please note that optimizers do update tensors with zero gradients if they are using weight decay or momentum (that is already non-zero). Try your experiment using plain-vanilla SGD without weight decay or momentum. If you still see this result, please post a simplified, complete, run…
Mahdi_Amrollahi
Is that possible to predict both classification and regression in single model?Suppose that we have target shape like[b1, b2, c1, c2, c3]which bs are for regression target and cs are for classification target and they are from one-hot encoding.
KFrank
Hi Mahdi! Yes, and it can be a reasonable thing to do. I recommend against using one-hot encoding. There’s no reason to do so and it introduces at least a little inefficiency. (I assume that you mean that you have three classes and that exactly one of c1, c2, and c3 is one, with the other tw…
MartinPerry1
I have unfolded tensor and got the resulting dimension like this:[batch, tilesCount, chanCount, h, w]. I would like to apply a different conv2d operation for each tile (a list of sizetilesCountwithconv2d). Can this be done on a single tensor or do I have to split it to list and apply convolutions separately in a loop? ...
KFrank
Hi Martin! Yes, you can use groups to give each tile its own convolution kernel and bias. To do this, reshape() (or possibly view()) your input tensor so that you combine your tilesCount dimension with your chanCount dimension. Using groups = tilesCount in effect splits your Conv2d up into mul…
JUNHAOYAN
I have been trying to figure this issue out by myself for a day but I have no idea what is going on here. The detailed error is shown below:K:\Anaconda\envs\cv\lib\site-packages\torch\autograd\__init__.py:197: UserWarning: Error detected in MaxBackward0. Traceback of forward call that caused the error: File "K:\Baidu...
KFrank
Hi Junhao! *= is an in-place operation. From what you’ve said, max_conf_idx will be a LongTensor of shape [98], so this is almost certainly your culprit. As a work-around you could try max_conf_idx = 5 * max_conf_idx. (This version creates a new tensor and sets the python reference max_conf_i…
papoo13
I am working on a research project and as part of it, I need to modify the Mask R_CNN architecture to have multiple inputs and outputs. I want to choose a base code for this, but various repos are available, including detecron2 and Facebook Mask_R_CNN. I found detecron2 complicated to start with. Do you suggest using P...
KFrank
Hi Samin! I have used pytorch’s Mask R-CNN. It works and seems sensible and solid, but I don’t have any useful comparisons with other implementations. One advantage of using the pytorch version is that you might be a little more likely to get answers about it on this forum, rather than about o…
sadra-barikbin
Hi, it seems indexing a tensor withsliceorintreturns a view of that without copying its underlying storage but indexing with another tensor (aBoolor aLongone but not a 0-dim long tensor) or a list returns a copy of the tensor. Am I right? If yes, why is this the case?This behavior seems not to be documented anywhere in...
KFrank
Hi Sadra! Yes. (You can use .storage().data_ptr() to see if the underlying data of a tensor has been copied or not.) With slices you can leave the original data in its original location in memory and still access it (reasonably) efficiently with strides and offsets. When you index into a ten…
S_M
Hi, I am trying to add some layer to the resnet18 pre-trained network using this code.class T(nn.Module):definit(self, class_num):super(T, self).init()self.base = models.resnet18(pretrained=True)self.sigmoid = nn.Sigmoid()self.class_num = class_numself.num_ftrs = self.base.fc.in_featuresself.linear = nn.Linear(10,1) d...
KFrank
Hi S! As posted, freez() has no return statement, so, in effect, it returns None. You set self.base to freez(), that is, None and call self.fc(self.base) which tries to evaluate net.fc (i.e., self.base.fc), but net (self.base) is None, hence the error. Best. K. Frank
JoshuaM
I’m extending open source code based on a paper and seek help understanding code related to the loss (the author already has a backlog of questions and comments from me at this point). My hope is that someone with more expert knowledge on losses can understand the code, and then I can make it easier for the next person...
KFrank
Hi Josh! What’s going on is that when you increase the number of classes to 4 from 2, the shapes of some tenors change. You need to account for this or you will get these shape-mismatch errors. In this particular instance ou has the length of its rows increase to 4 (from 2), but torch.cat ((a…
Kallinteris-Andreas
(Pdb) p temp [tensor([ 7.9873e-01, 9.9704e-01, -6.7735e-02, -3.6495e-02, 6.8676e-04, 5.2778e-02, 6.9929e-03, 1.8170e-02, -4.0842e-02, 8.8229e-02, -7.0201e-02, 7.8539e-02, -1.6455e-02, 6.0354e-02, -2.1752e-01, -7.2633e-02, 1.0848e-01, 6.1456e-02, -6.3961e-02, -1.0666e-01, -2.454...
KFrank
Hi Kallinteris! Doestorch.stack()do what you want? Specifically, something like torch.stack (list_of_tensors, dim = -1)? Best. K. Frank
John4
Hi. I want to translate the following matlab code in pytorch. Is there a simple way to perform it?idx = randperm(numberOfDbExamples,5); for i=1:length(idx) k(i)=find(labels==classificationAll(idx(i))); endcl=labelNames(k,1);
KFrank
Hi John! Please try to rewrite your matlab code using just pytorch tensors and tensor operations. If you have questions, please post a complete, fully-self-contained, runnable (or at least runnable up to where it raises an error) script together with its output and a description of what you wo…
ellipsis
I have tensor like this:arr1 = np.array([[ 1.6194, -0.6058, -0.8012], [ 1.1483, 1.6538, -0.8062]]) arr2 = np.array([[-0.3180, -1.8249, 0.0499], [-0.4184, 0.6495, -0.4911]]) X = torch.Tensor(arr1) Y = torch.Tensor(arr2)I want to do torch.dot on every tensor 1D (2 vectors) inside my 2D tensortorch.dot(X, Y)I want to g...
KFrank
Hi Ellipsis … This will depend on what “something” is. In general, you would want to figure out how to do “something” using pytorch tensor operations that act on your 2D tensors all at once. For your particular example of computing the dot products of the vectors in your 2D tensors you can us…
Prakhar_Sharma
I have two external trainable parameter as follows:bc_left_coeff = torch.tensor((1.1,), requires_grad=True, device=device)#.to(device) bc_right_coeff = torch.tensor((1.1,), requires_grad=True, device=device)#.to(device) params = list(PINN.parameters()) + [bc_left_coeff, bc_right_coeff]I want to modify thebc_left_coe...
KFrank
Hi Prakhar! At this point bc_left_coeff is a python reference to an object in memory, namely the Tensor you just created. Let’s call this “Object 1.” Then at some point you add “Object 1” to optimizer’s parameter list. optimizer holds its own reference to “Object 1.” When your “special condi…
Saswat
I’m working on a classification problem. The number of classes is 5000. I have a ground truth vector that has the shape (1000) instead of 1. The values in this target vector are the possible classes and the predicted vector is of the shape (1x5000) which holds the softmax scores for all the classes. Which loss function...
KFrank
Hi Saswat (and Srishti)! It’s not clear what your use case is. The first question, as Srishti mentioned, is whether you have a multi-label, multi-class problem or a multi-class (single-label) problem. Conceptually, is a given sample in exactly one class (say, class 3), but for training purpose…
xeTaiz
Hi there,I’m trying something along those lines:I have indices to a 3D volume (b), andb.nonzero()gives me (N, 3) indices to index with.Now I have another 3D volume with some more dimensions (a) and I would like to get something of the shape (BS, F, N) with N being the number of nonzero samples inb.a = torch.randn(1,2, ...
KFrank
Hi Dominik! Use pytorch tensor indexing as follows: Create five appropriately-structured index tensors – one each for each dimension of a – of shape [BS, F, N], and use these to index into a. Thus: >>> import torch >>> print (torch.__version__) 1.12.0 >>> >>> _ = torch.manual_seed (2022) >>> >>…
HeleneAthene
Hello, I am a beginner PyTorch user and have been following some tutorials to learn how to build some very basic PyTorch models. After building a model to fit a linear distribution (01. PyTorch Workflow Fundamentals - Zero to Mastery Learn PyTorch for Deep Learning) I tried to create a model to fit a polynomial distrib...
KFrank
Hi Helene! You can fit the polynomial, but training is slow so you might need a little patience. Your code will work if you use a lot of epochs. I’m not that patient, so I added momentum to the SGD optimizer to get the training to converge more rapidly. Here is your code, with (minor) modifi…
nassim
Hi, i want to design a network for a prediction task. But my prediction task is quite special. I don’t want to train my model to predict labels but the probability of those labels (my targets are probabilities of those labels , not certainties). So my question is ,which loss function should i choose for this task? Do i...
KFrank
Hi Nassim! CrossEntropyLoss would be a perfectly appropriate – and likely the best – loss function for this use case. (Older versions CrossEntropyLoss did not support probabilistic targets, but more recent versions, including the current stable release, 1.12.1, do.) Assuming that target is a p…
ann81
I am trying to reproduce the loss function from Eq 9 in thispaper. The idea is that it goes over different matchings of elements in the output and target to create a permutation invariant version of Cross Entropy Loss. This is my implementation currentlyCrossEntropyLoss = nn.CrossEntropyLoss() def SetCrossEntropyLoss(o...
KFrank
Hi Ann! Neither the loops nor the inplace operations will cause problems with backpropagation and gradient computation. Note, a nice feature of autograd is that it warns you if an inplace operation has broken backpropagation. If that were to happen, you could simply not use inplace operations…
Alex_Shen
Hi, I’m quite new to PyTorch and I came cross the ‘@’ operation, which does matrices multiplication for the last two dimensions. (referrence:How does the @ sign work in this instance?).As far as I understand, given two tensors A (bsz, d1, d2), and B (bsz, d2, d3), (A@B)[i] should equal to (A[i])@(B[i]); thus, these tw...
KFrank
Hi Alex! Because of floating-point round-off error, this will not be true in general. The two computations are mathematically equivalent, but pytorch chooses to perform various arithmetic operations in differing orders that can lead to differing round-off error. Integer operations don’t suffe…
lkdci
The theoretical floating point precision is 2**32, which is ~4.3e9. I noted a weird behavior withtorch.eqoperation, seems that the limit is around at 2.9e-8, see the example bellow.Is there any documentation about those values? which epsilon values are recommended to use to avoid numerical errors when using fp32 or fp1...
KFrank
Hi lkdci! Your misconception here is that the full 32 bits of a 32-bit single-precision floating-point number are used for precision. But 8 of those bits are used for the number’s (binary) exponent, which is what gives floating-point numbers their large dynamic range. That leaves you then wit…
ao_xu1
After I run this code:import torch import torch.nn as nn ta = torch.Tensor([[[[2., 4.], [0., 1.]]]]) up = nn.ConvTranspose2d(in_channels=1, out_channels=1, kernel_size=2, stride=1, padding=0) with torch.no_grad(): up.weight.data = torch.Tensor([[[[3., 1.], [1., 5.]]]]) tb = up(ta) print(tb)I get the result:ten...
KFrank
Hi Ao! You’re ignoring the bias term in ConvTranspose2d. Try: up = nn.ConvTranspose2d (in_channels=1, out_channels=1, kernel_size=2, stride=1, padding=0, bias = False) You will then obtain your expected result. (Or you could set up.bias to a known quantity just as you do with up.weight.) Bes…
peustr
This sounds counterintuitive but let me explain.I have 2 nn.Modules, let’s call themmodelandinput_generator.input_generatoraccepts a data pointxas input, and outputs a vectorx_new.x_newis in turn passed to themodel, andmodelis trained to minimize the cross entropy loss betweenmodel(x_new)andtarget. In code:# assume: in...
KFrank
Hi Panagiotis! If I understand your use case correctly, you would like to train input_generator so that it produces samples of x_new which if used to train model with the loss function cross_entropy (model (x_new), target) then model will learn (from being trained with x_new) to minimize cross…
J_Johnson
Suppose we have a matrix as follows:A=torch.arange(100).view(20,5)And suppose we also have a mask to apply, such as:B=torch.rand(100).view(20, 5) mask=B>0.1Now suppose we also wish to get the mean along Dim=1 but with the mask applied:print(torch.mean(A[mask], dim=1))But this gives an error, because applying this type...
KFrank
Hi Srishti (and J)! This replaces masked elements with 0.0 that then get mixed in with the mean() computation, diluting it. Based on the pseudocode J posted, I don’t think this is what he wants. Computing the mean in terms of a masked sum and a masked count gives what I think is the desired r…
songyuc
Hi, guys,I heard that WeightDecay might not be appropriate to be applied on all the bias terms. Is that true? And what is a good way to apply WeightDecay on bias terms?Your answer and guide will be appreciated!
KFrank
Hi Songyuc! I haven’t experimented with this in any detail, but I have used weight decay on entire networks, including the bias terms, without any problems. It is true – at least according to my intuition – that the bias terms have less redundancy in them than do, for example, the weight terms …
Maryam_Khaliji
In PyTorch, we havenn.linearthat applies a linear transformation to the incoming data:y = WA+bIn this formula,Wandbare our learnable parameters andAis my input data matrix. The matrixAfor my case is too large for RAM to complete loading, so I use it sparsely. Is it possible to perform such an operation on sparse matric...
KFrank
Hi Maryam! Note, you can use a Linear and apply it to a sparse tensor. (You don’t need to explicitly call something like torch.sparse.addmm().) You don’t have to use Linear, of course, but it might be stylistically better since it’s used so commonly. If it better fits your use case, you can a…
tsp_t
The result of [3, 3] shaped tensor matmul with [3, 16, 1080] was expected to yield [3, 16, 1080] shaped tensor.However, I get a runtime error.Is this the wrong implementation? Or am I missing something?import numpy as np import torch X = torch.from_numpy(np.random.randn(3,3)).cuda().float() Y = torch.from_numpy(np.ran...
KFrank
Hi tsp! torch.matmul() (@) doesn’t perform the matrix-tensor multiplication you might expect. Instead, for these tensors, it tried to perform “batch matrix multiplication” (broadcasting the batch dimensions), and the dimensions don’t line up properly. Probably the simplest approach is to use e…
simines
To use weighted random sampler in PyTorch we need to compute samples weight. In case of image classification where we have one label for each class, we can compute samples weight using sklearn library. However, for segmentation, for each image we have multiple classes. I was wondering how we can compute the samples wei...
KFrank
Hi Carol! I will answer in the context of semantic segmentation where you classify each pixel in an image (rather than assigning the entire image to a single class). To first approximation, you won’t want (or be able) to use sample weights for semantic segmentation. Instead you will want to u…
wayne1226
I have a 6-dim tensor say [1,1,4012,6034,11,11], how can I apply the convolution along the last two dims? Excepting the unfold operation which will cause OOM
KFrank
Hi Wayne! If I understand your use case correctly, you want to apply a 3x3 convolution to each of the 11x11 patches spanned by your last two dimensions. If this is right, you can use view() (or reshape()) to push your two large dimensions into the “batch” dimension (keeping a singleton “channel…