user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Harardin | I’m quite new in python and pytorch.I have perhaps simple problem.I get negative loss numbers returned.This is the output:Epoch [1/100], Step [10/63], Loss: 0.1118
Epoch [1/100], Step [20/63], Loss: -0.3783
Epoch [1/100], Step [30/63], Loss: -1.4037
Epoch [1/100], Step [40/63], Loss: -3.8306
Epoch [1/100], Step [50/63]... | KFrank | Hi Anton!
You are probably passing target values that are greater than one into
your MultiLabelSoftMarginLoss loss criterion.
min_max is read in from some unspecified data file, and then used as
the target for MultiLabelSoftMarginLoss, which expects its target
to consist of values that are ei… |
Wjk666 | Hi, I wish to usebcelossto calculate the prediction loss. But at the beginning of the training, the prediction is nearly about 1. Then as for the bceloss, it occurs some error. Looking forward to your help!For a toy example:import torch
import torch.nn as nn
a = torch.randn(512,4)
leakyrelu = nn.LeakyReLU(0.2)
att = nn... | KFrank | Hi Wjk!
Yes, this is a sensible thing to do.
This could also be an appropriate use case fortorch.clamp().
Note, however, you should only be doing this if the result you are forcing
to be <= 1.0 should already be mathematically no greater than 1.0, and
only exceed 1.0 because of round-off erro… |
arjung | I need to use KL Divergence as my loss for a multi-label classification problem with 5 classes (Eqn. 6 of thispaper). I have soft ground truth targets from a teacher network of the form [0.99, 0.01, 0.99, 0.1, 0.1] for each sample (since its a multi-label problem, a sample can belong to multiple classes), and predictio... | KFrank | Hi Arjung!
The short answer is use BCEWithLogitsLoss.
Several comments:
KL divergence and cross entropy are closely related. For fixed
targets, KL divergence and cross entropy differ by a constant that
is independent of your predictions (so it doesn’t affect training).
You should understand … |
Zhihan_Yang | In a classification task where the input can only belong to one class, the softmax function is naturally used as the final activation function, taking in “logits” (often from a preceeding linear layer) and outputting proper probabilities.I am confused about the exact meaning of “logits” because many call them “unnormal... | KFrank | Hi Zhihan!
The short, practical answer is because of what you typically do with
the log-softmax of the logits. You pass them into a loss function such
as nll_loss(). (Doing this gives you, in effect, the cross-entropy loss.)
If you were to pass the raw logits into nll_loss() you would get an
… |
Legolas | I need help/advice/example regarding the approach in the development of PyTorch custom-loss function in NLP multiclass classification.The dataset looks something like this:TEXT LABELtext1 ‘AC’text2 ‘AD’text3 ‘BC’text4 ‘BC’text5 ‘BD’…the rest of the dataset…Labels ‘AB’ or ‘CD’ are impossible from the business perspectiv... | KFrank | Hi Ninoslav!
I have a few comments:
First, to reiterate, since you want to “look inside” you classes, drilling
down into what you call the “class components,” it seems unnatural to
me to treat this as a single-label, four-class problem rather than a
multi-label, two-class problem. By using yo… |
nikogamulin | After being able to find the minimum value with scipy.optimize, I tried to implement the logic to find the optimal values with torch. When I tried to run the optimizer, it returned nan values.This is the code that I used to find the minimum with scipy.optimize:def get_pow_geometric(f, angle, power):
return np.sign(... | KFrank | Hi Niko!
Your pytorch code raises, in effect, f (angle) to a power, while your
numpy code raises np.abs (f (angle)) to a power. When f (angle)
is negative and power is fractional, your pytorch code will return nan.
(As an aside, pytorch also supports the “**” syntax for exponentiation.)
Consi… |
kof123 | Hello everybody,I am looking for the following:Assume that I have a trainable tensor T of shape torch.size([8]).Now I would like to train that tensor but also to have the following constraint:the tensor sould be symmetric in the sense thatT[0] = T[7]T[1] = T[6],T[2] = T[5],T[3] = T[4].i.e. the tensor T consists of actu... | KFrank | Hi Kof!
I would not use a tensor of length 8 and attempt to constrain its first
half to mirror its second. Just use a tensor of length 4, and use each
of its 4 elements twice in your computations.
Here is an example:
>>> import torch
>>> torch.__version__
'1.7.1'
>>> T = torch.randn (4, requi… |
pedro-mgb | Hello!My question is the following:I have 2 3D tensors, and with one dimension in common.1st tensor dimensions: a x b x c2nd tensor dimensions: a x d x eI want to multiply these two tensors along the dimension they have in common (a), and such that their output will be a 4 d tensor (e.g. dimensions b x c x d x e). Pret... | KFrank | Hi Pedro!torch.einsumis the general-purpose tool for “contracting” various
indices of tensors. Here is an example:
>>> import torch
>>> torch.__version__
'1.7.1'
>>> a = 3
>>> b = 2
>>> c = 5
>>> d = 3
>>> e = 4
>>> t1 = torch.randn ((a, b, c))
>>> t2 = torch.randn ((a, d, e))
>>> tt = torch.… |
niko_e | Hello together,I’m working on a dataset for semantic segmantation. I’m doing some experiments with cross-entropy loss and got some confusing results. I transformed my groundtruth-image to the out-like tensor with the shape:out = [n, num_class, w, h].Then I generate my target tensor with this out-tensor:target = torch.a... | KFrank | Hi Nikolas!
Without knowing the values in your out tensor, it’s hard to know what
the loss should be.
However, please note that the input passed into CrossEntropyLoss
(your out – the predictions made by your model) are expected to be
logits – that is raw-score predictions that run from -inf to… |
Arthur-99 | when I do backward() to some non-scalar variables $y$, the shape of result is always the same as input $x$.Is there any method to get a y-shaped result?e.g.y = model(x) # x.shape: (B, 1), y.shape: (B, K)
y.backward(torch.ones_like(y))
x.grad.shape == x.shape # (B, 1)
>>> TrueBut what I want to get is$$\frac{\part y}{... | KFrank | Hi Fangyu!
I’m not sure that I understand your exact use case, but the beta-versiontorch.autograd.functional.jacobian()might be what you want:
>>> torch.__version__
'1.7.1'
>>> def my_model (x):
... return torch.arange (2 * x.numel()).reshape ((2, -1)) * x * x
...
>>> x = torch.tensor ([2.… |
kfiros | Hi,I have 2D tensor of matrices, i.e I have matrices_tensor in size NxNx3x3 such that for index (i,j), matrices_tensor[i,j,…] yields matrix in size of 3x3.I would like to do the following:For target Nx3x1, I would like to get output in size Nx3 such thatoutput = torch.zeros((N,3))for i in range(N):for j in range(N):out... | KFrank | Hi kfiros!torch.einsum()is your go-to tool when you want to sum multiplied slices
(“contract indices”) of tensors.
Here is an example script:
import torch
print (torch.__version__)
_ = torch.manual_seed (2021)
N = 5
m = 3
matrices_tensor = torch.randn (N, N, m, m)
target = torch.randn (N, … |
richieYT-wan | From the definition of CrossEntropyLoss:input has to be a 2D Tensor of size (minibatch, C).This criterion expects a class index (0 to C-1) as the target for each value of a 1D tensor of sizeMy last dense layer gives dim (mini_batch, 23*N_classes), then I reshape it to (mini_batch, 23, N_classes)So for my task, I reshap... | KFrank | Hi Richie!
Yes.CrossEntropyLosssupports what it calls the “K-dimensional case.”
Note, pytorch’s CrossEntropyLoss does not accept a one-hot-encoded
target – you have to use integer class labels instead.
Let’s call your value 23 length. Your input (the prediction generated
by your network) s… |
msee19018 | Hey guys, I want to make a simple classification neural network with pytorch’s autograd package. I have gone through some resources that helped me create the code. Problem is the code is not working I have tried some solutions but it does not work for me.I am trying to classify mnist dataset, I am building simple 4 lay... | KFrank | Hi Hamad!
First, I think going through an exercise like this is very worthwhile.
Taking the time to do “by hand” some of the things built in to pytorch
is a great way to really learn what is going on and will prove valuable
when you move on to tackling more complicated problems.
I have not gon… |
ADONAI_TZEVAOT | I have a huge matrix A. I want to zero diagonals 2,-2 and 4. Please may I know an efficient way to do this using pytorch? | KFrank | Hi Adonai!
You may usetorch.diagonal()to get a modifiable view into your matrix of
the desired diagonals, and then usezero_()to zero them out:
>>> torch.__version__
'1.7.1'
>>> A = torch.arange (36).view ((6, 6))
>>> A
tensor([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
… |
danishnazir | Hi I have a prediction of shape [1,1,136,100] where Class is one and Batch size is 1.My Label is of size [1,136,100]Label = [[[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0, 0,255,…]]]I am recieving cuda assert error.Further Trace is given asself.criterion = nn.CrossEntropyLoss(ignore_index=255)... | KFrank | Hi Danish!
Based on this I speculate that you are performing binary segmentation
of an image. That is, for each pixel in your sample image, you want to
predict whether it is “background” or “foreground.”
If so, you should use be using BCEWithLogitsLoss.
Let’s say that your sample images have … |
S_M | Hi all, I want to compute the cross-entropy between two 2D tensors that are the outputs of the softmax function.P=nn.CrossEntropyLoss(softmax_out1,softmax_out2)softmax_out1 and softmax_out2 are 2D tensors with shapes (128,10) that 128 refers to the batch size and 10 is the number of classes.the following error occurs:R... | KFrank | Hi S.!
The short answer is that you have to write your own cross-entropy
function to do what you want – see below.
There are two things going on here:
First, as Aman noted, the input to CrossEntropyLoss (your
softmax_out1) should be raw-score logits that range from -inf to
+inf, rather than p… |
ProGamerGov | I’m thinking of something liketorch.nn.ConstantPad2d()only instead a padding with a constant value, each value added by the padding is random. | KFrank | Hi Pro!
At the cost of generating a full random tensor, you could use a sentinel
value and torch.where():
>>> torch.__version__
'1.7.1'
>>> t = torch.ones ((2, 1, 3, 3))
>>> sentinel = 999.9
>>> p = torch.nn.ConstantPad2d (1, sentinel)(t)
>>> torch.where (p == sentinel, torch.randn (p.shape), p)… |
Augustas_Macys | In binary segmentation, should the mask be represented as a matrix of 0s and 1s where 0 is one class (background) and 1 is another class. Or should it be represented as matrix of 0s and 255s where again 0 is one class (background) and 255 is another class. Or it does not matter? | KFrank | Hi Augustas!
The short answer is yes, the mask should be 0s and 1s (and, yes,
it does matter).
Specifically, when you use pytorch’s BCEWithLogitsLoss (or its
numerically-less-stable cousin BCELoss), the target (mask) you
pass in should be a floating-point tensor of probabilities that range
fr… |
11179 | Hello,I want to make NLLLoss in pytorch to successfully treat multilabel target (e.g [0 0 1 0 1 1] ).However I’ve got error that this loss is not for multitarget,so I saw documents and find it considers input shape as (N,C) and target (N,).I want to see how pytorch calculate NLLLoss since it expects values from log_sof... | KFrank | Hello Changrok!
I’m not sure what you mean by “multitarget.”
If you are working on a multi-label, multi-class classification problem,
then you don’t want to be using NLLLoss (or CrossEntropyLoss).
You should use BCEWithLogitsLoss.
The key idea is that a multi-label, multi-class problem (say, n… |
Anshul_Tomar | The problem is that of text classification where each document can be identified with one or more labels (104). So given a prediction\hat{y}of size (batch_size, 104) and a multi-one hot vectoryof size (batch_size, 104) which consists of value 1 for the labels it contains and values 0 for the labels it does not contain... | KFrank | Hi Anshul!
You should use binary_cross_entropy_with_logits() with no
“reduction.” Thus:
torch.nn.functional.binary_cross_entropy_with_logits (prediction, loss_labels, reduction = 'none')
This will return a tensor of loss values of shape [batch_size, 104]
(neither summed, nor averaged, nor oth… |
vishak_bharadwaj | A General question in mind. If I was training a classification model that I would then want to use for inference, wouldn’t it always be preferable to have a softmax layer at the end, instead of a regular linear that is input into a cross entropy loss function?Wouldn’t the former make it easier to understand NN outputs,... | KFrank | Hi Vishak!
No. For reasons of numerical stability, it is better to have your model
output the logits from its final Linear layer so that pytorch can use thelog-sum-exp trick, either in CrossEntropyLoss or in LogSoftmax.
Yes, looking at probabilities rather than logits could be easier to
und… |
Tejan_Mehndiratta | Suppose I have a training set which consists of 4 classes and the number of samples belonging to the 4 classes is 20, 30, 40, 10 respectively. So should I pass the tensor torch.tensor([20,30,40,10]) / 100. to the weight argument of the loss function?Or should I calculate the values of the weight argument for each batch... | KFrank | Hi Tejan!
You have this backwards – you want to weight the less-frequent
classes more heavily in your loss function. The most common
weighting scheme would be the reciprocal of what you have,
100.0 / torch.tensor ([20.0 ,30.0 ,40.0 ,10.0])
My preference is to calculate the weights using the … |
AbsolutePytorchNoob | I’m training a simple XOR neural network to familiarize myself with PyTorch.My code is:class XOR(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(2,2)
self.fc2 = nn.Linear(2,1)
self.optimizer = torch.optim.Adam(self.parameters())
self.loss = nn.BCELoss()
self.lh = []
def forward(sel... | KFrank | Hi Dr. Noob!
You have a “hidden layer” with two “neurons.” I believe that this
does not have enough structure to capture XOR (and the quadratic
term embedded in it). Try adding a third hidden neuron:
self.fc1 = nn.Linear (2, 3)
self.fc2 = nn.Linear (3 ,1)
Please see this related post for… |
jpj | I have 5 classes. I’m using a softmax function and getting 5 probabilities in each row that add up to 1 in total.To calculate the loss do I just pick the column with the highest probability, assign it to the column number and then calculate loss. For eg: if column 1 has highest probability- that row is classified as Cl... | KFrank | Hi jpj!
Yes, you should useCrossEntropyLossas your loss criterions (and not
use Softmax because CrossEntropyLoss expects logits rather than
probabilities as its predicted input).
Best.
K. Frank |
learner47 | I am using PyTorch and am still quite new to the library.I have a relation between my input and output given byy = ax + b, whereaandbare sampled from some distribution (say Uniform), that is, they are random. I would like to train a network to predictxupon seeingyanda. I am employing a network, namedprobability_network... | KFrank | Hi Learner!
Then (barring other noteworthy details) I would understand this as a
multi-label, three-class classification problem.
To illustrate what I meant by “additional structure”, consider the mapping
between a set of three bits and the integers 0, …, 7, where, e.g., “011” is
the binary re… |
sureshj | Given an input, I would like to do multiple classification tasks.Each input needs to be classified into one of 5 classes. There are 6 such classification tasks to be done. I could build six separate Linear(some_number, 5) layers and return the result as tuple in the forward() function. Then call the loss function 6 tim... | KFrank | Hi Suresh!
This is a perfectly reasonable approach and will work fine. It may well
introduce de minimis inefficiency, but any such cost will be negligible
compared with the cost of backpropagation.
This is also fine. I would probably use this second approach – not for
efficiency reasons, bu… |
zzzf | I want to use ConfusionMatrix in pytorch_lightning.metrics:pytorch_lightning.metrics.functional.confusion_matrix — PyTorch Lightning 1.1.6 documentation.I’m working on a multi-class segmentation problem where my mask originally is RGB valued (N, 3, H, W) and I converted it into one-hot (N,#Class, H, W) for training. Ho... | KFrank | Hi zzzf!
There are a couple of ways of going about this. Probably the most
flexible and most logically straightforward will be to index into a lookup
table with your three-channel colors.
Here is a demonstration script:
import torch
print (torch.__version__)
# convert rgb mask to integer clas… |
davidsriker | I have the following loss function:class WeightedBCE(nn.Module):
def __init__(self, pos_w, neg_w):
super(WeightedBCE, self).__init__()
pos_w = torch.tensor(pos_w, dtype=torch.float, requires_grad=False)
neg_w = torch.tensor(neg_w, dtype=torch.float, requires_grad=False)
self.register... | KFrank | Hi David!
First, as an aside: I haven’t looked closely at your WeightedBCE code, but I
don’t see anything mathematically wrong with it. However, the for-loop over
label will slow things down in comparison with pytorch’s built-in BCELoss
(and the preferred BCEWithLogitsLoss).
Pytorch’s built… |
Kaustubh_Kulkarni | I am getting decreasing loss as well as accuracy. The accuracy is 12-15% with CrossEntropyLoss. The same network except with a softmax for the last layer and loss as MSELoss, I am getting 96+% accuracy. I really want to know what I am doing wrong with CrossEntropyLoss. Here is my code:class Conv1DModel(nn.Module):
... | KFrank | Hi Kaustubh!
These two lines of code are in conflict with one another.
Your loss_fn, CrossEntropyLoss, expects its outputs argument to
have shape [nBatch, nClass], and its y argument to have shape
[nBatch] (no class dimension).
On the other hand, your torch.argmax(i) == torch.argmax(j)
test s… |
chichi | I have a question for the following code:tensor_1 = torch.randint(0, 10, [5, 2], dtype=torch.float32)tensor_2 = torch.randint(0, 10, [4, 2], dtype=torch.float32)max_1 = torch.max(tensor_1[:, None, :1], tensor_2[:, :1])print(max_1.size())The output is: torch.Size([5, 4, 1])How this is computed? | KFrank | Hi Chichi!
The short answer is pytorch’sbroadcasting.
The arguments to max() have the following shapes:
tensor_1[:, None, :1].shape = torch.Size([5, 1, 1])
tensor_2[:, :1].shape = torch.Size([4, 1])
When broadcast, the two trailing 1s line up, the middle 1 of the first
argument gets broadcas… |
Sunil_Sharma1 | I am trying to minimise the mse loss with constrain loss but constrain was increasing instead of decreasing.then i tried to only minimise constrain then it throw following error.class Edge_Detector(nn.Module):
def __init__(self,kernel_size,padding):
torch.manual_seed(1)
super(Edge_Detector,self).__init__()
... | KFrank | Hi Sunil!
If you want your kernels to be equal to the non-textual G_x and G_y you
gave, why don’t you just set them to be equal, rather than try to “learn”
them?
In a related point, it is true that your G_x and G_y satisfy your desired
constraint, and, indeed, loss_constrain takes on its minim… |
PhysicsIsFun | Greetings,I am a bit confused by the documented formula for the negative log-likelihood loss:NLLL766×242 35.6 KBWhat are those x_(n,y_n) ? They say x is the input, but the loss is not calculated from the input. A loss should be calculated from the output and the target, should it not?Best,PiFedit: is the following assu... | KFrank | Hi Physics!
Yes, the terminology in the documentation is somewhat unfortunate.
The argument to the loss functions that pytorch refers to as input is
indeed the “output” of the network (or derived from it). I prefer to call
this the “prediction.” The loss function then compares the “prediction… |
jjhh | I made a function to compute the IoU loss of 2 spansdef iou_loss(pred_start, pred_end, target_start, target_end):
"""
pred_start, pred_end, target_start, target_end: b, *
"""
num_common = (
torch.minimum(pred_end, target_end)
- torch.maximum(pred_start, target_start) + 1
).clamp_min... | KFrank | Hi jjhh!
The short story is that torch.minimum() and torch.maximum() are not
differentiable at the special points where the arguments are equal.
The function abs (x) offers a simpler example. When x > 0, the derivative
is +1, while when x < 0, it’s -1. When x = 0, mathematically speaking,
th… |
sparseinference | I see a small numerical difference when finding the log probability with a Categorical distribution, but I can’t see why.First, find the logits and sample an action:logits = policy(state).log_softmax(-1)
m = torch.distributions.Categorical(logits=logits)
action = m.sample()Now get the log probability of that action in ... | KFrank | Hi Peter!
If I understand your question correctly, I think that you’re missing the
fact that:
torch.distributions.Categorical (logits = logits)
and:
torch.distributions.Categorical (probs = torch.softmax (logits, dim = -1))
return essentially the same (up to floating-point round-off) distrib… |
oasjd7 | In torch version: 1.0.0, there is no ‘scatter’ function.How can I use this ‘scatter’ ? | KFrank | Hi oasjd7!
I’ve never used version 1.0.0, so I’m just guessing …
According to the1.0.0 documentationfor torch.Tensor the Tensor
class has an in-place .scatter_() method.
That is, you would call the .scatter_() method on an instance of the
Tensor class, making a copy of your Tensor, as necess… |
zeyuyun1 | Thispostand thisgithub pageexplains how to add an orthogonal constraint onto weight matrix. However, it doesn’t seems to work.In order to have a matrix A to be orthogonal, we must have (X^T X = I), thus, we can add |X^T X - I| in our loss. Here’s my code:#make a random vector
X = torch.rand(30,500).to(device)
#make a r... | KFrank | Hi Zeyuyun!
While this “orthogonality penalty” is zero if, and only, if X is orthogonal,
and is positive otherwise, it doesn’t work well for orthogonalizing X
with gradient descent, because its structure doesn’t fit* well with the
natural geometry of the set of orthogonal matrices.
Replacing t… |
harpalsahota | Hi There,I have a joint model with takes images and text as an input and produces two embeddings one for the image and the other for the text. Additionally, there is another branch of the network which takes the image embedding and via a single fully connected layer produces probabilities of certain classes existing in... | KFrank | Hi Harpal!
This detach() is wrong:
bce_loss(meta_preds.detach().cpu(), meta_cats_batch)
It “breaks the computation graph” in that it “detaches” meta_preds
from the computation of bce_loss() so that you don’t backpropagate
through, and optimize, the weights that were used to produce
meta_pre… |
Nich_010 | Hi, I’m currently attempting to re-implement a Tensorflow project using PyTorch. For reference, I’m currently utilizing the following virtual environment setup for the project:OS: Pop_OS 18.04 (Ubuntu 18.04 derivative)Python version: 3.6.9PyTorch version: 1.7.1+cu10CUDA version : 11.1Unfortunately, I’ve encountered a p... | KFrank | Hello Nicholas!
I think you have it backwards. Rather than being deprecated, it
appears that tile() is a new function.
I see tile() absent from the1.7.0 documentation, but present in the
master (unstable) documentation you linked to.
Here is tile() in a somewhat old nightly build:
>>> impor… |
Sam_Lerman | As the question is asked, e.g.:for param in model.parameters():
param.grad = 3.14
### do some additional compute
loss.backward()
optimizer.step()Will this add the new grads frombackward()on top of the manually set ones of 3.14? Or will it override the manually set ones? | KFrank | Hi Sam!
Yes, but remember to call optimizer.zero_grad() before setting
param (otherwise you will zero-out the value you set), and wrap
setting the params in a no_grad() block:
optimizer.zero_grad()
with torch.no_grad():
for param in model.parameters():
param.grad = 3.14
### do som… |
hoangcuong2011 | I have a simple code that generates a random tensor (float32). Then I compare each of the values in the tensor equal to the first number in the tensor. I got weird result where all True values are returning.import torchtorch.manual_seed(1)a = torch.rand(2, 10)tensor([[0.7576, 0.2793, 0.4031, 0.7347, 0.0293, 0.7999, 0.3... | KFrank | Hi Hoang!
Here a is only printed out to four decimal digits. That is, a[0][0]
is a number close to, but not actually equal to 0.7576. Perhaps
a[0][0] = 0.75758379.
Here you compare a[0][0] (as well as the rest of a) with 0.7576.
But a[0][0] is only approximately equal 0.7576 (equal only to … |
mishooax | Here’s my simple NN structure:class DNN(nn.Module):
def __init__(self,
input_layer_size: int,
hidden_layer_sizes: List[int],
dropout_rate: float,
debug: bool = False):
'''
Set up the network.
Args:
in... | KFrank | Hello Mishoo!
Yes. As you see, you can’t apply softplus() to a Linear. You need
to apply it to the output of the Linear, which is a tensor.
I would not append output_layer (nor output_layer_mean nor
output_layer_sigma) to linear_layers_list. Something like this:
output_layer_mean = … |
Hdk | How can I do this multiplication?Let´s assume two tensors:x= torch.ones(9,9)
y= torch.randn(3,3)xcan be be imagined as a tensor of9 blocks or sub-matrices, each of size(3,3).I want to doelementwise multiplicationof each block of (3,3) withy, so that the resultant tensor would havesize same as x.This task is analogous t... | KFrank | Hi Hdk!
Yes, I do believe that I misunderstood your goal.
Am I right that you want each block of what I called the “auxiliary block
matrix” to be a copy of your matrix y?
If so, I think that a new feature (as of 1.8?),torch.kron(), might do what
you need. Here’s an illustrative script:
impo… |
AlphaBetaGamma96 | Hi All,I was wondering if there’s a way to do an exclusive cumsum (like that implemented with Tensorflow’s cumsum). An example of this would be,tf.cumsum([a,b,c], exclusive=False) => [a, a+b, a+b+c] #standard cumsum
tf.cumsum([a, b, c], exclusive=True) => [0, a, a + b] #exclusive cumsumLet’s say I have a Tensor of [... | KFrank | Hi Alpha!
The best I can think of is to use pytorch’s “standard” cumsum() and
use roll() to right-shift the result:
>>> t = torch.tensor ([1, 2, 3])
>>> res = t.cumsum (0).roll (1, 0)
>>> res[0] = 0
>>> print (res)
tensor([0, 1, 3])
Best.
K. Frank |
szandala | I am learning to re-train Resnet, with one more layer of 9 classes on top of final 1000.I think I do not understand criterion function.criterian = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr = 0.0001, momentum = 0.9)
for epoch in range(20):
running_loss = 0.0
for X, Y in training:
... | KFrank | Hi Szandala!
The short story is that – for separate reasons – you are passing an
improper input and target to your CrossEntropyLoss criterion
function.
This is appropriate. You have a batch size of 1, with 9 predictions
for a nine-class classification problem.
This isn’t actually true.
You… |
Fly2Fly | Regular matrix multiplication:If I have N1 samples and N2 samples, their dimensions are both D.X1 = [N1,D], X2 = [N2,D]Calculate the similarity matrix between samples, I can useS = X2.mm(X1.T), where S = [N2,N1]But if X1 = [B,N1,D], X2 = [B,N2,D], and the B notes bathsize,If I want batch-wise calculation of matrix mult... | KFrank | Hi Fly!
Usetorch.bmm()(“batch matrix-matrix”), together withtorch.transpose()to line up the D dimensions properly:
S = torch.bmm (X1, torch.transpose (X2, 1, 2))
Best.
K. Frank |
over9k | Hello!Is there any requirement for labels for start from 0 all the way to 1, 2, 3, number of classes? Or can I have labels start from 1, for example?This is just a matter of having to apply a label encoder manually to the dataset or not.Thanks | KFrank | Hello Over!
Well, it depends on what you do with the labels.
In the common case that you useCrossEntropyLossas your loss
function, per its documentation, your labels (the target) must be
integer class labels that run from [0, nClass - 1], inclusive. That
is, the labels start from 0.
Best.
… |
Alice_NL | Dear community,I am trying to use the weights for the binary classification problem for CrossEntropyLoss and by now I am so lost in it….In my network I set the output size as 1 and have sigmoid activation function at the end to ensure I get values between 0 and 1. I assume it is probability in my case. If output is set... | KFrank | Hi Alice!
Let me answer your question(s) two different ways.
You could, but doing so would be overkill. You can just call the
function (or class) version of sigmoid() directly:
my_logits = my_model (my_batch)
with torch.no_grad():
my_probabilities = torch.nn.functional.sigmoid (my_logits)
… |
Rohit_Modee | I have tensor x shape = torch.Size([32, 69, 64]) and y = torch.Size([32, 69, 68, 64]). I want output to be torch.Size([32, 69, 68, 1]). matrix multiplication of [1,64] and [68,64] to [68,1]. | KFrank | Hi Rohit!
Try:
torch.einsum ('ijl, ijkl -> ijk', x, y).unsqueeze (-1)
The einsum() “contracts” over the “64” dimension, while the
.unsqueeze (-1) adds the trailing singleton dimension.
Best.
K. Frank |
grizzlycoder | Hello!I’m in my last year or undergraduate studies and I’m going to be joining graduate school next year, for which I am looking to buy a new laptop.I currently use Colab to run most of my machine learning projects mostly because of the free GPU, but as I’m starting to take on bigger projects I’m having to migrate to u... | KFrank | Hi Grizzly!
I don’t have a specific recommendation, but if you insist on getting a
laptop, I would suggest that you consider getting a “gaming” laptop.
Look for the biggest, fastest (nvidia, pytorch-compatible) gpu that you
are comfortable spending the money on.
However, there is a lot to be s… |
Giuseppe | Hy all, i have a problem in the code belowimport torch
import torch.nn as nn
from torch.optim import SGD, Adam
from torch.optim.lr_scheduler import StepLR
import numpy as np
from dataset import Dataset
from torch.utils.data import DataLoader
from torchnet.meter import AverageValueMeter
from torchnet.logger import Visdo... | KFrank | Hi Giuseppe!
You are calling the constructor for Sigmoid incorrectly, namely with
an explicit argument. (There is also the hidden self argument. That
is why the error message complains about two arguments.)
In more detail, torch.nn.Sigmoid is a class, while torch.sigmoid()
is a function (as … |
stark | I’m calculating the Dice score to evaluate my model for a binary image segmentation problem.The function I wrote in PyTorch is:def dice_score_reduced_over_batch(x, y, smooth=1):
assert x.ndim == y.ndim
# reduction over all axes except 0 i.e. batch
axes = tuple([i for i in range(1, x.ndim)])
intersectio... | KFrank | Hi Stark!
Flattening [64, 1, 128, 128] to [1, 1048576] mixes your batch
dimension in with your image dimensions.
Based on your comments and the comment in your code (rather than
on my absent knowledge of the Dice score), it seems that the Dice
score should be independent of how the image dimen… |
Bob_Li | Suppose I have a matrix e.g.A = tensor([[0, 1, 2], [3, 4, 5]]), and I have another tensor B e.g.B = torch.tensor([1, 5, 2, 4]), how can I multiply each scalar in A with B, to get C of shape [2, 3, 4] in this example? | KFrank | Hi Bob!
I believe you are asking for the generalized outer product. Please
try torch.ger() (torch.outer) with .reshape() or torch.einsum:
ABa = torch.ger (A.reshape([6]), B).rehshape ([2, 3, 4])
ABb = torch.einsum ('ij, k -> ijk', A, B)
These two versions should give you the same result. Do t… |
Michael_Lempart | Hi all,Iam wondering if I need to one-hot encode labels for a segmentation task when using BCEwithoutLogits?The pixels in my segmentation masks are either 0 (background) or 1(foreground).In some code examples I saw that labels where on-hot encoded, in others the output channel of the model is equal to 1.So I now Iam so... | KFrank | Hi Michael!
Please see my final comment in this reply to your other thread:
Best.
K. Frank |
granth_jain | Hi,I have a tensor and I want to calculate softmax along the rows of the tensor.action_values = t.tensor([[-0.4001, -0.2948, 0.1288]])as I understand cutting the tensor row-wise we need to specify dim as 1.However I got an unexpected result.can someone please help me in understanding how softmax and dim in softmax wo... | KFrank | Hi Granth!
The short answer is that you are calling python’s max() function,
rather than pytorch’s torch.max() tensor function. This is causing
you to calculate softmax() for a tensor that is all zeros.
You have two issues:
First is the use of pytorch’s max(). max() doesn’t understand
tensor… |
NightRain | Is there any difference between callingfunctional.mse_loss(input, target)andnn.MSELoss(input, target)?Same question applies for l1_loss and any otherstatelessloss function. | KFrank | Hi Night!
Roughly speaking, there is no difference.
Note, as written, this won’t work. This calls the MSELoss constructor
with invalid arguments. You need:
loss_value = torch.nn.MSELoss() (input, target)
# or
loss_function = torch.nn.MSELoss()
loss_value = loss_function (input, target)
That… |
Richard_S | Hello everyone, sorry for rookie question I’m starting to learn pytochthis is my simple 1 layer linear classifier :class Classifier(nn.Module):
def __init__(self, in_dim ):
super(Classifier, self).__init__()
self.classify = nn.Linear(in_dim , 1 )
def forward(self, features ):
final = ... | KFrank | Hi Richard!
As Prashanth notes, you could use BCELoss in place of
CrossEntropyLoss.
However, you’ll be better off removing the torch.sigmoid()
and using BCEWithLogitsLoss. Doing so will be mathematically
the same, but numerically more stable.
Thus:
class Classifier(nn.Module):
def __ini… |
localh | I am wondering how to deal with incongruent training and test labels with nn.CrossEntropyLoss.For an ultra minimal example say we have:logits = torch.tensor([-0.3080, -0.2961]).reshape(1, 2)
y = torch.tensor([0])
y_test = torch.tensor([2])
F.cross_entropy(logits, y)
F.cross_entropy(logits, y_test) # target is out of b... | KFrank | Hi Andrew!
The short answer:
Make sure that the classification model you build has outputs for all
classes in your classification problem.
An important note:
If your test set includes classes (“test labels”) that do not occur in
your training set (“training labels”), it will not be possible f… |
Luca_Viano | Hi!I was wondering which is the correct way to perform element wise binary classification using the BCEloss.My model outputs a tensor of shape (depth, width, length) and its last activation is an element wise Sigmoid.My target contains either 0 or 1 and has also shape (depth, width, length).I am currently computing the... | KFrank | Hi Luca!
As an aside, you will have better numerical stability if you use
BCEWithLogitsLoss and remove the final Sigmoid layer.
Consider using the pos_weight argument passed to the constructor
of BCEWithLogitsLoss to compensate for the rarity of “1” pixels.
A typical value for pos_weight to r… |
edshkim98 | Hello everyone,I am currently doing a deep learning research project and have a question regarding use of loss function. Basically, for my loss function I am using Weighted cross entropy + Soft dice loss functions but recently I came across with a mean IOU loss which works, but the problem is that it purposely return n... | KFrank | Hi Edward!
Yes, it is perfectly fine to use a loss that can become negative.
Your reasoning about this is correct.
To add a few words of explanation:
A smaller loss – algebraically less positive or algebraically more
negative – means (or should mean) better predictions. The
optimization step… |
fauxneticien | Hi all — I’m new to deep learning and PyTorch and am playing with some small examples to learn the ropes. I just wanted to check that I’ve implemented something correctly.I’m looking to use a CNN to detect whether there’s a quasi-diagonal line in an image of a distance matrix (1 = Yes, 0 = No), and if so where (t_start... | KFrank | Hey Nay!
I don’t really understand your overall use case – “test utterance,”
applying the model to a distance matrix – so I don’t have any
thoughts on your “real” problem
Three lower-level comments:
Your code for loss looks sensible and correct. (I’ll leave it up to
you as to whether at the … |
ccalafiore | I am training a model with nn.LogSoftmax(). Well, I am actually using torch.nn.CrossEntropyLoss() as loss funtion which combines nn.LogSoftmax() and nn.NLLLoss(). However, During the test phase, I want the model to output the probabilities, not the logs of probabilities. So, I would like to use nn.Softmax() for the te... | KFrank | Hello Carmelo!
You can do anything you want in your test phase, regardless of how
you trained your model. (Just make sure that your test-phase results
mean what you want them to mean.)
You say you use CrossEntropyLoss. The output of your model
should therefore be raw-score logits, and these … |
zeyuyun1 | I am relative new to pytorch. After doing a pretty exhaustive search online, I still couldn’t obtain the operation I want.My question is How do do matrix multiplication (matmal) along certain axis?For example, if I want to multiply a vector by a matrix, that would just be the following:a = torch.rand(3,5)b = torch.rand... | KFrank | Hello Zeyuyun!
The general-purpose tool for taking a product of (contracting) multiple
tensors along various axes istorch.einsum()(named after “Einstein
summation”).
(You can also fiddle with the dimensions to get them to line up as
needed and use matmul() or bmm().)
Here is a script that c… |
Johannes_L | Hey,I am trying to understand a example regarding training of a simple, fully connected net.The model is trained with the input “data”.output = self.model(data)
loss = F.nll_loss(output, target)
if loss.cpu().data.numpy()[0] > 10000:What is the loss.data doing? Somehow relating the loss to the input data?Thanks! | KFrank | Hi Johannes!
I’m not sure specifically what you’re asking, but here are some
comments:
In loss.cpu().data, data is a deprecated property that was used
to unwrap a Tensor from a Variable. (I believe this was prior to
pytorch version 0.4.0.)
It’s just a coincidence that the character string “d… |
meyro123 | Hi everyone,I’m currently trying to train a physics informed NN and I have a (probably very) simple question regarding autograd.My training samples are points in space and time, i.e. a two-dimensional tensor and my question is as follows. When I compute the gradient wrt. the training data, i.e.gradient = torch.autograd... | KFrank | Hi Fabian!
I don’t understand what you are saying here.
The following example script may answer part of your question:
import torch
torch.__version__
def f (x, y):
return x * y
x = torch.Tensor ([2.0])
x.requires_grad = True
y = torch.Tensor ([3.0])
y.requires_grad = True
u = f (x, y)
gr… |
kof123 | Hello everybody,that’s my first post, so please be kind!I am currently trying to implement the adjoint operation of a convolutional layer (in 2D and 3D).More precisely, let c be a convoltutional layer with a pre-defined kernel, e.g. a 3x3 kernel.What is the easiest and most efficient way of implementing the adjoint ope... | KFrank | Hello Andreas!ConvTranspose2dshould do what you want (at least in the plain-vanilla,
2d case – I didn’t check 3d or various stride / padding combinations).
Here is an example script:
import torch
torch.__version__
torch.random.manual_seed (2020)
cnva = torch.nn.Conv2d (1, 1, 3, padding = 1, … |
paula_gomez_duran | I have a batch = 256 of pair of vectors of dimension 32. The shape is so [256, 2, 32].What I would want would be to perform the dot product between each of the pair of vectors of the batch, so that I end up with a tensor of shape [256, 32].How should I do it ?Thank you in advance! | KFrank | Hi Paula (and Alex)!
Building on Alex’s suggestion, I believe that
X.prod (dim = 1).sum (dim = 1)
should do what you want.
Best.
K. Frank |
SiddharthSingi | I know its obvious why weights need to have gradient values, but I have a particular question about leaves and non leaves. Please read on, this question is not as long as it seemsSo I understand that the grad is not available for any intermediate node, only available for leaf nodes (However the reasoning is still not p... | KFrank | Hi Siddharth!
On the contrary, fc2.weight (and fc2.bias) are leaf tensors.
In the forward pass the values of fc2.weight do not depend on
the values of x (nor on the values in fc1). They only change (in
the conventional use case) when you call optimizer.step().
Are you imagining that only the … |
blade | I have a network with following architecturedef forward(self, W, z):
W1 = self.SM(W)
W2 = torch.argmax(W1, dim=3).float()
h_5 = W2.view(-1, self.n_max_atom * self.n_max_atom)
h_6 = self.leaky((self.dec_fc_5(h_5)))
h_6 = h_6.view(-1, self.n_max_atom, self.n_atom_features)
return h_6whereself.S... | KFrank | Hello Blade!
I have two networks that are trained together.
…
What you see is my downstream network: it takes in output of the upstream W
…
I want to turn them into either a one-hot vector or class labels W2
Once you turn the output of your upstream network into a one-hot
vector or a class… |
Eulerian | I’m trying to display the optimizer currently in use by the model for documentation purposes.So the following snippetoptimizer = torch.optim.SGD(model.parameters(), lr=1e-5)
print(optimizer)gives the following outputSGD (
Parameter Group 0
dampening: 0
lr: 1e-05
momentum: 0
nesterov: False
weight_de... | KFrank | Hi Nihal!
print (type (optimizer).__name__)
will do what you want.
(This is generally true for python objects, and is not specific to pytorch.)
Best.
K. Frank |
Huseyin | Hello,I have a problem where i would like to predict single class “d” [000001] and multilabel [ “d”,“z”] [010100] class at the same time in a classifier with LSTM. So I mean my final Network will be able to predict both single label and multilabel class.I want to know what would be the best aproach to this problem. Bec... | KFrank | Hello Hüseyin!
I think what you propose is correct, but I wouldn’t say it quite this
way.
Let’s say you have nClass classes, and you want to perform both
single-label and multi-label multi-class classification.
In order to have two “branches” you could have a final Linear layer
with 2 * nClas… |
Leockl | Using PyTorch, I am wanting to work out the square root of a positivesemi-definitematrix. I googled around for a PyTorch implementation but can’t seem to find the right one.This is what I have found:https://github.com/steveli/pytorch-sqrtm(this implementation appears to only work for positivedefinitematrices. I am afte... | KFrank | Hello Leo!
Perform the eigendecomposition of your matrix and then take the
square-root of your eigenvalues. (If any of your eigenvalues of your
semi-definite matrix show up as numerically negative, replace them
with zero.)
For more detail, see this post:
Best.
K. Frank |
Johnson_Mark | I have a tensorxsize ofBxCxHxWand a tensor y size ofB/2 xCxHxW. I want to perform multiplication between tensor x and tensor y such as the first part of tensor x (from 0 to B/2) will be modified by the result of the multiplicationduring forwarding, while the last part of tensor x is unchanged as the bellow figure.How t... | KFrank | Hello Johnson!
Try:
tensor_z = tensor_x * torch.cat ((tensor_y, torch.ones_like (tensor_y)), dim = 0)
Best.
K. Frank |
akib62 | Hello, I am usingsqueeze()before calculatingloss. My code is given below and giving an errorValueError: Target size (torch.Size([1, 256, 383])) must be the same as input size (torch.Size([1, 1, 256, 383]))def training_step(self, batch, batch_nb):
x, y = batch
y_hat = self.forward(x)
y_label = y.... | KFrank | Hi Akib!
cross_entropy() and binary_cross_entropy_with_logits take
targets (your y_label) with differing shapes, and, in fact, with
different numbers of dimensions.
If input (your y_hat) has shape [nBatch, nClass, height, width],
cross_entropy_loss() expects a target with shape
[nBatch, heigh… |
Hoodythree | Say I haveCclasses, and I want to get aC*Csimilarity matrix in which each entry is the cosine similarity betweenclass_iandclass_j. I write the below code to compute the similar loss based on the weights of last but one fc layer. Below is the part of the code for simplicity:cos = nn.CosineSimilarity(dim=1, eps=1e-6)
for... | KFrank | Howdy Hoody!
If you’re asking whether the assignment:
weights = self.model.module.model.fc[-1].weight
will prevent gradients from flowing back through the assignment
and break backpropagation, the answer is no.
In python, “variables” are references.
self.model.module.model.fc[-1].weight refer… |
NumesSanguis | Current situationI have a multi-label classification problem for which being overconfident is a problem in the end application. The data is labeled with 1 or more from[A, B, C, D, E], but in reality e.g. label B should not be treated as 1 or 0, but e.g. 0.7 (unfortunately unattainable).Normal trainingIf I would use BCE... | KFrank | Hi Numes!
The short answer is to use a “less-certain” target:
target = torch.tensor([[0.3, 0.3, 0.7, 0.3, 0.7],
[0.3, 0.7, 0.3, 0.3, 0.3]])
As I understand it, the “ground-truth” labels you are given are all
exactly 0.0 or 1.0. But (because you understand the problem)
y… |
berkay_berabi | Hi all,I have a multiclass classification problem and my network structure is a bit complex than usual. In a nutshell, I have 2 types of sets for labels. The ground-truth is always one label from one of the sets. (think like, labels from 0 to C are from one set and labels from C+1 to N are from another set)My network ... | KFrank | Hi Berkay!
Perform your s, (1 - s) weighting in “log space” so that you work
directly with the log-probabilities and only have to call log_softmax(),
with its better numerical stability.
That is, because:
log (s * prob) = log (s) + log_prob,
just add log (s) (and log (1 - s)) to your results … |
bing | Hi Guys,I am trying to do multi-class image classification.I am trying to debug my network for potential bugs so training and validating are on the same subset of data. Logically, the training and validation loss should decrease and then saturate which is happening but also, it should give 100% or a very large accuracy... | KFrank | Hi Bing!
Just to be precise, these are not “probabilities.” (If they were, they
would be values between 0 and 1 that sum to 1.) They are most
likely the output of a final Linear layer (with no subsequent non-linear
“activation”), and should be understood as raw-score logits.
The output of a… |
kliu | Hi all,I am wondering what loss to use for a specific application.I am trying to predict some binary image. For example, given some inputs a simple two layer neural net with ReLU activations after each layer outputs some 2x2 matrix [[0.01, 0.9], [0.1, 0.2]]. This prediction is compared to a ground truth 2x2 image like ... | KFrank | Hi kliu!
If I understand your use case, you should start with
BCEWithLogitsLoss as your loss function (and only change
to something else if you have a good reason and testing shows
that the change is for the better).
Just to be clear, for BCEWithLogitsLoss, the last layer of your
network sho… |
shinra | import torch
import torch.nn as nn
N,D_in,H,D_out=64,1000,100,10
model=torch.nn.Sequential(
torch.nn.Linear(D_in,H,bias=True),
torch.nn.ReLU(),
torch.nn.Linear(H,D_out,bias=True)
)
#torch.nn.init.normal_(model[0].weight)
#torch.nn.init.normal_(model[2].weight)
loss_fn=torch.nn.MSELoss(reduction='sum')
x=tor... | KFrank | Hi shinra!
This is more of a python question than something specific to pytorch.
In:
for param in model.parameters():
param is python variable which means that it’s a reference to
something. In each iteration through the for loop it is set to refer
to one of the model.parameters().
But … |
usami | Intorch.sortortorch.argsort, I can specifydescendingtoTrueorFalseto get sorted order I want.How can I specify the sorting by a dynamic comparison order. For example, given following tensor to be sorted:a = torch.tensor([[2, 1, 1, 2, 2, 2, 1], [3, 1, 1, 2, 2, 2, 1]])
compare = [torch.tensor([2, 1]), torch.tensor([2, 3, ... | KFrank | Hello Usami!
I do not believe that pytorch’s sort() supports a custom sort order
or comparator argument.
But you can implement it relatively easily. The idea will be to look up
your values to be sorted in your comparison-order vectors, and then
sort those indices.
Note that in your example u… |
shartzog | I’m working on a multilabel classification problem. In my current version, I have four potential labels: “Hospitalized”, “Intubated”, “Deceased”, and “Pneumonia”. My model trains well and has provided some interesting insights on cases with at least one label, but none of my post-training analyses account for the cas... | KFrank | Hi Sam!
You do not need (or want) a “None” label. The “None” case is indicated
by none of your four given labels being active.
You have a multi-label, multi-class classification problem. It is
multi-class because you have four classes, “Hospitalized,” “Intubated,”
“Deceased,” and “Pneumonia.… |
thao | Hi.I’m trying to modify Yolo v1 to work with my task which each object has only 1 class. (e.g: an obj cannot be both cat and dog)Due to the architecture (other outputs like localization prediction must be used regression) sosigmoid was applied to the last output of the model(f.sigmoid(nearly_last_output)). And for clas... | KFrank | Hello Thao!
I don’t fully understand your use case, but I would proceed as follows:
Use CrossEntropyLoss for the classification part of your model. To
do this, your model should output raw-score logits,, not probabilities,
so the last layer of your model should most likely be a Linear layer
w… |
Capo_Mestre | Hello,I have defined aDenseNet(please follow the link for details) and a custom Loss-functionMSE_modas shown below:# mean squared error with explicit const and linear terms
def MSE_toOptimize(params,yHat,y):
y0,y1 = params
x = [i for i in range(yHat.size()[1])]
x = torch.tensor(x).to('cuda:0')
size = yH... | KFrank | Hello Capo!
You are correct; this does break the computation graph.
In order to be able to backpropagate through the minimize() part
of your loss-function computation, pytorch has to be able to get the
gradient of minimize()'s output with respect to its input.
You have two choices:
You can w… |
jarvico | Hi all,Assume that we have a pertained NN model like LeNet-5 which successfully predicts handwritten digits. In this case number of features is 784 (assuming 28x28 input images) and number of outputs is 10. Sum of the output values(probs) adds up to 1 and each output shows the probability of that class for the given in... | KFrank | Hello Ömer!
Just as you use pytorch’s autograd to calculate the derivatives (gradient)
of your loss function with respect to your model’s parameters (and then
use those to update your model with gradient descent), you can use
autograd to calculate the derivatives of a prediction for a single cl… |
mzimmer | Hey! I implemented the following algorithm using python for loops, which are, afaik, not very efficient:sorted, indices = torch.sort(torch.abs(torch.reshape(x, (-1,))), descending=True)
running_sum = -r # r is some positive number
for idx, element in enumerate(sorted):
running_sum += element
if element <= (runn... | KFrank | Hi Max!
Yes, you can do this with pytorch tensor operations. Use cumsum()
divided by something like arange() to get the running mean. Then
test that against your sorted tensor to find when your condition first
holds.
Here is a pytorch version 0.3.0 script:
import torch
torch.__version__
to… |
Mirror_Neuron | A simple 6x6 matrixmg_data = [[10, 10, 10, 0, 0, 0],[10,10,10, 0, 0, 0],
[10,10,10, 0, 0,0],
[10,10,10, 0, 0,0],
[10,10,10, 0, 0,0],
[10,10,10, 0, 0,0]]And a 3x3 kernel or filterf_data = [[1,0,-1],[1,0,-1],
[1,0,-1]]How do I do a simple convolution operation using Stride = 1 a... | KFrank | Hello Mirror!
Note, I am using an older version of pytorch, 0.3.0.
The only way I know to perform a convolution in pytorch (without
writing your own convolution logic) is to create an appropriatetorch.nn.Conv2dand apply it to your appropriately-reshaped data.
(Newer versions of pytorch may o… |
hadaev8 | Cant find in google anything about it. | KFrank | Hi Had!
The short answer is that MSE loss is not a loss that would naturally
be used with classes. As such, pytorch’s MSELoss does not attempt
to implement any feature that might be considered analogous to
“class weights.”
The reason is that MSE loss is naturally a measure how much two
sets … |
arjun_pukale | which activation function to be used at last layer of segmentation models like segnet, unet?should I useF.sigmoidwhile defining the model’s last layer itself? | KFrank | Hi Arjun!
The short answer is that you should just use the output of your last
linear layer, with no activation function, as input to your loss function
(for plain-vanilla use cases).
I assume that you are asking about training a network to segment
2d images, that is, the output of your networ… |
localh | Good Afternoon,I am wondering whether this is a suitable way to approach a problem or if I should consider alternatives (that I am unaware of) as well.I have a relatively balanced classification problem involving 3 labels: 0, 1, and 2. I am interested, however, in paying a little more attention to getting the 0s right.... | KFrank | Hi Andrew!
Yes, this is a reasonable approach to more accurately classify
class-0 samples.
That is, adding these class weights to your loss function will train
your network to more often correctly label class-0 samples as
class-0 (fewer false negatives), but at the cost of more frequently
inc… |
arnavs | Hi,I’m working on a problem which involves learning taking a vectorX = [1, c, x_1, ..., x_N](currentlyN ~ 100, but much more in the future) and learning a specific quadratic form,Y'PY + b, whereY = [1, c, X_bar]andX_baris the average of thex's.The current way I’ve been doing this is by using a bilinear layer with a bia... | KFrank | Hello Arnav!
The idea would be to preprocess your data before you feed it to your
model.
Depending on the details of your use case, you could, for example,
read your original data off of disk (independent of pytorch), construct
your Y vectors, and then write this preprocessed data back to disk… |
CharlesLu | Hi there!When I use torch.nn.functional.kl_div(), I notice that while the reduced mean of result is positive, some values in the unreduced result are negative. I was wondering if it is the correct behavior, or I made some mistake in my codes?Thank you very much!image1445×956 87.8 KB | KFrank | Hi Charles!
You are correct that the KL divergence is non-negative, and you are
also correct that the individual terms returned by pytorch’s “unreduced”
kl_div() can be negative.
The reason is that, by definition, the KL divergence is taken between
two probability distributions, not between tw… |
AwesomeLemon | Hello,I’m having trouble understanding behaviour of class weights in CrossEntropyLoss.Specifically, when reduction=‘mean’. I test it like this:input = torch.randn(5, 2, requires_grad=True)m = nn.LogSoftmax(dim=1)mi = m(input)target = torch.tensor([0, 0, 1, 1, 1])w = torch.tensor([1, 100]).float()Now, without weights ev... | KFrank | Hello Awesome!
Passing weights to NLLLoss (and CrossEntropyLoss) gives, with
reduction = 'mean', a weighted average where the sum of weighted
values is then divided by the sum of the weights.
In your `reduction = ‘none’ version:
F.nll_loss(mi, target, weight=w, reduction=‘none’).mean()
by the… |
Massivaa | Hello,I have a question about the argmax function when I put :torch.argmax (output, 1)I get a result:grad_fn = NotImplementedand when I tried:torch.argmax (output, 1) .float (). requires_grad_ (True)it shows megrad_fn = CopyBackwards.so can you explain to me what exactly does that meanThank you in advance | KFrank | Hello Massivaa!
Another way to say it is that argmax() is not usefully differentiable.
Consider torch.argmax (torch.FloatTensor ([x, 1.0])).
argmax() will be 1 for x < 1.0 and 0 for x > 1.0. In both cases
its derivative (gradient) with respect to x will be zero, and it won’t
be mathematically… |
thomas | I have a code of a custom loss that I implemented on tensorflow that I would like to pass on Pytorch for technical reasons. However I can’t seem to make it work and I don’t know why.The pytorch loss doesn’t seem to train the networkThe aim is to compare raw linear output of a network (before softmax) with true probabil... | KFrank | Hi Thomas -
The short answer is that your pytorch code only takes one optimizer
step.
With default arguments, tf.keras.Model.fit() performs one epoch
of training with a batch size of 32. You pass in 1000 samples, so you
will train for about 30 optimizer steps. This should be enough to train … |
swap | I am constructing a DNN model using pytorch. I came across two ‘loss’ terms for training (see code below). My questions:Which training loss should I compare against validation loss? Shall I use loss or running loss?In both cases, training loss differs by several folds as compare to validation loss. What am I doing wron... | KFrank | Hello Swapnil!
I don’t really understand what you are trying to do nor what your issue is.
But I have a couple of comments:
When you calculate loss and val_loss you use normedWeights in
loss_function. But when you calculate running_loss you do not
use normedWeights. Also, running_loss is an … |
Hwarang_Kim | I built my loss function using conditional statement like:def myloss(data):
if blah blah:
loss = blah
if blah blah:
loss = blah
return loss
loss = myloss(output)
loss.backward()I worried it won’t work but it worked.but how can my loss function be backpropagated?Is my loss function differenti... | KFrank | Hello Hwarang!
No, this won’t work. The problem is that this version of myloss() isn’t
usefully differentiable. It is constant almost everywhere, so the gradient
will always be zero.
Mathematically, myloss() is differentiable (with zero gradient) except
when any of the data[i] = 0.5, at whic… |
dllacer | Hi everyone,This is a general doubt I have about the relationship between the activation function and the data.Imagine our data (images), after normalization, is centered at 0 and take values between -1 and 1. It means our network will try to output images which values will be also between -1 and 1.So, for example, if ... | KFrank | Hi Deep!
No, this way of looking at it isn’t correct.
The reason is that the weights in your layers can be negative and
the biases are not constrained. So a negative input value can be
multiplied by a negative weight or have a positive bias added to it,
and therefore become positive, before i… |
wouterM | Hi all,I am trying to get an autoencoder to work on my L2 normalized dataset. For now I use the MSE loss which works oke but I noticed that a lot of the reconstructed vectors are not nearly on the unit sphere, which they should be since I know every input vector is on there. Is there any simple solution to penalize or ... | KFrank | Hi Wouter!
To answer this specific question, yes, you can add a loss term
that will push your predictions onto the unit sphere.
When the (L2) norm or your prediction is 1, the prediction is on
the unit sphere. So just add unit-sphere mismatch term:
sphere_loss = fac * ((preds**2).sum (dim = 1… |
Ahmed_Abdelaziz | I have this model depicted in the figure. Model 1 and model 2 used to be two disjoint models such that they worked in a pipeline that we first train model 1 till convergence and feed the preprocessed outputs to model 2 as inputs. I am now training them end to end and I am struggling with how to integrate these two loss... | KFrank | Hello Ahmed!
Yes, this is, in effect, what will happen.
Summing the losses is the approach I would take. I would probably
include relative weights: loss = w1 * loss1 + w2 * loss2.
Note, that loss1 does not depend on the weights in modules D and
E, so backpropagating loss1 + loss2 will have th… |
nowyouseeme | I have a tensor in pytorch with sizetorch.Size([1443747, 128]). Let’s name it tensorA. In this tensor, 128 represents a batch size. I have another 1D tensor with sizetorch.Size([1443747]). Let’s call itB. I want to do element wise multiplication of B with A, such that B is multiplied with all 128 columns of tensorA(obv... | KFrank | Hello Mr. Knight!
Give B a dimension of size 1 using unsqueeze() so that it has a
dimension from which to broadcast:
B.unsqueeze (1) * A
Best.
K. Frank |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.