user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Assefa_Seyoum | I have a tensor of shapetorch.Size([400, 32, 32])Each 32x32 patch contains only ones and zeros.I want to return a geometric center / medoid of foreground pixels (1s).The shape of the return value would be[400, 2].Example:image863×535 88.8 KBThe above [4, 4] patch returns [1,2] as the coordinate.How to do that without a... | KFrank | Hi Assefa!
To do this on a “batch” basis, probably the simplest approach is to
generate a tensor that hold the indices of all of the pixels in your 32x32
slices and then compute the foreground-pixel weighted average of those
indices:
>>> import torch
>>> print (torch.__version__)
1.12.0
>>>
>>>… |
Gianluca_Maselli | Hi,I have built a neural network aiming to predict 5 continuous values from video samples in the range between 0 and 1. For the last activation, I used the Sigmoid Activation function and as a criterion the MSE loss. Is it good for both the choices?Thanks in advance for the help. | KFrank | Hi Gianluca!
MSELoss is usually the right choice for regression. I would recommend
that you always start with MSELoss and only use something different if
you have good reason and can show that it works better.
As for the Sigmoid, I would not use it, even though your target values
are in the r… |
alessandro_mondin | Hello all,I am trying to train the UNET on the DAVIS 2017 dataset.I am facing some issues because after 10 epochs the model is still struggling to output correct masks.In particular these are some of the outputs:image_41000×700 214 KBimage_31000×700 228 KBimage_21000×700 159 KBimage_11000×700 176 KBI am truly strugglin... | KFrank | Hi Alessandro!
10 epochs of training does not sound like a lot to me. (As always, this
will depend on the details of your use case.)
Networks for reasonably complicated image-processing tasks are often
trained on hundreds or thousands (or more!) epochs.
I would suggest training on a training … |
Ali_Aghababaei | Hi everyone,I have gotten confused in understanding the “pos_weight” and “weight” parameters in BCEWithLogitsLoss. I’ve read all the relevant discussions in this regard, to my knowledge; however, still, I’ve not understood them completely.Imagine that I have a multi-class, multi-label classification problem; my imbalan... | KFrank | Hi Ali!
Let me answer a couple of your specific questions first and then explain
how I look at it.
In this case the current (1.9.0) documentation forBCEWithLogitsLossis wrong (or at least misleading). Quoting:
weight (Tensor, optional) – a manual rescaling weight given to the loss of each … |
Ximeng | Hi,I need a differentiable metric to roughly reflect the level of positive values in a tensor, so literally counting is not necessary.I tried two hard operations:relu+torch.sign+sumtorch.count_nonzeroResult:requires_grad=True. But input.grad are all zeros after using “torch.sign” .requires_grad=FalseI’m not sure if fc ... | KFrank | Hi Ximeng!
1000 is very large for the multiplier used to “sharpen” the sigmoid().
This causes the sigmoid() to become quite close to a (discontinuous)
step function for which the gradients would be exactly zero. Very small
gradients (that underflow to zero) are to be expected here.
If you wan… |
gchou | Hi all,I am trying to do the following:Create a model (model A) with a few linear layers that produces X, a list of tensorsCreate a model (model B) with a few linear layers during the forward loop of model A (or create model B one time outside of the training loop and just reference it here each time)Overwrite the para... | KFrank | Hi gchou!
Models typically have Parameters and Parameters are typically things
that are optimized.
If I understand your use case, you don’t intend to optimize the “parameters”
(weights) of model B, but rather derive (“predict”) them using another model,
model A (whose Parameters you do intend … |
yzxhd | loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.empty(3, dtype=torch.long).random_(5).long()
target[1] = -100
output = loss(input, target)The target contains negative values but no error is raised. But if I changetarget[1]to other negative values, e.g.-1,-10, then the error can... | KFrank | Hi yzx!
From thedocumentation for CrossEntropyLoss:ignore_index=- 100
and
ignore_index (int, optional) – Specifies a target value that is ignored
and does not contribute to the input gradient. When size_average
is True, the loss is averaged over non-ignored targets. Note that
ignore_ind… |
AlphaBetaGamma96 | Hi All,I was just wondering if there’s a way to doscipy.special.hermitewithin PyTorch natively (in order to utilize the GPU). My current approach to pass to the CPU and then move back to the GPU whichalthoughworking, I’d prefer to utilize the GPU as much as possible! As it works can’t covertcudatonumpyerror if you dire... | KFrank | Hi Alpha!
I’m not aware of pytorch support for Hermite polynomials.
Edit:
Update: I see support for Hermite polynomials in a recent nightly build,
but it doesn’t appear to support autograd yet:
>>> import torch
>>> torch.__version__
'1.13.0.dev20220727'
>>> _ = torch.manual_seed (2022)
>>> x… |
Junaid | I created a single linear layer model with identity matrix as the weights. But by passing the random input values to the model. the output and input values are not same after 3 to 4 decimal points of float type . But incase of integers the values are same.Output:The input and output have to be same. But you can see tha... | KFrank | Hi Junaid!
This is probably the “TF32 bug.” This post has some details:
Do you get the right answer when running on your cpu? What gpu are
you using? Does torch.backends.cuda.matmul.allow_tf32 = False
fix your issue?
As an aside, please don’t post screenshots of textual information. Doin… |
Wesley_Neill | I am looking for a PyTorch analog toscipy.special.ivwhich excepts an arbitrary order as one of its arguments. I only see fixed 0th and 1st order implementations intorch.special’s docs. Does anyone know if this analog exists elsewhere? | KFrank | Hi Wesley!
I am not aware of any pytorch implementation of higher Bessel functions.
If you need gradients (backpropagation), you could wrap scipy’s iv() in
acustom autograd Function.You would (presumably using scipy again)
implement the derivative of iv() in your Function’s backward() method… |
blackbirdbarber | print(x.shape, x_skip.shape)
x_skip.resize_(x_skip.shape[0], x_skip.shape[1], x.shape[2], x.shape[3])
x = torch.cat((x, x_skip), dim=1)Out:torch.Size([1, 512, 24, 24]) torch.Size([1, 256, 25, 25])The problem is I wanted tocattwo tensors but since they don’t match I don’t have the idea how to cut tensorx_skipto ... | KFrank | Hi Blackbird!
To answer your specific question: resize_() doesn’t do what you would
want it to – it will mess up the two-dimensional structure of your image.
You can just slice into x_skip to trim off the excess of one row and column
of pixels:
x = torch.cat ((x, x_skip[:, :, :x.shape[2], :x.… |
jayz | Hey,I have a model that outputs batches with size B of “A-dimensional” softmax probabilities for C classes. For instance, the outputwcould look like this, for B=2, A=4 and C=3:# B x A x C
w = torch.softmax(torch.rand([2,4,3]),dim=2)
w
# standard A-dimensional class probabilities, shape: B x A x C
>> tensor([[[0.2901,... | KFrank | Hi Jay!
The short story is that the gradient you are asking for isn’t useful because
it is zero almost everywhere.
Some more detail:
The problem is that your labels, wp, are integers (and would have integer
values even if you were to convert them to floating-point numbers). It
doesn’t really… |
Pablo_Garcia_Sant | Hi, when my tensor:tensor([[[-0.2132, -0.0098, -0.2187, 0.2484, -0.2478, -0.1970],
[-0.1974, -0.0097, -0.1878, 0.2076, -0.2087, -0.1970],
[-0.2494, -0.0098, -0.2379, 0.2802, -0.2788, -0.2645],
[-0.2179, -0.0098, -0.2074, 0.2394, -0.2392, -0.2645]]])Passes through the following layer:self.... | KFrank | Hi Pablo!
Pytorch version 1.11 made a flexibility improvement to Conv2d so that it
no longer requires a batch dimension. Quoting from Conv2d’s1.10and1.11documentation, respectively:
Shape:
Input: (N,Cin,Hin,Win)(N, C_{in}, H_{in}, W_{in})(N,Cin,Hin,Win)
Shape:
Input: (N,Cin… |
Lugi | So I have the following code snippet:import torch
loc = torch.tensor(0., requires_grad=True)
scale = torch.tensor(1., requires_grad=True)
gaussian_test = torch.distributions.Normal(loc, scale)
gaussian_y.log_prob(torch.tensor(0.)).backward()
print(loc.grad, scale.grad) # None, NoneSince calculating a logPDF at a parti... | KFrank | Hi Lugi!
gaussian_y is not defined within the code you posted. Did you mean:
gaussian_test.log_prob(torch.tensor(0.)).backward()
Your reasoning is correct and I believe that you will get a gradient if you
correct the line noted above that appears to be a typo.
Best.
K. Frank |
Ha_St | Hello together,I’m trying to use a model with one parameter being used in two layers but slightly altered in the second layer. It looks something like this:class CrNN(nn.Module):
def __init__(self, n, m):
self.P1 = nn.Parameter(torch.rand((m, n))) #weights
self.P2 = nn.Parameter(torch.rand(m)) # bia... | KFrank | Hi Hannes!
I would suggest keeping your Parameters, P1 and P2, as is, but using
the functional form of linear(), rather than the class Linear.
Because torch.where() doesn’t backpropagate cleanly (assuming that
you do want to backpropagate through the altered layer1 weights), you
should use so… |
yoterel | When I try to construct a tensor (A 3x3 matrix in my case) from multiple other tensors that require grad, the resulting tensor does not have require_grad = True by default, and even if I set it manually, when backproping the tensors that were used to construct the matrix do not get gradients. Why is this so?example cod... | KFrank | Hi Yotam!
The short answer is that this is the way that the factory function
torch.tensor() works.
This is perfectly fine.
As an alternative – not necessarily better – you can use cat() and
stack() to compose test_mat out of the desired pieces:
>>> import torch
>>> print (torch.__version__)
… |
jayz | Say we have two methods of slicing for computing an output of a convolutional layer:# N - batch size
# CI - number of in channels
# CO - number of out channels
# T - sequence length (think of e.g. a time series 0, ..., t, ..., T)
# model
conv = nn.Conv1d(CI,CO,kernel_size=1)
# input
x = torch.rand(N,CI,T)
# meth... | KFrank | Hi Jay!
This is correct.
No,* because you have kernel_size = 1, neighboring points don’t get
mixed with one another, so the earlier points in x don’t affect the later
points in out1 and out2.
See this example:
>>> import torch
>>> torch.__version__
'1.12.0'
>>>
>>> conv1 = torch.nn.Conv1d (3… |
RobinFrcd | Hi,I’m trying to convert a custom UNET implementation from Tensorflow to PyTorch. I’ve encountered some problems with the Conv2D layers.I know there could be some trouble with padding, it triedthisandthisbut it didn’t help.My conversion code looks like this:from keras.layers import Conv2D
from torch import nn
import t... | KFrank | Hi Robin!
The problem is that reshape() doesn’t really do what you think it is doing
and is messing up the two-dimensional structure of the image.
Use permute() on the pytorch side and transpose() on the numpy side.
Here is a slightly tweaked version of your code with the fix for reshape()
at … |
lnair | Hello,I’m trying to implement a custom SGD optimizer, by changing the way in whichd_p * alphagets added toparam. I started out with the following custom implementation which copies SGD code from:https://pytorch.org/docs/stable/_modules/torch/optim/sgd.html#SGDwith a small change in_single_tensor_sgd():def _single_tenso... | KFrank | Hi lnair!
param = param + d_p * alpha creates a new tensor and sets the
python reference param to refer to the new tensor, rather than modifying
the tensor you wish to train. Conversely, param.add_(d_p, alpha=alpha)
modifies the desired tensor (“adds in place”).
One approach that would keep m… |
Ximeng | Hi,Suppose there is a tensor A=[3,4,5,6] with requires_grad=True, and a tensor THRES=[4] also with requires_grad=True. Let B=A[A>THRES]. In this case, B allows backwards and it inherite gradients from A. I think the bool mask term [A>THRES] doesn’t maintain any gradient infomation. Despite the fact that THRES influence... | KFrank | Hi Guo!
Your reasoning is correct. The thresholding operation is not (usefully)
differentiable, so autograd does not backpropagate through it.
To verify:
>>> import torch
>>> torch.__version__
'1.10.2'
>>> A = torch.tensor ([3., 4., 5., 6.], requires_grad = True)
>>> THRES = torch.tensor ([4.]… |
Ximeng | Hi , I was trying to generate a group of trainable monotone positive tensors as the weights for Conv1d. It actually works to some extent, but the problem is the real trainable parameter “alpha”/“beta” changed very slightly compared with orthodox convolution weights. They just fluctuated around the initiate value. So I ... | KFrank | Hi Ximeng!
Am I correct that you want the individual weight-values in your conv1d()
kernel to be positive and monotonically increasing, even as they train?
This won’t work.
You are only calling:
self.w = torch.softmax(self.lin * self.alpha + self.beta, dim=0).unsqueeze(0).unsqueeze(0)
once, … |
maryma | Hi I wanted to train a model for survival time prediction with MRI images. Suppose I have both images and labels and I want to make a dataset that contains both image and label. What can I do for example is there any way to give segmentation as a new channel map? Or is multiplying the tensors of images and labels, a go... | KFrank | Hi Maryam!
I chose dim = 1 because I was assuming the img and lbl already
had an nBatch dimension so that the nChannel dimension would be
in position 1.
Everything you’ve posted suggests that you do have an nChannel
dimension (for img and lbl), even if that dimension has size 1.
To check thi… |
alessandro_mondin | Hello all,I am trying to code from scratch the UNET where input dimensions in the paper are:input.shape = (batch_size, 3, 572, 572) and out.shape = (batch_size, 1, 388, 388).link here:UNET_PAPERIn this case which is the best practice to resize out.shape?It would be better to resize it in the Dataset class and load targ... | KFrank | Hi Alessandro!
There are any number of U-Net implementations scattered hither and
yon across the internet. I can’t tell you how good they are or how closely
they hew to the original U-Net paper.
First, read the original U-Net paper carefully, understand how the image
gets its edges trimmed o… |
LeanderK | I am working on a huge model where I am very much memory constrained. I continuously generate terms for regularisation, my loss looks something like:loss = accuracy + sum_ penalty alpha*penaltymy computational graph looks like this:computation -> computation -> computation -> computation -> computation -> (...)
... | KFrank | Hi Leander!
I don’t understand your use case, but let me make a couple of comments:
If you need to backpropagate the gradient of penalty1 back through only
the computation of penalty1 (and not through the computation of comp1)
then simply, .clone().detach() comp1, set requires_grad = True on
t… |
Liano | I train some pre trained models for a binary classification task. Therefore I want to optimize on the recall value. It seems like the nn.CrossEntopyLoss Function is the best one for the job, but is there another one or should I define my own loss function?? (I’m new to PyTorch)some help would be great | KFrank | Hi Kilian!
Recall (in the context of making classification predictions for a given
dataset) is the percentage of positive samples that you correctly classify
as positive. Note, it doesn’t care whether you classify negative samples
correctly or not.
It is a useful performance metric, but, in i… |
fried-chicken | What I want to do is:given a tensor with shape like [32,100] as input, I want to get 2 tensor with shape [32,50] and [32,50] as output, where the first [32,50] contains the top-50-largest elements in each rows and the second [32,50] contains the top-50-smallest.So far, I know I can use torch.topk() twice to get the des... | KFrank | Hi Fried!
In this specific use case you want, at the end, all 100 elements split up
a certain way. So you will be better off calling sort() once, rather than
calling topk() one or more times:
>>> import torch
>>> print (torch.__version__)
1.12.0
>>>
>>> _ = torch.manual_seed (2022)
>>>
>>> t =… |
hedeya1980 | I’m trying to adjust a binary segmentation U-net model, to be able to train a multi-class U-net on the German Asfalt Pavement Distress (GAPs) dataset.Traceback (most recent call last):
File "/content/drive/Othercomputers/My Laptop/crack_segmentation_khanhha/crack_segmentation-master/train_unet_GAPs.py", line 263, in ... | KFrank | Hi Mohamed!
That clears things up.
masks_pred correctly has its nChannels dimension as its second
dimension. But target_var has that extra singleton dimension that
doesn’t line up with anything in masks_pred. (In the most common
integer categorical class labels use case, masks_pred should ha… |
Vasudha_Venkatesan | Hello,I’m new to Pytorch and I’m trying to perform semantic segmentation of 3d images. When I use cross entropy loss with ignore index, I get the above error.def training_fn(net,
device,
input_dim,
epochs: int = 1,
batch_size: int = 1,
lear... | KFrank | Hi Vasudha!
You don’t have the requirements for pred and mask correct yet.
Your pred (target for CrossEntropyLoss) has to be floating-point and
have an nClass dimension, while mask (target for CrossEntropyLoss)
has to be long() and not have the nClass dimension.
Consider:
>>> import torch
>>> … |
rs27 | Hello,I would like to reshape a tensor (or alter the dimension of the tensor) such that the elements do not change location. Here is a simple example:torch.Size([2, 2, 2, 2])
tensor([[[[1., 0.],
[0., 0.]],
[[0., 1.],
[0., 0.]]],
[[[0., 0.],
[2., 0.]],
[[0., 0.... | KFrank | Hi Rajiv!
permute() followed by reshape() will do the trick:
>>> import torch
>>> torch.__version__
'1.10.2'
>>>
>>> s = torch.tensor([[[[1., 0.],
... [0., 0.]],
... [[0., 1.],
... [0., 0.]]],
... [[[0., 0.],
... [2., 0.]],
... [[0., 0.],
..… |
aonurdasdemir | I am implementing my own grad check function as autograd’s built-in one is slow on large tensor input and outputs. What I do is choose some random points on the input tensor and perturbe them to calculate finite differences, then I compare the results with automatic gradient. Here is my implementation,def grad_check(mo... | KFrank | Hi Ahmet!
The lesson here is that calculating gradients numerically can be nuanced and
requires thoughtful attention to floating-point arithmetic.
Two things to pay attention to:
Your data (and target and the output of your model) are of order 1, and
your individual squared-error values are of… |
my3bikaht | Sorry, maybe it’s a stupid question and it’s already late, how grad computed for matrix multiplied by itself from the calculus standpoint? I mean if we have matrix m x m and multiply it by itself just like in self attention in transformers, isn’t it already non-linearity without activation function? | KFrank | Hi Sergey!
It’s just regular calculus. Let’s say that A is an m x m matrix. Then
(A @ A)[i, j] = sum_k (A[i, k] * A[k, j]). To compute the full
Jacobian of A @ A with respect to A, you need to evaluate the derivatives
d (A @ A)[i, j] / d A[k, l] for all values of the indices i, j, k, and l.
… |
peter_m | I’m completely new to PyTorch, so apologies in advance if this is very silly.My goal is to post-process (evolutions of) probabilistic forecasts for which the outcome is known. E.g. I have forecasts of the form[.5, .6, .8]and the information that this forecast resolved positively, i.e.resolution=1. (In this example, the... | KFrank | Hi Peter!
This is pytorch’sBCELoss.
However, for reasons of numerical stability, you will be better off usingBCEWithLogitsLoss. To do this, you will have to modify your network to
predict logits that run from -inf to inf (rather than probabilities that run
from 0.0 to 1.0).
You would typic… |
Hyeonuk_Woo | Hi, I’m not good at using trick for matrix multiplication.I want to get rid of “for loop iteration” by using Pytorch functions in my code. But the formula is complicated and I can’t find a clue. Can the “for loop iteration” in the below replaced with the Torch operation?import torch ,sys
B=10
L=20
H=5
mat_A=torch.randn... | KFrank | Hi Hyeonuk!
Yes, my tip is to use pytorch’s “Swiss-army knife” of tensor multiplication,einsum().
>>> import torch
>>> torch.__version__
'1.11.0'
>>>
>>> _ = torch.manual_seed (2022)
>>>
>>> B=10
>>> L=20
>>> H=5
>>>
>>> mat_A=torch.randn(B,L,L,H)
>>> mat_B=torch.randn(L,B,B,H)
>>> tmp_B=torch.… |
SouthTorch | I used the following code to implement my MNIST dataset learning. When L1&L2 regularization are not used, the test accuracy can reach 94%. When L2 is used while L1 is not used, accuracy can reach 96%. While the usage of L1 can drop the accuracy straight down to 11%. Is my implementation wrong? or L1 is just like that, ... | KFrank | Hi David!
The short story is that I would prefer L2 over L1 regularization.
I haven’t looked at your code in any detail.
I haven’t performed careful experiments comparing L1 with L2
regularization (and not in the context of conventional network
architectures).
However, the result you’re seei… |
ciacc | For the following simple code, withpytorch==1.9.1, python==3.9.13vspytorch==1.11.0, python==3.10.4, The result is totally different. In the newer version of pytorch, the grad is lost.import torch
S = torch.zeros(1,4)
a = torch.tensor(1.,requires_grad=True)
S[0,2:4] = a
print(S)pytorch==1.9.1, python==3.9.13gives:tensor... | KFrank | Hi Ciacc!
This appears to be a known bug / regression that has recently been fixed.
It works for me in a version-1.13 nightly build:
>>> import torch
>>> torch.__version__
'1.13.0.dev20220604'
>>> S = torch.zeros(1,4)
>>> a = torch.tensor(1.,requires_grad=True)
>>> S[0,2:4] = a
>>> print(S)
tens… |
yuri | as the conv layer performs the sum of the elementwise product between two arrays A and Bhowever , I would like to use the same iteration mechanism to perform a custom operation as follows:for those who might notice that this equation is the Kullback–Leibler divergence, indeed I want to perform the KL div between 2d arr... | KFrank | Hi Yuri!
Please take a look atUnfold(or unfold()).
Here is a discussion about using unfold() for a custom convolution (with
links to further discussion):
Best.
K. Frank |
Chrystian | I am a bit confusedLet say I have 4 different losses.losses_list = [loss1, loss2, loss3, loss4]and as usual I want to add them together. Does the followingfinal_loss = 0
for loss in losses_list:
final_loss += lossgives different grad result than doing the following below?final_loss = loss1 + loss2 + loss3 + loss4My... | KFrank | Hi Chrystian!
It is possible for these two approaches to produces results that differ
by a small floating-point round-off error. The sequence of additions
could be performed in differing orders that would be mathematically
equivalent, but could differ (by a small round-off error) numerically.
… |
111414 | How can I achieve fast masking as follows:import torch
q = torch.Tensor([2, 3, 6, 2])
x = torch.randn(4, 10, 3, 3)
for i in range(4):
x[i, int(q[i]):] = 0
print(x) | KFrank | Hi Bin!
You can get rid of the loop by multiplying x inplace with a boolean
mask tensor:
>>> torch.__version__
'1.10.2'
>>> _ = torch.manual_seed (2022)
>>> q = torch.Tensor([2, 3, 6, 2])
>>> x = torch.randn(4, 10, 3, 3)
>>> xB = x.clone()
>>> for i in range(4):
... x[i, int(q[i]):] = 0
...… |
shon711 | Hello.I have series of matrix multiplication in a for loop structure, I want to transform it to one “big” matrix to do all the multiplication together to better utilize the GPU.Here is the current implementation:The model inputx, yin shape of[batch_size, k, config.hidden_size].For each category id[0, 1, 2, 3]we compute... | KFrank | Hi Shon!
It’s not entirely clear to me what the values num_cats and k are.
Let me assume that you want the shape of your final “all the multiplication
together” result to be [batch_size, num_cats, k, k].
You can compute your three-term product with einsum():
result = torch.einsum ('bnkf, bnfg… |
zwj | I want to train a neural network that can map the two-dimensional uniform distribution to the 512-dimensional normal distribution. how should I do? I have construct a fully-connected and I am using the KL divergence function as loss function. It seems that the loss do not decrease while training the network.The followi... | KFrank | Hi zwj!
The essence of your problem is that KLDivLoss compares two (discrete)
probability distributions as described by actual (log) probabilities, rather
than as described by sets of samples from those distributions.
On a lower technical level, a symptom of your core problem is that
you can’… |
111414 | The following code can produce an orthonormal matrix for me:import numpy as np
from scipy.linalg import orth
def get_matrix(M, N):
Phi = np.random.randn(N, N).astype(np.float32)
return orth(Phi)[:M]
Phi = get_matrix(10, 10)
print(np.matmul(Phi, np.transpose(Phi, [1,0]))) # should be very close to identity ma... | KFrank | Hi Bin!
You can use pytorch’s svd() to do what I am pretty sure is the same
thing as scipy.linalg.orth() is doing:
>>> import torch
>>> torch.__version__
'1.11.0'
>>> _ = torch.manual_seed (2022)
>>> gaus = torch.randn (5, 5)
>>> svd = torch.linalg.svd (gaus)
>>> orth = svd[0] @ svd[2]
>>> orth
… |
111414 | I know thattorch.randnis not differentiable, but we can use reparameterization technique to make the standard deviation differentiable:x = ...
noise = x * torch.randn_like(x)Istorch.poissondifferentiable? Or if there exists a way to maketorch.poissondifferentiable? | KFrank | Hi Bin!
It depends on what you are actually asking.
The function torch.poisson() is not differentiable (even though it has
a grad_fn). There are two reasons for this: First, torch.poisson()
returns a sample from the Poisson distribution, and pytorch does not
support backpropagating through s… |
Ali_Akyurek | Hi all,I have a question regarding PositionalEncoder implementaton in official transformers tutorial*There’s the following implementation there:torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))However I’d expect to see something like1/((10000.0 ** (torch.arange(0, d_model, 2) / d_model)))What’s th... | KFrank | Hi Ali!
There is a performance advantage (but no substantive numerical
advantage). The pow() (**) function is modestly more expensive
than exp(). (While log() is expensive, you only have to compute
it for a single scalar, and not the whole arange() tensor.)
For timing purposes I have made a m… |
isaka_lorry | Hi, I read many articles in ‘discuss.pytorch.org’ community on why parameters are not getting updated. I found many similar challenges like -Optimizer.step() not updating correctly. But, I didn’t know where my network went wrong? Training is not happening in my network. Any inputs and suggestions please.I am working on... | KFrank | Hi Surya!
As posted, your code – loss.backward – doesn’t actually call the
.backward() method of the loss Tensor.
Try loss.backward(). (Note the parentheses.)
Also, check whether your gradients are not None and are non-zero
before calling optim.step(), e.g., print (model[0].weight.grad).
Bes… |
farbabi | I am trying to reproduce the results reported inDecoupled Neural Interfaces using Synthetic Gradientspaper by PyTorch. The key idea in this paper is to approximate the gradient of the loss, using a synthetic gradient, gk, so that:After calculating the gradient of the loss, I need to update the weights of the upstream l... | KFrank | Hi Faraz!
I don’t understand what you are saying here.
With the exception of the duplicated index that I assume is a typo (see
my previous post), I think that the
in your original post is correct.
The way I read the image of the equation in your original post, L is the
scalar loss computed b… |
jayz | Hey,I have H=10 groups of time series. Each group contains C=15 correlated time series. Each time series has a length W=100. I feed the data in batches X of shape BCHW = (32,15,10,100) to my model.What I would like to do is to independently apply 1d-convolutions to each “row” 1,…,H in the batch. At first, I used a comp... | KFrank | Hi Jay!
You can use the groups feature of Conv1d. To do so you will have
to merge your channels (C) and rows (H) dimensions together, using
.transpose() so that they get merged in the correct order.
Here is an illustrative script:
import torch
print (torch.__version__)
_ = torch.manual_seed … |
Albert_HK | Hi,how could I achieve the following function without for loop ?Should I use scatter function ?Thanks!position_ids = torch.arange(500).reshape(10, 50)
prompt_pos = torch.arange(50).reshape(10, 5)
for index in range(10):
position_ids[index][prompt_pos[index][0]:] = prompt_pos[index][0] | KFrank | Hi Albert!
I don’t see a way to do this with scatter(). You can, however, compute
an appropriate boolean mask and then use it to index into position_ids
(or, equivalently, use torch.masked_select()):
>>> import torch
>>> torch.__version__
'1.10.2'
>>>
>>> position_ids = torch.arange(500).resha… |
Jeguarko | Help to understand how BCEWithLogitLoss works for a multiclass case with class imbalance (object detection, Yolov5 (yolov5/loss.py at master · ultralytics/yolov5 · GitHub)).I have a dataset of 6595 images. Each image can have up to 5 different object classes. Suppose these are people, cars, billboards, trees, bicycles.... | KFrank | Hi Egor!
Yes, then this is a multi-label, multi-class problem for which
BCEWithLogitsLoss would typically be the best choice.
Your proposed values for pos_weight look appropriate, given the
class frequencies you posted.
When pos_weight is not None, it gets applied along the class dimension
of… |
Mukeyii | Hello there,is there an easy way in PyTorch to split an index mask tensor into multiple masks, each containing only one contiguous labeled area (e.g. [num_areas, H, W])?Tensor [1, 512, 512] (Index Tensor containing 0 or 1) to a Tensor [6, 512, 512]. 6 is the amount of contiguous areas, which is not static. The colored ... | KFrank | Hi Kemal!
What you are looking for are the connected components (of an image,
rather than of a graph).
I do not believe that pytorch supplies a built-in connected-components
algorithm, but several pytorch connected-components implementations
appear to be available on the internet. (I haven’t… |
sebastienwood | Hi !I’m working on a project that has the following pipeline:numerical integration of a given functioninterpolation (using ScipyrectBivariateSpline)inference: given a new tuple (x1, x2) use the interpolation to predict (y)Note the first two part can be done offline, and the spline function saved for future use (factori... | KFrank | Hi Sebastien!
I am not aware of a built-in spline function being offered by pytorch.
If I understand your use case correctly, it is acceptable to fit the spline
function once, in advance of using pytorch, but you want to be able to
evaluate that pre-fit spline and backpropagate through it withi… |
hnakao | I would like to learn a piecewise linear non decreasing function where both input and output are one dimensional. This can be achieved by passing through a series of ReLU layers with some constraints on the weights and biases so that the slopes are always non negative.Can PyTorch implement this? If not, are there any a... | KFrank | Hi Hnakao!
This can certainly be done.
The most natural way to represent a piecewise linear function is as a
linear-interpolation look-up table. (If each linear piece is non-decreasing,
the overall function will also be non-decreasing.)
One concrete approach is illustrated in the below script… |
malfonsoarquimea | Hi! I have a trained model and now I would like to compute the gradient of the output with respect to the inputs. Based on this postpython - Getting the output's grad with respect to the input - Stack OverflowI am doing it like this:inputs.require_grad_()outputs=model(preprocessing(inputs))gradients= [torch.autograd.gr... | KFrank | Hi Malfonsoarquimea!
Here is what is probably going on:
If your model:
outputs=model(preprocessing(inputs))
maps a batch of inputs, say of shape [nBatch, N], to a batch of scalar
outputs of shape [nBatch] (or similar), and each batch element of
outputs depends only on the corresponding elemen… |
111414 | 1. Background:I can calculate the gradient ofxwith respect to a cost functionlossin two ways: (1) manually writing out the explicit and analytic formula, and (2) usingtorch.autogradpackage. Here is my example:import torch
import torch.nn.functional as F
for i in range(10):
x = torch.randn(8, 1, 128, 128)
y = t... | KFrank | Hi Bin!
To get the gradient of the result of one function applied to the result of
another function, that is, of the composition of two functions, you would
use thechain rule.This is how autograd computes the gradient when
many functions are composed together, such as the successive layers
… |
yuchiq | I have a fully connected layer in torch.self.fc = nn.ModuleList([nn.Sequential(nn.Linear(10, 1),self.activation)])In the optimizer, I want to assign different weight_decay for the parameters in this layer. Some thing like (not correct code here)optimizer = optim.Adam([{'params':self.fc.parameters()[0:5],'weight_decay':... | KFrank | Hi Paul!
If you want to use different values of weight_decay for different
parameters, use the parameter group facility of Optimizer.
However, if you want to use different weight decays for different
elements of the same parameter, things become more complicated.
The issue is that an entire te… |
Yeo_Wei_jie | I want to apply transfer learning by loading the state dict of one model to another. However, in the final layer which is a linear layer of 2D dim, i would like to randomly initalise it partially. Meaning say the linear layer is of size [3,256], how do i applytorch.nn.init.xavier_uniform_to only 20% of the parameters i... | KFrank | Hi Wei Jie!
You could use a number of approaches.
I would probably use multinomial() to choose which elements of
the Linear to partially initialize. Then, really just for convenience, I
would apply xavier_uniform_() to a temporary tensor of the same
shape as the Linear.weight in question. La… |
Anikily | for example,[[1. 0. 1. 0. 0. 0.],
[0. 0. 1. 0. 1. 0.]]and i want get[[[1. 0. 0. 0. 0. 0.],
[0. 0. 1. 0. 0. 0.]],
[[0. 0. 1. 0. 0. 0.],
[0. 0. 0. 0. 1. 0.]]]what is the elegant way to achieve this operation in pytorch? | KFrank | Hi Yu!
Yes, you are correct. That was my oversight.
We can explicitly tell one_hot() the number of classes, rather than
having it “guess:”
>>> onehot = torch.nn.functional.one_hot (multihot.nonzero()[:, 1].view (multihot.size (0), count), num_classes = multihot.size (1))
>>> onehot
tensor([[[1… |
Podidiving | Hello, everyoneI have the next code:feature = torch.randn(10, 20)
target = torch.randint(0, 4, (10,))
total = 0
for i in range(0, 4):
for j in range(i + 1, 4):
diff = feature[target == i].mean(0) - feature[target == j].mean(0)
total += torch.norm(diff, 2)Can you help me to optimise it? I feel, it can be done ... | KFrank | Hi Podi!
You need to address two issues to avoid explicit loops:
First, you have to rework feature[target == i]. This is because the
shape of feature[target == i] depends on the value of i. Because
pytorch does not support ragged tensors (tensors whose slices don’t
have the same shape), you … |
Anikily | Given a 2d tensor a.shape = (B, D), I want to randomly sample k elements from this tensor, so i write this code:a = torch.randn(B, D)
p = torch.ones((B, D))
index = p.multinomial(num_samples=k, replacement=True)The shape of index is (B, k) and the shape of a = (B, D), how can i index elements from a?i.e. out[i, j] = a[... | KFrank | Hi Yu!
torch.gather (a, 1, index) should do what you want.
Best.
K. Frank |
ChrisRahme | Hello!I’m new to machine learning and PyTorch, and I’m stuck on this error which seems really simple but I can’t find where to fix it:ValueError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_52832/2153252887.py in <module>
5 n_epochs = 10
6
----> 7 train_u... | KFrank | Hi Chris!
Based on your edits, it looks like you are on the right track.
Let me make some comments based on my speculation about your use
case and what you are trying to do.
Based on the name TissueDataset, the name UNet, and the use of
BCEWithLogitsLoss as your loss criterion, I assume that y… |
passiveradio | Thank you for reading my post.I’m a college student, and currently developing the peak detection algorithm using CNN to determine the ideal convolution kernel which is representable as the ideal mother wavelet function that will maximize the peak detection accuracy.I’ve tried to create my own IoU loss function for the ... | KFrank | Hi Passive!
As you have deduced, your IoU loss criterion is not (usefully) differentiable.
First, to clear up some context: Based on your thresholding value of
thresh = 0.5, let me assume that inputs (the output of your model)
are to be thought of as probabilities that range from zero to one (… |
Maxwell_Albert | Here is a question about how to do bit-wise change to pytorch tensor.I have a tensor with size [1,32] and type int16. But only 10 bits of 16 are useful.(since values are too small).And I want to change it bit-wise to tensor with size [1,10] and type int32, which means the data or the binary value are the same.How could... | KFrank | Hi Maxwell!
For what it’s worth, you can do this with pytorch’s bit-manipulation
routines, without converting to numpy.
Here is a pure-pytorch solution, similar in concept to Matias’s approach:
import torch
print (torch.__version__)
_ = torch.manual_seed (2022)
def weird_format (t10):
tbi… |
anotherone_one | Good afternoon!I have a model that has 6 classes on which each class has several possible labels. I wanted to ask if it is possible to give a list of weights for each label of each class.My model:class CNN(nn.Module):
def __init__(self):
super(CNN, self).__init__()
self.model = pretrainedmo... | KFrank | Hi Another!
Yes, you can weight your labels / classes individually.
But first, some context and terminology:
At a technical level, you are performing 6 multi-class classification
problems “in parallel.” What you call “6 classes,” I would call 6
classification problems. And what you call “sev… |
JiangtaoLiu | I tried to solved the very simple equation y = ax1 + bx2 + cx3 + d using nn.Linear. The pearsonr is only 0.331. But the sklearn’s LinearRegression gave me good results and its pearsonr is 0.943. Can someone tell me why? My code is as follows:(My torch.versionis ‘1.11.0’)from sklearn import datasets
import matplotlib.py... | KFrank | Hi Jiangtao!
First, your code doesn’t run for me – see below.
The problem is that your model returns pred of shape [nBatch, 1],
while MSELoss expects the shape to be [nBatch] (assuming that
train_y has shape [nBatch]).
You should use squeeze() to remove pred’s trailing singleton dimension:
lo… |
Andrew_Cirincione | Hello! I am currently working on a custom module inside my pytorch model. This module creates a gaussian kernel that is convolved across the models input, while the parameters of the gaussian kernel are to be learned. There is to be 256 x 256 gaussian kernels generated. Myinitfunction looks like this:def __init__(self,... | KFrank | Hi Andrew!
The parameters that are to be learned should be the Parameters of
your Module. gaussian_bank should just be a regular variable – not
a Parameter – because it is not being “learned” (optimized) directly.
(I assume that gaussian_bank is what you are referring to as your
“gaussian ke… |
SeoHyeong | Hi, I have this task in my hands where I have two tensors of the same two-dimensional size, let’s say tensoraand tensorb. I’d like to sort a and b (in the first dimension) so that the largest element of tensorbis multiplied by the largest element of tensora, and the second largest element of tensorbis multiplied by the... | KFrank | Hi SeoHyeong!
Yes. You can do this by multiplying the two sorted tensors together
(so that largest multiplies largest, and so on), but remembering the
“sorting indices” (the argsort()) of tensor a, and then using them to
“unsort” the product tensor so as to recover the original order of a:
>>>… |
TeDataPro | HeyI would like to add manualy an output layer to BERT in order to predict multiple features which are binary.For example, these outputs would answer the questions:Is the text positive? 1 if yes, 0 otherwise.Is this text about sports? 1 if yes, 0 if not.Is this text about business? 1 if yes, 0 if not.My first idea was ... | KFrank | Hi Te!
As you describe it, you are performing a multi-label, multi-class
classification. It is multi-class because you have three classes:
“positive,” “sports,” and “business.” It is multi-label because for
any given sample, none, some, or all of the classes can be active,
so each sample can… |
vahvero | Hi!I am currently doing a training with mask rcnn model and all outputmasksseem to be really bad compared to the label scores.In my training set most of the masks have one annotation inside an another. For example:A = torch.zeros((5, 5)).to(int)
A[1:4, 1:4] = 1
B = torch.zeros(
(
5,
5,
... | KFrank | Hi Vahvero!
This is perfectly reasonable for Mask R-CNN (although it may indicate
that you are working on a problem that is inherently more difficult to train).
Mask R-CNN performs instance segmentation. It is conceptually fine
to have instance-1 of class-A be contained in instance-2 also of … |
francescocarzaniga | I have a single tensor where all elements need to be elevated to each power contained in another tensor.Let’s say I have tensor A with shape [100], and tensor B with shape [64, 5]. Tensor A is my initial tensor, and tensor B contains a 64-batch of 5 elements.Tensor C should be [torch.pow(A, exp) for exp in batch for ba... | KFrank | Hi Francesco!
Use pytorch’sbroadcastingwith unsqueeze() to line the dimensions
up appropriately:
torch.pow (A.unsqueeze (-1), B.unsqueeze (1))
# or
torch.pow (A.unsqueeze (0).unsqueeze (-1), B.unsqueeze (1))
Best.
K. Frank |
welahi | Hello,I need to implement some kind of a “generalized MSE” loss, where I don’t just considerloss_mse(target, model), butloss_mse(O(target), O(model)), whereOis a rather complicated function.The problem is thatOdetaches the PyTorch-tensors as numpy, calls some different thrid-party libraries to calculate the result and ... | KFrank | Hi Welahi!
The best approach – if it’s doable – would be to rewrite your custom
loss O using (differentiable) pytorch tensor operations. Then you will
get autograd “for free.”
If this is not practical – maybe the stuff in your third-party libraries is
too complicated – you will have to write … |
Valentin_Fontanger | Hi !I need to build a tiny Deep Learning project for school and I am using pytorch to compare all of my modules.Most module returns to me the same gradient and output as pytorch and I am happy with that.But I fail all my tests involving my linear Module (wx + b)Here is my test :TestLinearModule(unittest.TestCase):
... | KFrank | Hi Valentin!
These two results are indeed different, and not just because of
round-off error.
Your problem is that the weight property of torch.nn.Linear is
stored as the transpose of how you store the _parameters property
of your Linear class. That is, pytorch’s weight has shape
[out_featur… |
jiwidi | I’m trying to port some code from keras to pytorch and I’m having some trouble achieving the same loss logic. I want to perform a simlar loss totf.keras.losses.CategoricalCrossentropy. TorchCrossEntropyLosshandles targets with an integer withnclasswhile keras does it with a onehot encoder, to overcome this I tried usin... | KFrank | Hi Jaime!
Keras / tensorflow’s CategoricalCrossentropy and pytorch’s
CrossEntropyLoss (more precisely, the function objects obtained
by instantiating these classes) take their prediction and target
arguments in the opposite order.
I believe for keras / tensorflow you want:
print(f"Loss with t… |
Qiyao_Wei | MWE below. I have also printed out c and d, so I am pretty sure they have the same elements. Am I misunderstanding something about comparing the difference between two tensors?import torch
a = torch.rand(3,2,5)
b = torch.rand(3,5,4)
c = torch.stack([a[i] @ b[i] for i in range(3)])
d = torch.einsum('bij,bjk->bik', a, b)... | KFrank | Hi Qiyao!
This is due toround-off error.
Your calculations for c and d are mathematically equivalent, but the
order of the operations differ (in a mathematically-equivalent way),
introducing numerical round-off error.
This can be seen by modifying your example to check not just for
exact equ… |
nn_beginner | Hi,I hope you can help. I am designing a controller for a system, where the controller NN is trained using an imported NN I made, which is the state space representation of the system.But it seems the weights are not updating on each epoch, I have attached the code below:This is my defined controller:class Net(nn.Modul... | KFrank | Hi Finn!
First, let me note that this second version you posted no longer has
loss.backward() in it. If that’s not just a typo, it would prevent your
weights from being updated.
Second, please post a simplified, fully-self-contained, runnable script
that illustrates your issue, together with … |
asabater | Hi! I have a multidimensional Tensor (4 or more dimensions) and I want to assign data to it based on given indices.E.g. in the tensormemI want to modify the 6 rows (3 rows of each dimension 0) with the indicesindicesand their final value must be the one given by the 6 rows onvalues.:mem = torch.zeros(2,4,5,6) ... | KFrank | Hi Alberto!
You may create a view into mem using pytorch indexing and then
assign values into mem through the indexed view:
import torch
print (torch.__version__)
mem = torch.zeros(2,4,5,6) # size -> (2,4,5,6)
indices = torch.Tensor([[[0, 0],[0, 1],[2, 1]], # size -> … |
jayz | Hello,so, imagine we have a 2d matrix input of shape m rows x n columns to a conv2d layer. My goal is to preserve the number of rows of the matrix while running the same kernel along each row.In more detail, say, we apply a conv2d layer with a kernel (1,k) to the matrix, then, the layer would in my understanding learn ... | KFrank | Hi Jay!
Is it possible that you misunderstand how Conv2d works?
Consider:
>>> import torch
>>> torch.__version__
'1.10.2'
>>> conv = torch.nn.Conv2d (1, 1, kernel_size = (1, 3))
>>> conv.weight
Parameter containing:
tensor([[[[-0.2149, 0.2000, -0.0982]]]], requires_grad=True)
>>> conv.bias
Para… |
learner47 | I have a neural network, which produces a single value when excited with input. I need to use this value returned by the network to threshold another array. The result of this threshold operation is used to compute a loss function (the value of threshold is not known before hand and needs to be arrived at by training).... | KFrank | Hi Learner!
The thresholding operation is not (usefully) differentiable with respect
to x. To train x you should use a “soft,” differentiable thresholding
operation. You may use sigmoid() as a 'soft," differentiable step
function. Thus:
thresholded_vals = data_array * torch.sigmoid (data_ar… |
Entropy | I am trying to train a U-Net for image segmentation. My dataset consists of 80x80 pixel images (so 6400 pixels per image), and each image can be segmented into 3 parts: primary background, secondary background, and a third class that can be any one of 9 separately defined classes. So I have 11 classes in total.My goal ... | KFrank | Hi Entropy!
The conventional wisdom suggests that you should weight each
class inversely to the number of samples (pixels) in that class.
Now your “third class” is actually nine “special classes.” Let’s
assume (since you don’t give the numbers) that those “special
classes” all appear about eq… |
S_M | Hi allWhile I am using the following code on Cuda, where A and B are 2D tensors with shape [128,128].C = A.pinverse().matmul(B)I get the error,svd_cuda: the updating process of SBDSDC did not converge.how can I handle this error?Any help would be appreciated. | KFrank | Hi S!
First, to be clear, this is not about whether A is invertible. The whole
purpose of the pseudo-inverse (torch.pinverse()) is to perform a
mathematically useful operation even when the matrix is not invertible.
(And the pseudo-inverse coincides with the regular matrix inverse
(torch.inve… |
Alan_lam | I am building a CNN model with residual network achidecture for input images with different dimension. At the same time, I want to make sure the output has the same dimension as the input.In the forward pass of the Generator object, I declare a list objectsize_listto store the dimension of the tensors during its down-s... | KFrank | Hi Alan!
Yes, that is correct.
You do pass in an output_size argument when you instantiate
Transpose_Block (but it doesn’t make sense to try to do it this way).
However, you do not pass in output_size when you instantiate the
ConvTranspose2d block property of Transpose_Block. Instead,
you pa… |
Adam007 | Hi I have a question about ConvTranspose2d, in which situation would you use ConvTranspose2d over conv2d ? Or in which situation I SHOULD use ConvTranspose2d? | KFrank | Hi Adam!
In general, if you are building a “conventional” convolutional network
(whatever that means), you should use Conv2d.
The noteworthy use case for ConvTranspose2d that I am familiar with
(I’m sure that there are others.) is in the U-Net architecture, where it is
used as an “upsampling” … |
yegane | Hi,I have an NxM matrix (A) and another NxM matrix (B). The values of B are labels for values of A.If I have C number of labels in B. Is there a simple GPU-friendly operation that takes the average of all elements of A that have the same labels in B, and then maps them into a vector with the size of Cx1? Can I make it ... | KFrank | Hi Yegane!
One approach is to extend both A and B along a new “class” dimension
(using expand() and one_hot(), respectively). The one-hotted version
of the labels tensor is used as a class mask for the values tensor so that
per-class sums and counts can be computed, and from them, averages.
H… |
Waffles | I have two tensors of 3 features that are linked to their own rank values.I’m attempting to predict & learn in a pairwise fashion if I have a lower or higher rank match, however, it seems my problem is I cannot compute my gradients?(The model here is simplified for debugging purposes.)I was hoping someone could give me... | KFrank | Hi Phil!
As written, I believe than neither left nor right is defined in your function
custom_loss() (nor elsewhere in the code you posted), so I don’t think
that your code will run at all.
If you fix that (in a sensible way), gradients should backpropagate through
custom_loss().
Best.
K. Fr… |
magicaltoast | Hi, I have two tensors with shapes (20,10) and (Batch, 10) and I want to multiply them to get out the shape (Batch, 20, 10). I can easily do it without the batch dimension like this(torch.rand(20, 10) * torch.rand(10))but I can’t make it work with batch | KFrank | Hi Damian!
Use unsqueeze() to line up the dimensions appropriately, and then let
pytorch’sbroadcastinghandle your batch dimension:
>>> import torch
>>> torch.__version__
'1.10.2'
>>> (torch.rand (20, 10) * torch.rand (6, 10).unsqueeze (1)).shape
torch.Size([6, 20, 10])
Best.
K. Frank |
osama-usuf | I have a task where I perform an operation over individual elements of the network gradient.For a fully-connected layer, I have anm x ngradient matrixG. I have an equivalentm x nupdate matrixP.Elements ofGandPmap one-to-one i.e. thatP_{ij}dictates how to updateG_{ij}I have gotten this to work with a nested loop, but th... | KFrank | Hi Osama!
In general, if you want to apply a function element-wise to the elements
of a pytorch tensor and that function is built up of “straightforward” pieces,
it will usually be possible to rewrite that function in terms of pytorch tensor
operations that work on the tensor as a whole (elemen… |
folterj | Hi, we use convolutional networks (like shufflenet) and are training single, multi-label and (single label) multi-class PyTorch models. We also need probability values for each prediction.We would like to check best practice for these cases, and we haven’t found a clear answer online so far.Describing each scenario:Sin... | KFrank | Hi Joost!
You may treat a binary problem as a two-class multi-class problem,
and then you would use CrossEntropyLoss just as you would for
a more-than-two-class multi-class problem.
But it’s a little clearer and modestly more efficient to treat it explicitly
as a binary problem. in which case … |
ferrophile | Consider a single linear layer as follows.xandware vectors of the same size, and will be the input / weight of this layer.x = torch.rand(1, 63)
w = torch.rand(1, 63)
fc = Linear(63, 1, bias=False)Suppose I evaluate the following block:permute = np.random.permutation(63)
fc.load_state_dict({'weight': w}, strict=False)
v... | KFrank | Hi Hong Wing!
This is due to floating-point round-off error. Repeat your experiment
using double precision and your “slightly different numbers” will agree
to about twice as many decimal places as they do in the single-precision
example you posted.
Best.
K. Frank |
pietz | Let’s say I have two very sparse binary images (0 is much more frequent than 1) and I want to calculate the per-pixel precision and recall of the two masks agreeing with each other. Basically asking: Where are the masks equal given that a pixel in A is true and the same given for B is true. We could do that along the l... | KFrank | Hi Pietz!
Apply your a == b test to a max-pooled version of b:
>>> import torch
>>> torch.__version__
'1.10.2'
>>> _ = torch.manual_seed (2022)
>>> b = (torch.randn (1, 1, 10, 10) > 1.7).float()
>>> b
tensor([[[[0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0., 0… |
umbriel | I want to copy tensor elements to another tensor at positions given by indices along given dimension.Example:A = [[3, 2, 1], [2, 4, 5], [6, 3, 2]]B = [X, Y, Z]Index = [0, 2, 1]Dim = 1Result should be: [[X, 2, 1], [2, 4, Y], [6, Z, 2]]What’s the best way to achieve this?Thanks! | KFrank | Hi Umbriel!
You could use indexing with assignment:
>>> import torch
>>> torch.__version__
'1.10.2'
>>> A = torch.tensor ([[3, 2, 1], [2, 4, 5], [6, 3, 2]])
>>> B = torch.tensor ([100, 200, 300])
>>> Index = torch.tensor ([0, 2, 1])
>>> A[torch.arange (3), Index] = B
>>> A
tensor([[100, 2, 1]… |
Omroth | I have a tensor of shape [5sx,5sy,5*sz] and I’d like to create a tensor with shape [sx,sy,sz] where the value of each element:new_tensor[x,y,z] = mean(old_tensor[5x:5x+5,5y:5y+5,5z:5z+5])Preferably in one instruction that’s fast (and followed by autograd)Any ideas?Thanks,Ian | KFrank | Hi Ian!
You might prefer to use AvgPool3d. You can view it as a special
case of Conv3d:
>>> import torch
>>> torch.__version__
'1.10.2'
>>> _ = torch.manual_seed (2022)
>>> t = torch.randn (5, 10, 15, requires_grad = True)
>>> torch.nn.AvgPool3d (5) (t.unsqueeze (0).unsqueeze (0)).squeeze (0).s… |
barthelemymp | Hello,I’m was making a neural network to to try a few option of pytorch, and then when I tried it on the classical Breast Cancer dataset my algo was just stuck. I simplified to the maximum my model, but accurracy seem to be blocked.my model:class Modela(torch.nn.Module):
def __init__(self):
super(Modela, se... | KFrank | Hi Barthelemy!
Let me speculate that you are building a binary classification
model – i.e., some sample either is or is not breast cancer, based
on some kind of input features taken from a breast-tissue sample.
(Your last layer, self.l3, has two outputs, suggesting that this
may be binary.)
… |
Hongnan_G | In PyTorch’s recent vision examples here:vision/transforms.py at main · pytorch/vision · GitHubandvision/train.py at main · pytorch/vision · GitHub, it was shown how to useMixupwith the pipeline. I noticed when trying to use theirMixupfunction on my own thatCrossEntropyLossin general don’t expect targets to be of one-h... | KFrank | Hi Hongnan!
Possibly relevant to your issue:
As ofversion 1.10, CrossEntropyLoss supports probabilistic targets (in
addition to integer-class-label targets). One-hot-encoded targets can be
understood as a special case of probabilistic targets. Earlier versions did
not support probabilistic … |
L-Reichardt | Dear Forum,Is it possible to create a scalar that is only trained during n-amount of batches? I would create my scalar alpha (init. at 1) through:alpha = nn.Parameter(torch.ones(1, requires_grad=True))Am I correct to assume that the value of alpha then changes during training, e.g. becomes 0.9? Or did I set this up inc... | KFrank | Hi L!
There are a number of ways to do this. I would probably use two
separate optimizers:
optModel = torch.optim.SGD (myModel.parameters(), lr = 0.1)
optAlpha = torch.optim.SGD ([alpha], lr = 0.1)
(This assumes that alpha is not one of myModel’s parameters.)
Now you can call optModel.step() … |
Tobias_Kalb | Hi, I am trying to extend an exisiting trained nn.Linear() layer by new output units, as I want to train it for new classes as well. So the idea is to simply add output units to the existing ones. However, in my current implementation (see below) the output for the existing classes is not exactly the same as from the i... | KFrank | Hi Tobias!
As you suspect, this is very likely floating-point round-off error.
As the size of a tensor changes, pytorch can change the details of
how it pipelines tensor operations, both on the cpu and gpu. This
can cause operations to be reordered in a way that is mathematically
equivalent, … |
luke0 | Hi, I’m trying to run a cnn for image classification. Very new to this, so using a mashup of tutorial code and my own inputs. I get this error when I try to run:mat1 and mat2 shapes cannot be multiplied (12x403328 and 1266750x120)All my image inputs are 750x563 jpgs.Torch size is:Shape of X [N, C, H, W]: torch.Size(... | KFrank | Hi Luke!
By the time you get to fc1 – where the error is occurring – your images
are no longer of the same size as when passed into forward().
Conv2d changes (reduces) the size of your image.
MaxPool2d also reduces the size of your image.
In forward(), print out the shape of x (initially yo… |
drydenwiebe | Hello,Right now I have pseudo-labels for an image dataset from DeepLabV3+ that are of shape [H W, 1] where each pixel is an integer from 0 to 18 representing the class of the pixel (using cityscapes pretraied models).Now, what I want to do is focus on only a few classes (say for example, 10, 12, 13) and map the rest of... | KFrank | Hi Dryden!
You therefore want four classes, “background”, “class 10”, “class 12”, and
“class 13.” You should then label them with with the four integer class
labels 0, 1, 2, 3.
Set up a translation table that maps the integers {0, 1, 2, ..., 17, 18}
to your desired smaller set of class labels… |
Koramajin | Hi, I’ve got high absolute error in torch.matmul. Here is my exmaple code.import torch
from torch import tensor
def main():
torch.cuda.manual_seed(42)
mask = tensor([[0., 0., 0.], [1.0, 0., 0.]], device='cuda')
matrix = torch.randn(3, 3, device='cuda')
print(matrix)
res = torch.matmul(mask, matri... | KFrank | Hi Koramajin!
I made a mistake in my earlier post – see the edit, above.
Please try specifically setting the TF32 flag to False:
torch.backends.cuda.matmul.allow_tf32 = False
and see if that resolves the issue.
(Sorry for the earlier mistake.)
Please note: My understanding is that your A100 … |
Olivier-CR | I am working on Audi A2D2 dataset 2D segmentation.The segmentation mask are provided as 3-channel, RGB images (despite having only 55 classes).In order to process the labels faster in my data loader, I’d like to open them as grayscale even though they are RGB. Because there are only 55 different RGB pixel values, it sh... | KFrank | Hi Olivier!
Yes, the risk is real, and such an occurrence is in fact quite likely: See the
so-called“birthday paradox.”If the person who prepared the segmentation masks were kind, then he
could have purposely chosen RGB values that map to distinct grayscale
values. (And if he were diabolic… |
J_Johnson | Suppose I have a tensor of images as follows:A=torch.rand(10, 3, 28, 28)And suppose I have another tensor that I want to be multiplied elementwise by all images and layers of A as follows:B=torch.rand(28, 28)Is there an easier/faster/more efficient way to do this,insteadof the following?:B=torch.cat([torch.cat([B.unsqu... | KFrank | Hi J!
You may use the expression for element-wise multiplication, C = A * B,
and pytorch will usebroadcastingto multiply all of the images and channels
in A by B.
Note that broadcasting treats “missing” leading dimensions as if they were
singleton dimensions, so C = A * B.unsqueeze (0).unsqu… |
AlphaBetaGamma96 | Hi All,I’ve been looking for an equivalent determinant function that computes the determinant of a Vandermonde Matrix. In short, the Vandermonde determinant scales better than a standard determinant due to the fact that the matrix is restricted.Such a determinant is defined as,wherexis a vector of lengthn.I’ve written ... | KFrank | Hi Alpha!
I doubt that your nested-loop version scales worse that det(). Your
version scales in time as n**2 (just count the number of times through
the loop), while det() scales as n**3. Of course for moderate values
of n your python-loop version is indeed likely to be much slower than
det(… |
duyducvo4444 | Hello all~With torch.arange(start=1, end=4) I will have a tensor [1, 2, 3]Now if I want to replace the ‘start’ parameter’s value with a tensor, how can I do that without doing the loop?for example if I have a=[[1], [2]]If I write torch.arange(start=a, end=a+3)I want to obtain[[1, 2, 3],[2, 3, 4]]Is it possible to do th... | KFrank | Hi Duy!
You can add the desired start values to the result of arange(), and do
so on a tensor basis:
>>> import torch
>>> torch.__version__
'1.9.0'
>>> start_values = torch.tensor ([1, 2, 5, 7])
>>> torch.arange (3).repeat (4, 1) + start_values.unsqueeze (1)
tensor([[1, 2, 3],
[2, 3, 4],… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.