user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Sherzod_Bek | Hi,I did binary classification(dog&cat) output is between 0 and 1. It works perfectly with two classes.But when I test totally different image(human, nature, etc) output is closer to 1(class1) or closer to 0(class2).I think it should show around 0.5. because image doesn’t look like any class.could you explain reason... | KFrank | Hi Sherzod!
Here’s my speculative way of looking at this:
You train your classifier to predict one of two classes. When it gets it
right, it gets rewarded for predicting that class with high certainty, so
there is some bias towards making high-certainty predictions. Because
you don’t train w… |
Charamba | Hi Guys,I would like to remove zero values of a tensor and “join” the non-zero values in each row of a tensor in format [B, C, H, W]. A naive way would to doout_x = x[x!=0], this approach is bad because would destruct the Tensor dimensions.For resume, I would like to transform an input tensor like this:in_x = torch.ten... | KFrank | Hi Luiz!
At the cost of n log (n) time complexity, you can use argsort()* and
then use gather() to index back into your input tensor:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> in_x = torch.tensor([[[[0., 0., 2., 20., 250., 0., 0., 0., 0., 0., 250.,
... … |
LuukJ | Hi everyone,I am currently working on a setup where the output of my network is first modified by my own module before computing the loss and backpropagating this, as follows:class NeuralNet(nn.Module):
def __init__(self):
super(NeuralNet, self).__init__()
self.Layer1 = Layer()
self... | KFrank | Hi Luuk!
Yes, but …
You won’t want to bypass your Own_module backpropagation entirely.
Suppose Own_module were simply return -input, that is, it just flipped
the sign of (the gradient of) the loss function? Then you would be training
your model to maximize the loss function, your predictions… |
gkrisp9 | Hello, I am new to PyTorch and I want to make a classifier for 3D DICOM MRIs. I want to use the pretrained resnet18 from monai library but I am confused with the input dimensions of the tensor. The shape of the images in my dataloader is [2,160,256,256] where 2 is the batch_size, 160 is the number of dicom images for e... | KFrank | Hi gkrisp!
It would almost certainly be worse, if I understand correctly that you
are working with 3d images.
The point is that your images have substantive spatial structure.
That is, just as a pixel with x = 17 is right next to x = 18, but far
away from x = 148, a slice in your 3d “z-stack”… |
Federico_Ottomano | Hello,I’m wondering if there is a pretty straightforward way (possibly this is trivial) to implement a neural network in PyTorch with a variable number of input features.Many thanks,Federico | KFrank | Hi Frederico!
Focusing on your word “standard,” no, a fully-connected network will
not be able to accept a variable number of input features.
Let’s say you have an input batch of shape [nBatch, nFeatures]
and the first network layer is Linear (in_features, out_features).
If nFeatures != in_fea… |
codeflux | Hi,I am implementing an A2C algorithm, the loss function for the critic is simply the advantage function and that works.For the actor I use this:loss = -distribution.log_prob(sample)*advantage.detach()
loss.requires_grad = True
loss.backwards()where advantage is calculated using the critic and sample is from sampling f... | KFrank | Hi Codeflux!
I believe that MultivariateNormal and Normal have the same
behavior in this regard.
In general, you can’t differentiate or back propagate through calling
.sample() on a Distribution. This is true for Normal, as well as
MultivariateNormal. In contrast, you typically can backpropa… |
HmmmmML | Hi! I have a very simple exampleModulebelow, where I have acircular buffer, and attempt to learn a_delayparameter (i.e. distance between a read and write pointer) that transforms an input sin wave into a phase-shifted and zero-padded output. The goal is to emulate adelay line(as in DSP), learning an unknown delay param... | KFrank | Hi Hmmm!
Although _delay is a Parameter and potentially trainable, at a technical
level, as soon as you call .item() on it you “break the computation graph,”
as the result of .item() is no longer a pytorch tensor and therefore no
longer participates in autograd.
At a more conceptual level, you… |
mmitjans | Hi,I’m trying to build a convolutional 2-D layer for 3-channel images which applies a different convolution per channel. This brought me to investigate thegroupsparameter innn.Conv2d. If I’m not mistaken, to do this I should simply create aConv2dlayer in a manner similar than:conv_layer = Conv2d(3,3,(1,5),groups=3)For ... | KFrank | Hi Marc!
Your understanding of groups does seem to be correct. However,
in your test you’ve overlooked Conv2d’s bias.
You can either turn bias off (bias = False) or copy bias over
from conv1 to conv2, along with weight:
>>> import torch
>>> import torch.nn as nn
>>>
>>> I = torch.randn(10,3,4… |
111414 | I have two real-valued matrices A and B with the shapes of (m, n) and (n, p), respectively.I know there are fast APIs (e.g. mm, matmul, einsum) in PyTorch to achieve matrix multiplication, but I want to knowif there exists an efficient way to change the dimension-reduction function from inner product to the operation I... | KFrank | Hi Bin!
I think, in general, if your g() is built from a broadcastable operation
and a reduction operation, you can accomplish your goal with pytorch
broadcasting.
In your specific case, you can use unsqueeze() in the appropriate
locations to replace the nested loops with broadcasting, and t… |
my3bikaht | Documentation mentions that it is possible to pass per class probabilities as a target.The target that this criterion expects should contain either:…Probabilities for each class;…Target: … If containing class probabilities, same shape as the input.which also comes with example:>>> # Example of target with class probabi... | KFrank | Hi Sergey!
Support for “soft,” probabilistic targets for CrossEntropyLoss is new
as of (I believe) the current stable version, 1.10.0.
Your best bet will be to upgrade to the current stable release.
Best.
K. Frank |
droid | I have a vanilla implementation of UNet, which I want to use for multiclass segmentation (where each pixel can belong to many classes). I am interested in advice on which loss function to select in this application.This long threadsuggests usingCrossEntropyLossat first, before recommendingBCELoss. Is one of these metho... | KFrank | Hi Droid!
Let me distinguish between a (single-label) multi-class problem and
a multi-label, multi-class problem. In both cases you have multiple
classes (one of which might be a “background” or catch-all “other”
class).
In the single-label case, each pixel (or more generally, each item
to b… |
blu_head | Hi everyone,I’ve been trying to optimize images from a specific class and I created the tensor training_data_new myself (serves as a training dataloader). However, it still gives me the error “can’t optimize a non-leaf Tensor” on the line where I create optimizer2. I have tried casting it to float and just multiplying ... | KFrank | Hi Blu!
The seemingly innocuous image = image * 1.0 creates a new
image (that is then assigned to the python reference variable image)
that, being the result of a tensor computation, is no longer a leaf
variable.
Consider:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> image = torch.zeros… |
snowball | I’m slightly confused as to what param.grad is calculating mathematically?Here, it says “Computes and returns the sum of gradients of outputs with respect to the inputs.”https://pytorch.org/docs/stable/autograd.htmlCan someone help me interpret this?Suppose I’m looking at the weight of one neuron in a fully connected h... | KFrank | Hi Snowball!
Yes.
Not exactly.
Let w be a Parameter (or for than matter, just a Tensor that
has requires_grad = True, but is not wrapped in a Parameter),
and let L be a scalar (that is, a tensor with a single element) that
has been calculated from w (and a bunch of other Parameters
and non-P… |
hankdikeman | I have a custom loss function defined and I hit a wall debugging it. It is designed to return loss that is scaled according to the output value:import torch
from torch import nn
import torch.nn.functional as F
class ConditionalMeanRelativeLoss(nn.Module):
def __init__(self):
super(ConditionalMeanRelativeLo... | KFrank | Hi Henry!
It looks like your issue is due to a troublesome bug in the innards of
autograd – not specific to torch.where(), but in lower-level infrastructure.
However, in your use case, you can work around it by clamping the
denominator of your potential divide-by-zero away from zero. Here
is … |
enemis | Hi,I havent found exactly this problem before, and keen if anyone has any ideas. I have a 2d matrixxcontaining integer values. I want to count how many of each value per row and return a new 2d matrixnum_of_valuethat has the same number of rows, but the columns represent different values. So in num_of_value[0,1] is the... | KFrank | Hi Simen!
Please try torch.nn.functional.one_hot (x).sum (dim = 1).
Best.
K. Frank |
zvant | I always thought 32-bits floats should be sufficient for most ML calculations. I tested the actual precision of a simple matrix multiplication operation on NumPy, PyTorch CPU, and PyTorch CUDA. Here is my code:import numpy as np
import torch
np.random.seed(0)
M = np.random.randn(1000, 1000).astype(np.float64)
for T_n... | KFrank | Hi Zvant!
Depending on your GPU, nvidia might be switching you over by
default to the misleading (dishonestly?) named “tf32” floating-point
arithmetic. (tf32 is essentially half-precision floating-point.)
You can try turning tf32 off with:
torch.backends.cuda.matmul.allow_tf32 = False
See t… |
Qiyao_Wei | Hi all,Even though torch.symeig() seems to give accurate results most of the time, I ran a test case today and noticed that the eigenvalues and eigenvectors don’t make sense. My Pytorch version is 1.8.0, see following minimal reproducible example—import torcha = torch.tensor([[1,3,4],[2,2,4],[8,7,6]]).float()d,q = torc... | KFrank | Hi Qiyao!
Your matrix, a, is not symmetric, but torch.symeig() expects a
symmetric matrix to be passed in. Use torch.eig() for a general,
square, non-symmetric matrix.
(In practice, I believe that symeig() just uses the upper triangle of
the matrix you pass in.)
Best.
K. Frank |
danishnazir | Hi I have a normalized data which is from [-1,1] with mean 0 and standard deviation 1. I want to map it to [0,1] in order to give to the network. Can anyone tell me here how does this remapping work and will we get any benefit of normalization even after changing the range to [0,1]? | KFrank | Hi Danish!
Note that taking what you’ve written literally this can only be true if half
of your data is -1 and half is 1. You probably mean something a little
different.
mapped_data = (data + 1) / 2
If you are feeding your data to an already-trained network that was
trained with data in th… |
afsaneh_ebrahimi | I’m trying to set one element of weight to 1 and then hold it until the end (prevent it from updating in the next epochs). I know I can set requires_grad but I just want it for one element? | KFrank | Hi Afsaneh!
The short answer is to set the specific element in question back to
1 after calling opt.step().
As you’ve recognized, requires_grad applies to an entire tensor,
not separately to individual elements. It is also true that an Optimizer
applies to entire tensors, and not to individua… |
mpalaourg | Hello everyone,I have a -nooby- question about gradient computation. Let’s say I have an input matrixXwith shape of[T, T]. I want to process this matrix in a block diagonal way, where these blocks will have a shape of[B, B]with (B << T).For the first implementation and to check if my logic make sense, I went with a sim... | KFrank | Hi George!
I believe that your discrepancy is due to (accumulated) round-off
error.
An easy way to test this is to repeat your computation using double
precision (by using torch.double tensors). If the discrepancy is due
to round-off error it should drop dramatically, say to about 1e-13. If … |
ZimoNitrome | I have a network with a linear head followed by a sigmoid activation function. Most of my output neurons should be in a range 0-1 and thus sigmoid makes sense, but some of the neurons should output normalized (standardized) colors.So for the last three neurons I dotorch.logit(x)as they can be in the range [-1.3, 1.4]. ... | KFrank | Hi Zimo!
Instead of applying sigmoid() to all of your neurons and then applying
logit() to your color neurons to undo the sigmoid(), apply sigmoid()
only to your non-color neurons so that the color neurons never get
transformed.
(Applying sigmoid() to a large-enough (non-inf) value will map it … |
ZimoNitrome | I am trying to train a model to output the correct angle. I am currently restricting my outputs to [0, 2pi]:2 * torch.pi * torch.sigmoid(logits)My question is: What if the prediction is something like 1.9pi, but the target is 0.1pi. The loss should in theory be something like 0.2pi but in my current situation it will b... | KFrank | Hi Zimo!
Rather than outputting a single value that is your angle, I think it makes
more geometric sense to output two values, x and y, on the ray that
defines your angle. Then regulate your x and y by pushing them
towards (but not constraining them to lie on) the unit circle with a term
like… |
gemsanyou | I know that we can’t call backward on vector Tensor without reducing it to a scalar. However, I also need the gradient to be a vector, with each column is the gradient of each column of the Loss with respect to the parameters, i.e.,import torch
x = torch.tensor([4.0], requires_grad=True)
L1 = torch.sin(x) * torch.cos(x... | KFrank | Hi Kadek!
Does autograd’sjacobian()do what you want?
Best.
K. Frank |
BramVanroy | Doing multi-label binary classification with BCEWithLogitsLoss, but I get a RunTimeError “RuntimeError: result type Float can’t be cast to the desired output type Long”. Running 1.8.1 on Windows but the problem also occurred on 1.4. Am I doing something wrong with respect to multi-labels, perhaps?from torch import Flo... | KFrank | Hi Bram!
Two comments:
First, as you’ve seen, BCEWithLogitsLoss requires its target to
be a float tensor, not long (or a double tensor, if the input is
double). And yes, converting to float (labels.float()) is the
correct solution.
Second, as to why: Unlike pytorch’s CrossEntropyLoss,
BCE… |
ljmzlh | How to implement this (essentially calculating average of vectors)batch_size, d= 8, 128
n, N= 100, 10
feature=torch.rand(batch_size, n, d)
belong=torch.randint(0, N, (batch_size,n))
output=torch.zeros(batch_size, N, d)
for i in range(batch_size):
for j in range(N):
output[i][j]=feature[i][belong[i]==j].me... | KFrank | Hi ljmzlh!
The core issue is that feature[i][belong[i]==j] has a different
shape for different values of i and j. Therefore if you try to build a
“tensor” whose “slices” are given by the above expression, you will
end up with a “ragged tensor” (that is, a tensor whose slices have
differing sh… |
snau | I am trying to learn a parameter which is one element of a bigger matrix. The loss function does not directly use the learnable parameter, but a matrix having this parameter.Simplified code snippet is given below to reproduce the errorimport torch as t
import torch
from matplotlib import pyplot as plt
param = t.tensor... | KFrank | Hi Rishi!
The problem is that you have to rebuild the “computation graph”
before you call .backward() for a second time. Both indexing
into a and setting that “value” to param count as part of the
computation graph.
Consider:
>>> import torch
>>> print (torch.__version__)
1.9.0
>>>
>>> param… |
hadaev8 | For example, I have models net0 and net1 working like thisout0 = net0(inp0)
out1 = net0(net1(net0(inp1)))
loss = criterion(out0, out1, target)I want to reverse the gradient sign from the output of model net1 but calculate net0(inp0) as usual.In simple case, I would doout0 = net0(inp0)
out1 = net0(net1(inp1))
loss = cri... | KFrank | Hi Had!
As an alternative to using a hook, you could write a customFunctionwhose forward() simply passes through the tensor(s) unchanged, but
whose backward() flips the sign of the gradient(s).
You would then insert it at the desired place in your network, e.g.:
out1 = net0 (GradientReversal… |
Aesteban | Given a 2d matrix of size (2000x1000) i need to compute the outer product of each row with itself. Finally all the outer products must be averaged. What is the fastest/most efficient way of doing so?This is by far the biggest bottle neck in my program. Ive come up with 2 solutions. The 2. of which, against all intuitio... | KFrank | Hi Aesteban!
The calculation you are asking for can be performed with a single
matrix multiplication:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> _ = torch.manual_seed (2021)
>>> def avg_matrix_outer_products_v2(a):
... x_dim = a.shape[0]
... ourter_products = torch.outer(a[0], … |
mrityu | Hey.Generally, when we fine-tune a classifier by keeping a pre-trained model as a feature-extractor only, we set therequires_grad = Falsefor the pre-trained block and only train the newly added FC layer.For eg., see the code snippet below:-# Setting up the model
# Note that the parameters of imported models are set to ... | KFrank | Hi Mrityunjay!
Yes, you are correct. When you call optimizer_ft.step(), the
optimizer will only update the weights that were specified in that
optimizer.
Even, if other weights – not in the optimizer – have had their
gradients computed, those other weights will not be updated.
Yes. Just to… |
James_Lee | Hi there. Is there a way for me to calculate the BCE loss for different areas of a batch with different weights? Seemed that the *weight(Tensor,optional) – a manual rescaling weight if provided it’s repeated to match input tensor shape fortorch.nn.functional.binary_cross_entropy_with_logits — PyTorch 1.9.1 documentatio... | KFrank | Hi James!
If I understand your question correctly, you can just use weights of 0.0
and 1.0 to do this.
Let’s say that the input to your model is a batch of images of shape
[nBatch, height, width], and that the output of your model (which
will be the input to BCEWithLogitsLoss) and the target y… |
UmarMubeen | here is my code and errorResidual blockdef Residual_block(in_channel,out_channel):res_layer = [nn.Conv2d(in_channel, out_channel, kernel_size=3, padding=1, stride=1 ),nn.BatchNorm2d(out_channel),
nn.ReLU(inplace= True),
nn.Conv2d(out_channel, out_channel, kernel_size=3, padding=1, stri... | KFrank | Hi Umar!
The problem is that nn.ReLU(out) constructs a ReLU object so
that you then pass that ReLU object to conv_3.
You want either:
out = nn.ReLU() (out)
# or
out = nn.functional.relu (out)
(I’m a little surprised that nn.ReLU(out) itself doesn’t throw an
error because in most cases your ou… |
Haziq | I am training a model for classification where each ground truth has some uncertainty and is thus a vector of probability scores e.g.[0.1, 0, 0.7, 0, 0.2, 0, 0]instead of[0,0,1,0,0,0,0]. The cross-entropy loss in PyTorch however, accepts only an integer target so I was hoping if someone could recommend a solution or an... | KFrank | Hi Haziq!
(As an aside, your title for this thread, “Cross entropy with logit
targets” should probably be “Cross entropy with probability targets,”
since you ask about “probability scores” and use probabilities in the
example you give.)
Your ground-truth target probabilities are what are somet… |
Usman_Mahmood | Hello, I have a tensor of shape N * X * Y where N is the number of subjects. I want to average the upper and lower triangle for each matrix i in N. For example if subject 1 has the matrix:tensor([[1, 2, 3],[4, 5, 6],[7, 8, 9]])Then the output should be:tensor([[1, 3, 5],[3, 5, 7],[5, 7, 9]])So, adding upper and lower ... | KFrank | Hi Usman!
Probably the most direct approach is to average the matrix with its
transpose. Here is an illustration for the 3-dimensional-tensor use
case you mention:
>>> torch.__version__
'1.7.1'
>>> t = torch.tensor ([[[1, 2, 3], [4, 5, 6], [7, 8, 9]], [[10, 20, 30], [40, 50, 60], [70, 80, 90]]… |
Alex07 | I have a tensor likea = torch.Tensor([3,2,7,9,2,9, 9])However, I need the values to start from 0 and go ton-1wherenis the number of unique elements ina. One possible way to compute this seems to be:r = torch.zeros_like(a)
for i,el in enumerate(torch.unique(a)):
r[a == el] = igivingtensor([1., 0., 2., 3., 0., 3., 3.... | KFrank | Hi Alex!
There’s no way you can avoid unique() (or its equivalent). That’s
an inherent bit of processing required by your problem.
You can avoid the loop – depending on the details of your use case,
such as having the values in a being non-negative integers that are
not ridiculously large – b… |
James_Lee | Hi there. I found this statement (BCELoss — PyTorch 1.6.0 documentation. ) in PyTorch doc. Does this mean that I could use thetorch.nn.BCELossfor soft labels without transforming the soft labels into hard labels with a threshold when calling BCE loss? Thanks. | KFrank | Hi James!
Neither BCEWithLogitsLoss (which you should use), nor BCELoss
(which you should not use) has a built-in thresholding feature.
But it’s easy enough to threshold target (the labels) before you pass
it in:
my_threshold = 0.65
thresholded_target = (target > my_threshold).float()
loss = t… |
jhp | Hi I have a quick question about kl divergence loss in PytorchIs it okay to use sigmoid instead of softmax for input? Most of the case I noticed that softmax probability distribution is used, but I wonder does that make sense to use kl divergence loss for multi-label target.I want to use KL divergence loss by giving mo... | KFrank | Hi Jhp!
Not really.
KLDivLoss doesn’t care what any of the dimesions – including
the batch dimension – are. It simply performs an element-wise
computation and takes the mean (but see itsdocumentationfor
how its reduction = 'batchmean' and deprecated reduce and
size_average constructor ar… |
Shar | Hi,I’m trying to use the function:loss = criterion(outputs, labels)where the inputs are:labels=tensor([[2]])outputs=tensor([[274.3095, 842.6060, -52.4284]], grad_fn=<AddmmBackward>)but I get the error:multi-target not supported at /Users/distiller/project/conda/conda-bld/pytorch_1570710797334/work/aten/src/THNN/generic... | KFrank | Hi Shar!
Your labels has one too many dimensions. It appears that
you are using a cross–entropy-type loss criterion. Pytorch’s
CrossEntropyLoss (and related loss criteria) expect your
outputs to have shape [nBatch, nClass] and your labels
to have shape [nBatch] (with no nClass dimension). I… |
melike | Hi all, I have a tensor with integers in the range [0, N-1] and I need to create N masks, one for each integer value, i.e. in the 0’s mask all values of 0 should be True and the rest False, and so on. So far I could come up with a for loop on the range, but that drastically increases the runtime. I’d be grateful if som... | KFrank | Hi Melike!
Try:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> _ = torch.manual_seed (2021)
>>> N = 10
>>> t = torch.randint (N, (2, 3, 5))
>>> i = torch.ones ([N] + list (t.shape)).cumsum (0) - 1
>>> masks = t == i
>>> t
tensor([[[4, 9, 3, 2, 5],
[6, 2, 0, 5, 0],
[1, 9, 7, … |
azer | Hi all,I am training resnet18 for image classification and I got good results but accuracy of the validation dataset is higher than the training dataset.| train loss: 0.0059 | train acc 0.9621 | val loss: 0.007485 | val_acc: 0.9771For the train dataset I used the weighted cross entropy as loss function since my data... | KFrank | Hi Azeai!
There are a number of possible reasons for this:
(First, a quick note: One would normally expect your model to perform
at least a little better on the training data.)
The character of your training and validation datasets could be
different. For example, maybe your validation image… |
Marek_Balaz | Hello, I would like to multiply tensor t1 = torch.tensor([1, 2, 3, 4, 5]) and t2 = torch.tensor([1, 2, 1]) in order to get result similar like from 1D kernel application: [1 * 1 + 2 * 2 + 3 * 1, 2 * 1 + 3 * 2 + 4 * 1, 3 * 1 + 4 * 2 + 5 * 1]. Can you give me advice, how to compute this case without any for loop?Thank yo... | KFrank | Hi Marek!
Useunfold()to generate the correct “slices” of t1:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> t1 = torch.tensor([1, 2, 3, 4, 5])
>>> t2 = torch.tensor([1, 2, 1])
>>> t1.unfold (0, 3, 1) @ t2
tensor([ 8, 12, 16])
You could also useconv1d()if you unsqueeze() t1 and t2 to add
… |
ivo-1 | Hello,I am using the ResNet architecture as a feature extractor for an OCR task. While debugging I noticed that the output values of ResNet are very similar for any input image out of my dataset. So I decided to look at the output values when an untrained ResNet is given random input.resnet = torchvision.models.resnet1... | KFrank | Hi Ivo!
I can reproduce what you see.
I don’t see anything wrong with this result (although I don’t have
an expectation one way or the other whether it should work out
this way).
My intuition – that could be wrong – suggests that pumping a
random input through a randomly-initialized Res… |
talipturkmen | Hello,Firstly I’m very sorry with this newbie question. I couldn’t find an efficient answer. I want to create a mask with zeros and ones for the n by n matrix. For value each i-th row I want to set the columns between i-a and i+a to 1 and rest of them to 0.As an example of the valuesn = 4 (4x4 matrix)a = 1I want to get... | KFrank | Hi Talip!
I think thattorch.tril()and/ortorch.triu()will be the key to what you want.
Here is one specific approach:
>>> torch.__version__
'1.6.0'
>>> n = 4
>>> a = 1
>>> torch.tril (torch.ones ((n, n)), a) * torch.triu (torch.ones ((n, n)), -a)
tensor([[1., 1., 0., 0.],
[1., 1., 1.,… |
omer_as | Hey all,I have a tensor t with shape (b,c,n,m) where b is the batch size, c is the number of channels, n is the sequence length (number of tokens) and m a number of parallel representations of the data (similar to the different heads in the transformer).I want to perform a 1D conv over the channels and sequence length,... | KFrank | Hi Omer!
You can .reshape() your input tensor and use the groups constructor
argument of Conv1d:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> _ = torch.manual_seed (2021)
>>> b = 2
>>> c = 3
>>> n = 5
>>> m = 2
>>> t = torch.rand ([b, c, n, m])
>>> u = t.permute (0, 3, 1, 2).reshape (b, m … |
Aditya_Prakash | In my neural network (RNN), I am defining the loss function such that the output of the neural network is used to find the index (binary) and then the index is used to extract the required element from an array which in turn will be used to calculate MSELoss.However, the program givesparameter().grad = Noneerror which ... | KFrank | Hi Aditya!
I haven’t looked at your code or error messages in any detail.
But, yes, your “graph is breaking.”
code, as a function of output, is not (usefully) differentiable, so,
regardless of what you subsequently do with code, you won’t be
able to back propagate through it.
I have no idea … |
Ada | My network threw an error during backprop because layer shapes did not match, and I wondered how/why the network was able to do the forward pass without throwing an error. After investigating, I’ve discovered some weird behavior.If the model is on the CPU, all is well:model = nn.Linear(100,1)
x = torch.randn(1,200)
mo... | KFrank | Hi Ada!
This appears to be a known bug that has recently been fixed. See
this thread:
Best.
K. Frank |
xianqian | If we have a tensor like this[[True, False, False,False],
[False,False,False,False],
[True,True,False,False],
[[True,True,True,True]]The check should returnTrue. But in case there is something like this[[True, False, True,True], <--- wrong
[False,False,False,False],
[True,True,False,False],
[[True,True,True,True]]shoul... | KFrank | Hi Xianqian!
cumprod() – for boolean values – will test for “decreasing values”:
>>> import torch
>>> torch.__version__
'1.9.0'
>>>
>>> b1 = torch.tensor ([
... [True, False, False, False],
... [False, False, False, False],
... [True, True, False, False],
... [True, True, Tru… |
miturian | I apologize if this is adequately explained in the documention. If so, please just give me a link…I have only foundDoes PyTorch average or sum gradients over a minibatch?autogradFor example when you retrieve the gradients like so:
loss = F.nll_loss(output, target)
loss.backward()
for key, value in model.named_paramete... | KFrank | Hi Miturian!
I think you’re trying to say something slightly different, so let me
rephrase it:
x is a batchSize-2 “input” to the “model”; w is the (scalar) weight
that defines this very simple “model”.
Yes.
Yes, but I think it’s more helpful to think of this as a “tensor” chain
rule, rathe… |
andreys42 | HelloIm wonder why NLLLoss doesn’t change when using [2,2] weights in example below?There is really incomplete documentation related to details of calculations.log_prob = torch.tensor([[0.1, 0.5],
[0.8, 0.8],
[0.8, 0.1]])
target = torch.tensor([0, 0, 1])
weight = torc... | KFrank | Hi Андрей!
You have two mistakes in your calculation: First, NLLLoss does not
take the log() of its input, but you do in your manual calculation.
Second, when you manually calculate the weighted average, you
should be dividing by 3 * 2 (not (3 * 4)). Thus:
>>> import math
>>> import torch
>>>… |
matthewleigh | Hey everyone,I have a minor issue and I am not sure if it is a bug or I am simply not understanding something. But I noticed that in my project I was getting some strange results for certain configurations and error messages not popping up when expected.To boil it down, I am allowed to multiply matrices of incompatible... | KFrank | Hi@ptrblck!
I can confirm that the issue has been fixed in the current nightly (that
is, the cuda version also throws the shape-mismatch error):
>>> torch.__version__
'1.10.0.dev20210830'
>>> torch.nn.Linear (3, 3).cuda() (torch.randn (5, 10).cuda())
Traceback (most recent call last):
File "<s… |
thomas | Hello everyone!I have an input of this shape:(num_samples, num_symbols, num_features, num_observations)I would like to feed through this input through a neural network.The neural network as(num_features, num_observations)shape input and(num_outputs)outputs, giving me(num_samples, num_symbols, num_outputs)when I apply a... | KFrank | Hi Thomas!
I do not know of any functionality built into pytorch similar to your
apply_along_axis(). And even if there were, it would still impose
a performance penalty, as it would still be breaking up what might
have been a single, larger tensor operation into many smaller, axis-wise
tensor… |
Sitaraman | Hi,Here is my code, on training the logits dont seem to change at all. What could be the reason?from dgl.nn import GraphConv, SAGEConvclass GCN(nn.Module):definit(self, in_feats, h_feats, num_classes):super(GCN, self).init()#self.conv1 = GraphConv(in_feats, h_feats, allow_zero_in_degree=True)#self.conv2 = GraphConv(h_... | KFrank | Hi Vilayannur!
I haven’t looked at your code in any detail, however:
“breaks the computation graph” because
Variable(loss, requires_grad = True) creates a new tensor
(that also happens to be called loss), and (by design) gradients
backpropagated to the new loss don’t get further backpropagate… |
julliet | I have a binary classification problem. Right now I’m using several linear layers with ReLU activation.I’m using BCEWithLogitsLoss() for Loss, so I’m not implementing any Softmax on the layers.Predictions of the model look something like this:-0.2443, 6.6122, 25.0909, ..., -62.7383, 0.3066, 61.6255So I can’t rea... | KFrank | Hi Julia!
In terms of comparing your predictions to the “zeroes and ones” of
your label, BCEWithLogitsLoss does precisely this (without converting
your predictions into 1s and 0s).
BCEWithLogitsLoss takes predictions that are raw-score logits
(such as those produced by your final Linear layer … |
abhisek | Trying to implement Tversky metric as follows:import torch
def tversky_score(
predictions,
targets,
alpha=0.5,
beta=0.5,
eps=1e-16,
encode_target=True
):
"""
Ref A: https://arxiv.org/abs/1706.05721
alpha = beta = 0.5 : Dice coefficient
alpha = beta = 1 : T... | KFrank | Hi Abhisek!
Could you post a trimmed-down, runnable, fully-self-contained script
that reproduces the error? (Please have the script print out the version
of pytorch you’re using, torch.__version__.)
Please provide hard-coded (or random) sample data (with size and
dimensionality as small as po… |
Chris_XU | Hi, I would like to understand the cross entropy loss for multi-dimensional input by implementing it by myself. Currently I am able to get the close result by iterating usingnp.ndindex,K = 10
X = torch.randn(32, K, 20, 30)
t = torch.randint(K, (32, 20, 30)).long()
w = torch.randn(K).abs()
CrossEntropyLoss(weight=w, re... | KFrank | Hi Chris!
You can get a tensor of weights corresponding to the class labels
in t by indexing into w, and you can get a tensor of (negative)
log-probabilities by calling .take_along_dim() with t as the
argument:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> _ = torch.manual_seed (2021)
>>> … |
kabu1204 | docs:torch.nn.KLDivLosswhich I think should be:图片3550×452 46.2 KB | KFrank | Hi Kabu!
No, the documentation for KLDivLoss is correct.
The equation you posted an image of contains the term:
y_n (log y_n - x_n)
You are expecting log x_n rather than just x_n. But KLDivLoss
expects x_n to be already a log-probability. Quoting from the
documentation you linked to:
As w… |
EricPengShuai | Is it impossible to install version 0.3.0 or 0.3.1 of pytorch on Windows now? | KFrank | Hi Shuai!
I was able to install and run pytorch 0.3.0 on windows 10. (My
motivation was to run pytorch on an old laptop gpu, and 0.3.0
was the newest version of pytorch I could find that was pre-built
with support for my old gpu.)
See this post from@ptrblckwhere he gives a link to some “leg… |
ArshadIram | I am trying to optimize over the value z and netG is trained GAN model.Here is the code. I am getting an error. I want to min the loss between the generated images x and the z. something like this:maxEpochs = 100
z = nn.Parameter(torch.rand(64,100,1,1), requires_grad=True).to(device)
opt = torch.optim.Adam([z]).to(devi... | KFrank | Hi Iram!
Looking at an object’s __dict__ property is often a good way to
probe all of its properties. So start with:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> opt = torch.optim.Adam ([torch.randn (3, requires_grad = True)])
>>> opt.__dict__
{'defaults': {'lr': 0.001, 'betas': (0.9, 0.9… |
ph14 | How does the functiontorch.randngenerate variates? What specific method does it use, and where can I find a reference (if there is one)? Also, does the method change based on CPU/GPU usage? | KFrank | Hi Piers!
As near as I can tell, randn() uses theBox-Mullermethod, both on
the cpu and gpu.
I am not aware that the algorithm used is documented anywhere
but in the code. It’s also quite opaque to me how any given pytorch
python call gets dispatched down to the code that actually does the
… |
MrPositron | Hi all!I am stuck at one problem. Let say that that I have tensors A and B. Now, I want to update elements in A at locations given in tensor B.For example, let say there are two tensors A and B with size 3 x 6, and 3 x 2.A = [
[1, 2, 3, 4, 5, 6],
[2, 3, 4, 5, 6, 1],
[3, 4, 5, 6, 1, 2],
]
B = [
[0, 1],
... | KFrank | Hi Nauryzbay!
You may usescatter_add_()(with pytorch tensors) for this:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> A = torch.tensor ([
... [1, 2, 3, 4, 5, 6],
... [2, 3, 4, 5, 6, 1],
... [3, 4, 5, 6, 1, 2],
... ])
>>> B = torch.tensor ([
... [0, 1],
... [0, 3],
... … |
PhysicsIsFun | Greetings,I am confused by PyTorchs usage of the momentum SGD method.https://pytorch.org/docs/stable/generated/torch.optim.SGD.html#torch.optim.SGDThe formulas state thatv_{t+1} = \mu * v_{t} + g_{t+1}
p_{t+1} = p_{t} - lr * v_{t+1}The documentation remarks that this differs from the original formula used by Sutskeve... | KFrank | Hi Physics!
The two formulations are equivalent. Let’s call the “velocity” in the
first, pytorch, formulation vPytorch_{t} and in your second proposed
version vPhysics_{t}. The two formulations only differ in a redefinition
of v, namely vPhysics_{t} = -vPytorch_{t}, that drops out of the
fin… |
John_Doe | Hello,I am trying to implement a BCEWithLogitsLoss version with a different weight for some pixels. The goal is to have good borders in a segmentation task.The outputs of my net are logits.My weight map have the same size as my target. (For example [batch_size, height, width]).My implementation currently looks like thi... | KFrank | Hi John!
I would recommend that you use BCEWithLogitsLoss’s weight
argument:
mean_weighted_loss = torch.nn.BCEWithLogitsLoss (weight = pix_map) (pred, target)
As a further comment: You can certainly write your own version of
BCEWithLogitsLoss, but if you do, you should, for reasons of
nu… |
Patrickens | Dear All,Im working on a simulation algorithm where the linear algebra is handled bypytorch. One step in the algorithm is to do a 1d convolution of two vectors. This needs to happen many times and so it needs to be fast. I decided to try to speed things further by allowing batch processing of input. This means that I s... | KFrank | Hi Tomek!
Package your nbatch dimension as “channels” (in_features)
and then use conv1d()'s groups feature so that you apply each
weight vector in your batch of weight vectors separately to the
corresponding “channel” of your input.
Here is your code with the “groups” version added on at the e… |
wasabi | I have a tensor X of shape (a, b, c) and a matrix of permutation (not a permutation matrix) P of shape (a,b), where each row of P is an output of torch.randperm(). I want to shuffle X in the following way:for i in range(a):
Y[i] = X[i][P[i]]
return Ywhat’s the best way to achieve this? Thanks. | KFrank | Hi Wasabi!
Use gather():
>>> import torch
>>> torch.__version__
'1.9.0'
>>> _ = torch.manual_seed (2021)
>>> a = 2
>>> b = 3
>>> c = 5
>>> X = torch.arange (a * b * c).reshape (a, b, c)
>>> X
tensor([[[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]],
[[… |
Magjo | Hi,I have difficulties to understand why this code does not throw errormodel = torch.nn.Linear(512,2)
opt = torch.optim.SGD(model.parameters(), lr=0.1)
inputs = torch.rand((32,512))
outputs = torch.rand((32,2))
opt.zero_grad()
pred = model(inputs)
pred[:,1] = torch.sigmoid(pred[:,1])
loss = torch.nn.functional.mse_l... | KFrank | Hi Magjo!
I’m guessing … (But it’s the weekend, so let me guess away!)
At issue is not only whether you are using an inplace operation,
but also whether the tensor modified by the inplace operation is
used directly in the backward() computation.
The derivative of relu() depends on the sign o… |
Yongjie_Shi | I have two networks, for example, netA and netB. However, I want to use different loss functions to update different networks. For example, I want to use loss1 to update netA, and use loss2 to update netB.I have defined different optimizers for netA and netB. Each optimizer optimizes only the parameters of the correspo... | KFrank | Hi Yongjie!
Your process it mostly correct. You need to use retain_graph = True
in your first backward() call:
loss1.backward (retain_graph = True)
No, one forward pass is enough. (You do, of course, have to calculate
both loss1 and loss2.) But you do need two backward() passes.
(If you w… |
joec | Hi, I am seeing an issue on the backward pass when using torch.linalg.eigh on a hermitian matrix with repeated eigenvalues. I was wondering if there is any way to obtain the eigenvector associated with the minimum eigenvalue without the gradients in the backward pass going to nan. I am performing this calculation as a ... | KFrank | Hi Joe!
The short answer: No, there is not.
The issue is that in the presence of repeated (degenerate)
eigenvalues, “the eigenvector associated with” a degenerate
eigenvalue is not well defined.
An eigendecomposition algorithm (such as torch.linalg.eigh())
will give you a list of eigenvalues… |
Samuel_Bachorik | Hi this is my code for solving quadratic equation. This is working fine but problem is when I try to add one more unknown.x = torch.nn.Parameter(torch.zeros(1), requires_grad=True)
def model(x):
b=3
a=2
c=1
global y
y = a*x ** 2 + b*x + c
return y
optimizer = torch.optim.Adam([x], lr=0.1)
for... | KFrank | Hi Samuel!
Consider the following:
>>> import torch
>>> torch.__version__
'1.9.0'
>>>
>>> # your scalar x = z[0] and y = z[1]
>>> z = torch.nn.Parameter (torch.tensor ([3.0, 7.0])) # just to make it more interesting than 0.0
>>> equationCoefficients = torch.tensor ([[1.0, 1.0], [1.0, -1.0]])
>>>… |
tianle-BigRice | I needed to optimize my own loss using the Optimizer, but I ran into this problemTraceback (most recent call last):
File "train.py", line 138, in <module>
fire.Fire()
File "D:\Anaconda3\lib\site-packages\fire\core.py", line 141, in Fire
component_trace = _Fire(component, args, parsed_flag_args, context, nam... | KFrank | Hi Tianle!
What do you think this error message might be telling you?
If you were debugging somebody else’s code, what issues might
this error message suggest you take a look at?
This entry in your params list is a dictionary that contains a Parameter.
Does this make sense?
But this entry i… |
lavish619 | I am using a pretrained resnet101 and I want to change the dilation rates and stride of some conv layers.If I initialize the layers again, that will change the weights of that layer, but incase of stride or dilation rate change only, the weights should not get changed because the kernel size is same.So how can I change... | KFrank | Hi Lavish!
If it were me, I would probably do:
for i in range(23):
saveWeight = self.resnet.layer3[i].conv2
self.resnet.layer3[i].conv2 = nn.Conv2d (256, 256,
kernel_size=3,
stride=1,
… |
Alef93xx | Hey guys!I’m trying to train a neural network for multiclass semantic segmentation (FCN) using the CrossEntropyLoss function, but the following error occurs:Preds: torch.Size([1, 21, 160, 240])Target: torch.Size([1, 3, 160, 240])The size of tensor a (21) must match the size of tensor b (3) at non-singleton dimension 1A... | KFrank | Hi Alisson!
Let me make a number of comments before outlining how one
might convert RGB colors to integer class labels,
First, just to use a clear-cut word, let me call your ground-truth,
annotated (labeled) images “masks.” So your dataset consists
of a bunch of images that will be input to y… |
_joker | Hi All,I have a very simple use case where I would like to predict a floating number (y), given four floating numbers (x1, x2, x3, x4) that denotes the property of a process. I would like to have some pointers or insights on different supervised and unsupervised approaches to solve this problem and which one among the ... | KFrank | Hi Joker!
First, especially because your xs differ in scale by several orders
of magnitude, you should most likely normalize your input data to
be or order one. This makes it easier for your training to get started,
and your model doesn’t have to “learn” to deal with these very different
scal… |
Bahman_Rouhani | I want to apply a mask to my model’s output and then use the masked output to calculate a loss and update my model.I don’t want the autograd to consider the masking operation when calculating the gradients, i.e. I want the autograd to treat my model as if it had outputed the masked version of my input. In other words, ... | KFrank | Hi Bahman!
Your code should do what you want. Autograd tracks computations
with pytorch tensors and doesn’t care whether those computations are
“free standing” (such as your mask operation) or part of your model or
part of your loss – they’re all treated the same.
If mask has 0s in it, then w… |
Samue1 | I have a tensorTwith dimensions(batch_size, size_n, size_n)T =
[[[0.9527, 0.8821],
[0.8442, 0.6147]],
[[0.0672, 0.5737],
[0.1963, 0.4532]],
[[0.0992, 0.3838],
[0.4169, 0.0925]]]and want to extract the diagonal of each matrix in that batch to getdiag_T =
[[0.9527, 0.6147],
[0.0... | KFrank | Hi Samuel!torch.diagonal()does what you want:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> T = torch.tensor (
... [[[0.9527, 0.8821],
... [0.8442, 0.6147]],
... [[0.0672, 0.5737],
... [0.1963, 0.4532]],
... [[0.0992, 0.3838],
... [0.4169, 0.0925]]]
... )
>>> torch.… |
SebGruber1996 | Hi!When I define the following functions ‘n_deriv_’ (calling ‘jac’ recursively) and ‘n_deriv__’ (calling ‘grad’ recursively in a for loop), they work without issues:import torch
from torch.autograd.functional import jacobian as jac
from torch.autograd.functional import hessian as hes
from torch.autograd import grad
de... | KFrank | Hi Sebastian!
Your error is caused by python scoping rules and is not specific to
pytorch nor torch.autograd.functional.jacobian.
Please see this python FAQ:Why do lambdas defined in a loop with different values all return the same result?Here is a tweaked version of your code that shows how… |
avitase | Hi:)I want to calculate the inverse FFT of a truncated input vector,Python 3.8.10 (default, May 19 2021, 18:05:58)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> x = torch.rand(5)
>>> fx = torch.fft.fft(x)
>>> fx
tensor([3.2079+0.0000j,... | KFrank | Hi Avitase!
Pytorch’s fft functions, including ifft(), pad by simply appending zeros
to the end of the input vector – they don’t insert zeros into the middle.
You can get the behavior I believe you want by using rfft() / irfft().
The following illustrates these two points:
>>> import torch
>>> … |
Vignesh_Baskaran | I am trying to understand the discrepancy that happens while performing matrix multiplication in batch.To summarize I am trying to do the following:matmul(matrix, tensor) → Slice the output → sliced outputslice the input tensor → matmul(matrix, sliced_tensor) → sliced outputI expect the results to match exactly but th... | KFrank | Hi Vignesh!
Yes, such a discrepancy is to be expected due to floating-point
round-off error.
In short, when you use floating-point arithmetic to perform operations
in different orders that should be mathematically equivalent, you, in
general, expect to get (slightly) different results.
In p… |
Samue1 | Given a one-dimensional input tensorS, I want to evaluate the following expression:J_ij = S_i(delta_ij - S_j)wheredelta_ijrepresents the Kronecker delta. The resultJof this expression is a square matrix. I would like to know how I can efficiently evaluate this expression using PyTorch? My current implementation is very... | KFrank | Hi Samuel!
No. If you had tried it, you would have discovered that torch.outer()
does not accept multidimensional tensors.
No, this will throw an error (because you pass a multidimensional
tensor to torch.outer()).
You can, however, use pytorch’s swiss army knife of tensor
multiplication fu… |
lkp411 | Is there a way to efficiently, in a vectorized manner, compute the combinations along each rows of a 2D tensor individually?For example:a = torch.tensor([[2, 5, 6], [7, 9, 4]])
result = torch.combinations(a, 2, dim=1)results should look liketorch.Tensor([[[2, 5],
[2, 6],
[... | KFrank | Hi lkp411!
Yes, the idea would be to construct the combinations of a 1D vector
of indices and then index into your multidimensional tensor, swapping
the dimensions around appropriately.
Like this:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> a = torch.tensor([[2, 5, 6], [7, 9, 4]])
>>> a… |
Samue1 | I have a batchx = torch.rand(size=(M, N))and want to create for each of theMinputs a diagonal matrix with dimensionsN x Nsuch that the output has dimensionsM x N x N. How can I do that? If I passxtotorch.diagI get a one-dimensional output.Any idea what I do wrong? | KFrank | Hi Samuel!
Try:
torch.diag_embed (torch.rand (size = (M, N)))
Best.
K. Frank |
WilliManFR | Hello,I have a problem. I have done a CNN which gives me an output of the form : (BATCH_SIZE, 1, HEIGHT, WIDTH). However, in order to apply the CrossEntropyLoss function, I need an output of the form, (BATCH_SIZE, NB_CLASS, HEIGHT, WIDTH). How can I get such a matrix from my original output? I currently have three clas... | KFrank | Hi William!
As an aside, it sounds like your current CNN performs binary (i.e.,
background-foreground) segmentation.
It sounds like your desired use case is multi-class (with NB_CLASS
classes) semantic segmentation.
First, once you’re down to (BATCH_SIZE, 1, HEIGHT, WIDTH), that
is, a singl… |
masteryoda | I have atensor with multinomial probabilities. Each vector (in my example below is 1x3) inside the tensor represent multinomial probability distribution for 1 random variable:I want to sample from the multinomial probability distributiontensor of random variables.For example, this is the tensor (MxNxIxJx3) with the mul... | KFrank | Hi Yoda!
As I understand your question, you are asking for the categorical
distribution (which is a special case of the multinomial distribution).
torch.distributions.Categorical take batches of probs (as does
torch.distributions.Multinomial), so you can just pass your probs
in as-is.
Here is… |
drbeethoven | Hello,I am trying to create a method that allows me to create a nn of variable number of layers and size. As such, I am using a module list.However, I notice that when I used “nn.Linear” before using a module list, I would have to specify Sigmoid in between layers and soft max at the end. The soft max I can just put at... | KFrank | Hi James!
I’m not entirely sure what you’re asking or how you intend to use
your ModuleList, but note that a torch.nn.ReLU is a Module
so you can include it in your ModuleList, in between, for example,
some torch.nn.Linears.
Best.
K. Frank |
metro | Hi there,I’m looking for a loss function which will motivate a network to output on the last layer either near 0 or near 1 values. I’m imagining a function that looks similar to this. The output layer is of type float/double and will be used as a mask.Background:I’m training an unsupervised network to predict masks. My... | KFrank | Hi Metro!
I don’t understand your use case, but, in general, you can certainly
penalize outputs that are not close to 0 or 1.
Let x be a single output. You could then try things like:
penalty_0_1 = (x * (1.0 - x))**2
penalty_0_1 = torch.abs (x * (1.0 - x))
penalty_0_1 = ((x * (1.0 - x))**2)**a… |
NPC | Hey,i am sorry if i missed a similar topic.I want to skip a weight in a convolution layer. (I know bad description).Lets say i have a kernel like [a, b, c].But i want a == c (or more precisely I want the optim. to threat it as one parameter).Is there a proper way to archive this?I am currently just setting them to (a ... | KFrank | Hi NPC!
To me the conceptually cleanest approach would be to build your
constrained kernel from a separate two-element Parameter that
you actually optimize. Something like:
import torch
from itertools import chain
# initialize a = 1.1, b = 2.2
k = torch.nn.Parameter (torch.tensor ([1.1, 2.2]… |
jhuteau | I want an efficient (vectorized) implementation instead of my current for-loop implementation.I have a MxN matrix named Sim corresponding to the similarity scores of M anchors with N documents.I have multiple negative (not matching the anchors) documents as well as multiple positive (matching) documents for each anchor... | KFrank | Hi Jhuteau!
Easy peasy:
import math
import torch
print (torch.__version__)
torch.manual_seed (20212021)
# code with tensor operations
def hardest_triplet_margin_lossB (preds, targets, margin, hardest_fraction):
# preds: the similarity scores, of shape [num_anchors, num-docum… |
phantom90 | Hi there,Just curios what will happen if the image on the disk changes when we run DataLoader to traverse the dataset. Will the loaded data be the latest file on the disk or otherwise.Thanks! | KFrank | Hi Phantom!
What will happen is whatever your code decides to do.
A torch.utils.data.DataLoader is a wrapper that lets you iterate
over a Dataset. Per the documentation, aDatasetis an abstract
class that you have to implement concretely. In particular, you have
to implement its __getitem__… |
lv_Poellhuber | So I have this network that has the following architecture:image1960×1464 527 KBThe goal of this architecture is to extract features out of a sequence of 30 frames, without knowing what those features are. The 30 frames are represented as images, but they aren’t real images, which is why we can’t have a classification ... | KFrank | Hi Louis-Vincent!
I haven’t looked at your code, but yes, in general the kind of thing
you propose doing should work just fine.
Make sure you understand the basics of how pytorch uses the
require_grad property of a tensor. Normally the weights, etc.,
of your model, and the tensors that depend… |
Shawn_Zhuang | Hi,in pytorch lightning, recently I found that if I use F.Dropout in forward step, even when I set mode to model.val, the dropout still work, then I realize I should replace it with nn.Dropout as module attribute. After that, everything performs normally.Then my concern would be like, if I use F.relu in forward instead... | KFrank | Hi Shawn!
F.relu() (which is to say torch.nn.functional.relu()) is a
function. nn.ReLU (torch.nn.ReLU) is a class that simply calls
F.relu(). These two ways of packaging the function do the same
thing, including when calling .backward().
There is no need to instantiate two instances of the n… |
Rohit_R | Say I create a placeholder for a batch of 3 images -batch = torch.zeros(3, 3, 256, 256, dtype=torch.uint8)I have my dummy image -image = torch.randint(size = (3,256,256), low=0, high=256)I then do -batch[0] = imageI am unable to understand the following outputs -id(batch[0]) == id(image)
out: FalseShould this... | KFrank | Hi Rohit!
Batch is a single “holistic” tensor of shape [3, 3, 256, 256]. It is
not a “collection” (in the sense of, say, a python list or dictionary) of
three 3x256x256 tensors.
Pytorch is doing some moderately fancy stuff with python here.
This is not simply assigning image to the 0 element… |
LearnedLately | I want to sample a tensor of probability distributions with shape (N, C, H, W), where dimension 1 (size C) contains normalized probability distributions with ‘C’ possibilities. Is there a way to efficiently sample all the distributions in the tensor in parallel? I just need to sample each distribution once, so the resu... | KFrank | Hi Learned!
Yes, you can use torch.distributions.Categorical, provided you
adjust your distributions tensor so that its last dimension is the distribution
dimension.
Here is an example script:
import torch
print (torch.__version__)
_ = torch.random.manual_seed (2021)
N = 2
C = 3
H = 5
W = 7
… |
Harimus | Hello, so I think showing the problematic behavior I’ve encountered first is best:Screenshot from 2021-05-19 19-01-111051×386 24 KBSo I’ve been training Policy-gradient (Reinforcement Learning) methods withTanhDistributions. Tanh distributions built-inlog_prob()method is very sensitive to the numeric value close to 1 &... | KFrank | Hi Dan!
This is a documentation bug. Quoting from pytorch’s1.8.1 documentation:
eps float The smallest representable number
such that 1.0 + eps != 1.0.
This is sort of on the right track, but really isn’t correct.Numpy’s (1.20) documentationgets it right:
eps : fl… |
Abhilash | I’m a beginner in Computer Vision, Pytorch and working on the multi class classification problem ( MNIST), how do I adjust the penalty for misclassifying, for example, a 5 as a 6, because a human would do similar mistake as they look pretty close ( for a terrible image), or 1 as 7 in few images. The weight parameter in... | KFrank | Hi Abhilash!
The most straightforward approach would be to use cross entropy as
your loss function, but to use probabilistic ("soft’) labels, rather than
categorical (“hard”) labels.
Pytorch does not have a soft-label version of cross-entropy loss built
in, but it is easy to implement one. Se… |
ZimoNitrome | Given a tensor of values in the range [0, 1], multiplying these values with a scalarpand applying a softmax gives scaled probabilities that sum to 1. Increasingppushes the values to either 0 or 1. See example:values = torch.tensor([0.00, 0.25, 0.50, 0.75, 1.00])
softmax_values = torch.stack([torch.softmax(p*values, 0)... | KFrank | Hi Zimo!
There are lots of possibilities. (You could choose between them by
imposing further conditions on the behavior of your function.)
Here is an illustration of one possible choice:
>>> import torch
>>> torch.__version__
'1.7.1'
>>> _ = torch.manual_seed (2021)
>>> def gradual (values, p)… |
krish13 | This topic seems to be widely discussed but I got a question. The document in the Pytorch indicate following formula:image1374×402 47.4 KBMy question is related to N.Let’s say my target size is [1* 1 * 10 * 10] - B,C,H,WThe output from my network is also [1* 1 * 10 * 10] - B,C,H,WIn this case N = 1. Thus, according to... | KFrank | Hi Krish!
As an aside, you should use BCEWithLogitsLoss rather than BCELoss
for reasons of numerical stability.
To answer your question, the documentation is a little imperfect on this
point. BCELoss simply computes the loss for each pair of matching
elements of the output and target tensors,… |
AerysS | I have a torch tensor of shape(batch_size, N). I want to apply functional softmax with dim 1 to this tensor, but I also want it to ignore zeros in the tensor and only apply it to non-zero values (the non-zeros in the tensor are positive numbers). I think what I am looking for is the sparse softmax.I came up with this c... | KFrank | Hi Aerys!
I didn’t look at the github code you linked to, but, in general, if you
have a (properly-written) torch.nn.Module or
torch.autograd.Function, you can instantiate it “on the fly” and
call it, rather than using it as a “layer” in a model.
Thus, for example:
probs = torch.nn.Softmax (d… |
weiguowilliam | I just started to use PyTorch and I plan to build an ensemble of networks. I implemented it with a list. But I got the following error:I’m confused by the error. The network has just 2 fc layers. Could you please help me explain that? Thanks in advance.Traceback (most recent call last):
File "test_list.py", line 107,... | KFrank | Hi Wei!
Your list_of_loss keeps growing with every iteration of the loops
over num_epochs and train_loader.
Therefore you keep calling list_of_loss[0].backward() on the
same loss over and over again that was created for the first sample
in your first epoch.
Put another way, the newly appended… |
AnhMinhTran | Hi guys, just wondering if it is possible to combine two different model training on different dataset into one?To illustrate my goalInkedannotation_LI3840×2880 489 KBFor model A: I have A.pthFor model B(red colour): I have B.pthIs it possible to combine them into one since the data is too skewed | KFrank | Hi Ahn!
You won’t be able to combine the two models together in some naive
way. The problem is that while model A has learned to distinguish a
“Worm” from a “Brittlestar” and model B has learned to distinguish a
“Prawn” from a “Seaspider,” neither model has learned to distinguish
a “Worm” fro… |
stevethesteve | At some point during computation, my model needs to compute the logarithm of softplus of a parameter.Currently, I implement this via:torch.nn.functional.softplus(theta).log()Due to the log() call I fear that there might be issues with computational stability.Is there a computationally more stable way of computing log-s... | KFrank | Hi Steve!
I haven’t worked through this in detail, but a first look suggests that
the softplus() fix in the recent nightlies addresses your issue.
Running the script you posted on today’s nightly, 1.9.0.dev20210504,
seems to show that the issue is gone:
1.9.0.dev20210504
diffA.abs().max() = te… |
jpj | I have a fully connected neural network with 78 input features and two hidden layers with 50 nodes each. Output with 7 nodes.self.hidden_layer_1 = torch.nn.Linear(78,50)
self.hidden_layer_2 = torch.nn.Linear(50,50)
self.output = torch.nn.Linear(50, 7)def forward(self, input):
weights = np.load('./weights.npy'... | KFrank | Hi jpj!
This is fine. At this point self.hidden_layer_1.weight is a tensor with
shape [50, 78]. (The order of the dimensions is correct because of
how pytorch multiplies batch tensors with weight tensors.)
This is your problem, You are replacing hidden_layer_1.weight, whose
shape is consis… |
akvilonBrown | Greetings!I’d like to ask for a suggestion from this venerable community on how I can handle a loss for a mulit-task network?The data goes forward in parallel in an Unet-like network with two heads performing semantic segmentation with different targets (not a multi-class configuration, the tasks differ).I was unable t... | KFrank | Hi Iaroslav!
Yes, it is perfectly reasonable to add the two losses together, and
there is no need to write a custom loss function.
So, something like:
loss_task_1 = torch.nn.CrossEntropyLoss() (pred_head_1, target_task_1)
loss_task_2 = torch.nn.CrossEntropyLoss() (pred_head_2, target_task_2)
to… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.