user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
jarvico | Hi, I need to calculate backward derivative of output tensor with respect to a batch of input tensor.Here is the details:Input shape is 64x1x28x28 (batch of mnist images) output shape is 64x1.Output is calculated based on some logic using the outputs of feedforward operation.So actually, for each image of shape 1x1x28x... | ptrblck | That would be the usual use case, wouldn’t it? The samples in a batch are independent from each other (besides batch-dependent layers such as batchnorm layers).
If I understand it correctly, your single sample approach would look like this:
# setup
x = torch.randn(64, 2, requires_grad=True)
mode… |
davidsriker | I have a custom dataset class where I apply some transforms.My definition of the transforms are:train_transform = {'img': transforms.Compose([transforms.Resize(Polyp.IMAGE_SIZE),
transforms.RandomVerticalFlip(),
... | ptrblck | If you want to apply the same “random” transformation to the data and target, I would recommend to use the functional API as seenhereand to avoid depending on the seeding. |
Song1 | Hi, I started studying pytorch recently and I’m stuck in a problem. The codes below trains w[0], …, w[8] which are the 2 * 2 elements of a weight matrix. The weight matrix is in the function named forward. I want to train w[1], …, w[8] to produce y from a. But after operating the codes, an error occurred. It is ‘Runtim... | ptrblck | If you create a new tensor, you will detach the inputs from the computation graph.
The creation of your matrix tensor might be the issue here.
Could you try to rewrite the creation using torch.cat instead?
Let me know, if that helps or if we need to dig a bit deeper. |
comely420x | I am sorry if this is a very simple question. How do I initialize the weights of my network such that the weights are produced by the softmax function on the learnable log-probabilities? | ptrblck | You could create the desired initial weights using any method and copy them into the model parameter via:
my_weight = ... # your method to create the initial weights
with torch.no_grad():
model.my_layer.weight.copy_(my_weight) |
grid_world | I am using Python 3.8 and PyTorch 1.7.1. I saw a code which defines a Conv2d layer as follows:Conv2d(3, 6, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)The input ‘X’ being passed to it is a 4D tensor-X.shape
# torch.Size([4, 3, 6, 6])The output volume for this conv layer is:c1(X).shape
# torch.Size([4,... | ptrblck | The formula to calculate the output shape is given in thedocs.
Your posted formula is missing the dilation and the subtraction of the constant 1s.
Also, note that the floor operation is used as indicated by the brackets. |
rcshubhadeep | Hello All,I have been trying to classify two sets of images. Which are pretty close in looking to each other. One set of image is image of GUI buttons (mainly desktop)Another set is textboxes (mainly desktop as well)I have 40 images per class inside my train set and 10 per class in my validation set.I have taken (almos... | ptrblck | This might be expected, if your overall training is unstable and you would have to play around with some hyperparameters. Also, if you don’t seed the code and don’t force it to be deterministic, slight variations are expected. In the best case your training would be stable enough to yield approx. t… |
cbd | Lets say “a=torch.rand(1,4,2,2)” and “count_a=torch.zeros(4)”.I want count of non zero of a(0,0,:,: ) to store in count_a(0), a(0,1,:,: ) to store in count_a(1) etcIf i used below code it stores total non zero count of “a” in to “count_a”.Code:import torchcount_a=torch.ones(4)a=torch.rand(1,4,2,2)count_a=torch.count_no... | ptrblck | Thanks for the clarification!
I misunderstood the [4, 4, 4, 4] output as the shapes, not the values.
In that case, you could flatten the last two dimensions and use the dim argument in count_nonzero:
a = torch.rand(1,4,2,2)
count_a = torch.count_nonzero(a.view(1, 4, -1), 2)
print("a value is ",a… |
jmontoyaz | Hi everybodyI’m getting familiar with training multi-gpu models in Pytorch. I found this official tutorial onbest practices for multi-gpu training. I adapted the original code in order to return two predictions/outputs and use two losses afterwards. Predicted values are on separate GPUs, also note that the model uses 2... | ptrblck | You would have to push the calculated losses to the same device before summing them.
This should work:
loss = loss_fn(outputs1, labels1) + loss_fn(outputs0, labels0).to('cuda:1') |
pavel1860 | hi, I’m pretty new to pytorch and I am trying to fine tune a BERT model for my purposes.the problem is that the.to(device)function is super slow. moving the transformer to the gpu takes 20 minutes.I found some test code on pytorch github repoimport torch
import torch.nn as nn
import timeit
print("Beginning..")
t0 =... | ptrblck | You are most likely running into the JIT kernel compilation, since you are not using sm_80 or sm_86 in your binaries due to CUDA10.1.
Use the CUDA11.0 binaries and the startup time should be gone. |
Bahaa_Kattan | I am training my model on multi-class task usingCrossEntropyLossbut I’m getting the following error:ValueError: Classification metrics can't handle a mix of multiclass and continuous-multioutput targetshere is my training loop:for i, batch in enumerate(iterator):
text = batch['sequence']
features = batc... | ptrblck | The error is raised by a sklearn metric method, which gets unexpected inputs.
Your current code snippet doesn’t show it’s usage, so you would have to check the docs of the method and make sure to pass the right input values.
My best guess is that the metric method expects predictions, not logits. |
Carsten_Ditzel | Trying to combine several loss function in a dict called loss like soerr = torch.sum(torch.stack([l(input, label) for l in loss.values()]))I am wondering if this breaks the connection for back propdebugging tells me<bound method Tensor.backward of tensor(17353.5000, device=‘cuda:0’, grad_fn=)>which look ok but I am not... | ptrblck | Your approach seems to work and I get valid gradients:
output = torch.randn(1, 1, requires_grad=True)
target = torch.randn(1, 1)
loss = {i: nn.MSELoss() for i in range(10)}
err = torch.sum(torch.stack([l(output, target) for l in loss.values()]))
err.backward()
print(output.grad)
> tensor([[-6.1927… |
Mona_Jalal | It just occured to me that this could be a PyTorch incompatibility problem. Could you please guide how to fix it?I am trying to run the demo code in this repository. I haven’t changed the code. How can I fix this error?GitHub - vchoutas/expose: ExPose - EXpressive POse and Shape rEgression(expose) mona@goku:~/research/... | ptrblck | This code:
File "/home/mona/research/code/expose/expose/utils/plot_utils.py", line 831, in __call__
valid_mask = (color[3] > 0)[np.newaxis]
expects color to have 4 values, as it indexes it with 3. Based on the error message color contains only 3 values, which is why the error is raised.
I don… |
nluedema | I noticed some big differences in the runtime of Conv1d when using different values for out_channels. Below you can see three tests I ran with different out_channel sizes.import torch
import timeit
class CNN(torch.nn.Module):
def __init__(
self,in_dim, out_dim,kernel_size,
):
super().__init__()... | ptrblck | cudnn might use different kernels for different setups (input shape, conv setup). In your example, a matrix multiplication kernel should be used and on my machine these kernels are used:
CUDA Kernel Statistics:
Time(%) Total Time (ns) Instances Average Minimum Maximum … |
bing | Hi,I am trying to run inference on an image classification task for 4 images.I am gettingFile "inference.py", line 88, in accuracy test_correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred)).cpu().numpy())) # noqa RuntimeError: shape '[1, 1, 4]' is invalid for input of size 12I am quite not sure where I am... | ptrblck | You are currently calculating the max in the batch dimension, which seems to be wrong as you would usually compute the predictions by taking the argmax in the class dimension.
This should work:
output = model(data).squeeze() # output.shape == [12, 4]
preds = torch.argmax(output, dim=1) # preds.sha… |
Kaustubh_Kulkarni | I am not able to understand exactly what input needs to be given to the LSTM layer. It expects a state computed from before but I do not have these states. How do I proceed with the forward function? For now, this is the model and it gives me an error that says:AttributeError: 'tuple' object has no attribute 'size'.cla... | ptrblck | The nn.LSTM module expects inputs as:
input of shape (seq_len, batch, input_size): tensor containing the features of the input sequence. The input can also be a packed variable length sequence. Seetorch.nn.utils.rnn.pack_padded_sequence()ortorch.nn.utils.rnn.pack_sequence()for details.
h_0 of… |
Riccardo_Taiello | Hi I don’t why this happens, someone can help me? Thanks in advance.class MyEnsemble(nn.Module):
def __init__(self, n_clients):
super(MyEnsemble, self).__init__()
self.models = nn.ModuleList([MyModelA() for _ in range(0,n_clients)])
def forward(self, x1, id):
output = self.model... | ptrblck | The optimizer already executed its step() method using the calculated gradients from the output.backward() call and thus manipulated the parameters.
all_losses stores these output tensors (losses) and tries to calculate the gradients again, which won’t work since the parameters were already updated… |
aknirala | By default parameter inPlace for nn.LeakyRelU has been set to False. I was wondering what are the repercussions for that, and why that is the default behavior?I believe if we do not explicitly set it to True then a bit more memory would be used as a copy of that particular layer would need to be saved. LeakyRelu should... | ptrblck | Inplace operations can overwrite values required to compute gradients and might thus yield an error message such as:
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [1024]], which is output 0 of LeakyReluBackward1, is … |
FTravi | Hello everyone,I’m new to torch/PyTorch, and I’m currently trying to translate a script in Lua + torch into Python + PyTorch. The script in question implements a visual search model from a paper, and it can be foundhere.The model that’s used is Caffe VGG16, but it’s loaded through torch.Since it’s visual search, there ... | ptrblck | I’m not sure what you mean.
My argument is, that the feature extractor should yield an empty activation in both frameworks, if the model is created correctly and all parameters are equal.
I guess Caffe/Lua might use another rounding approach in calculating the output shape, which could yield a 1x… |
Degs | I am running into an issue where I have a custom convolutional layer usingnn.Unfold, which I get the same values comparing with a regularnn.Conv2dwith the same weights initialized.However, if I replace the layer when training a network, the weights seem not to be optimized as the regular nn.Conv2d do, causing the netwo... | ptrblck | torch.unfold or nn.Unfold would propagate the gradients.
Could you post your custom implementation of the conv module, so that we could have a look? |
Rohit_Modee | Before modification NetG_network = torch.nn.Sequential(torch.nn.Linear(lh1, lh2),torch.nn.CELU(0.1),torch.nn.Linear(lh2, lh3),torch.nn.CELU(0.1),torch.nn.Linear(lh3, lh4),torch.nn.CELU(0.1),torch.nn.Linear(lh4, lh5))After modification for debugging.class G_network(nn.Module):
def __init__(self, lh1, lh2, lh3, lh4, ... | ptrblck | Your model works fine using this code:
class G_networkDef(nn.Module):
def __init__(self, lh1, lh2, lh3, lh4, lh5):
super(G_networkDef, self).__init__()
self.fc1 = nn.Linear(lh1, lh2)
self.fc2 = nn.Linear(lh2, lh3)
self.fc3 = nn.Linear(lh3, lh4)
self.fc4 =… |
tyb_10 | Hi,I get NaNs when I run my training in Mixed precision training mode.I have pointed the error at the following placetorch.nn.functional.grid_sample(input, grid, padding_mode="zeros",
mode='bilinear',
align_corners=True,)when I change the sampling mode tonearest, it does not happ... | ptrblck | float16 can easily overflow if you are using values with a value close to the min. and max. values:
torch.finfo(torch.float16).max
> 65504.0
E.g. this code snippet overflows in the second approach and yields Infs in the result after applying torch.mm:
x = torch.randn(1024, 1024, device='cuda').ha… |
Dwight_Foster | Are you passing a input with cuda into the model? | ptrblck | Make sure to assign the tensor, as the to() operation won’t work inplace on tensors:
x1 = x1.to('cuda') |
mukul_01 | Hello all,I have query regarding the placement of optimizer.zero_grad() and optimizer.step()for idx in range(epoch):for kdx in range(batch):y_pred = model(X)loss = loss_fn(y_pred,y_target)optimizer.zero_grad()loss.backward()optimizer.step()Do we need to call them once for every epoch or for every batch iteration? | ptrblck | It depends on your use case.
The usual approach would be to zero out the old gradients, calculate the new gradients via backward(), and update the parameters via optimizer.step() for each batch (so once per iteration).
However, you could simulate a larger batch size by accumulating the gradients u… |
msee19018 | I trying to prune a custom built Lenet() Model. I first train model for 15 epochs on mnist data. Then I try to remove filters with minimum L1 norm. I am doing this by copy the weights of filters I want to retain in a list then I create a new model of Lenet with less number of filters and then I try to copy trained weig... | ptrblck | I would not recommend to use the .data attribute, as it might yield unwanted behavior and/or other issues.
Instead, wrap the parameter manipulation into a with torch.no_grad() block:
model1 = LeNet(3,16)
a = torch.rand_like(model1.conv1.weight[0]).requires_grad_(True)
a1 = torch.rand_like(model1.c… |
wuchiz | I trained the mode in mixed precision. in certain function, a input tensor in float16 is transformed into float32 after torch.norm截屏2021-02-04 下午4.36.25974×688 101 KBdis_vec (float16) dis (float32)and if I use dis=torch.sqrt((dis_vec**2).sum(-1)), dis is also float32 | ptrblck | If you want to apply the norm using float16 values and are sure that you won’t run into numerical issues, you could disable autocast for this operation and manually cast it to the desired type (you can use nested autocast decorators). |
digiamm | Hy guys, I am having a runtime error withlibtorch. I am getting a video stream and I want to get the probability out for my classification problem. The program runs for the first 4/5 frames and then it crashes.This is what I am doing:void MyClass::prob(const cv::Mat& img, const bool cuda){
torch::Tensor img_tensor ... | ptrblck | Did you try to add the suggested clone() operation to the code?
E.g. start at the beginning by adding it to the torch::from_blob() operation and try to isolate the line of code, which raises the error. |
shihanmax | Hey everyone!I have a question of selecting/changing values by some specific indices.Here is an example:import torch
"""
The original tensor is like this:
t = torch.tensor(
[[99, 2, 1, 3, 4],
[1, 2, 3, 99, 4],
[4, 1, 99, 2, 3]]
)
I want to change t's value with rule:
for each row, set elements which is... | ptrblck | The desired target doesn’t match the description:
for each row, set elements which is before 99 to 1; 0 otherwise,
since the 99 in the first row is set to 0, while the others are not.
Assuming you would like to set the value at 99 to 1, this code should work and would avoid the loop:
t2 = torch.… |
OasisArtisan | So I’m working on a project where I had to modify NCCL a bit to serve my purpose.Now my question is how would I force pytorch to use my version of NCCL?To start with, Is NCCL dynamically linked so pytorch would automatically link to any version of NCCL available? or is it statically linked that I need to recompile Pyto... | ptrblck | You can seeherethat NCCL is statically linked to the binaries and can take a look at the repository for more information about the build process. |
morphism | Dear everybody:Usually, we separate input data into three, which are training set, validation set, test set in deep learning.For each epoch, I want to do the best way to get a better model using validation set.For example, for each epoch, after finishing learning with training set, I can select the model parameter whic... | ptrblck | Yes, this is a common technique and is called early stopping. You would store the model’s state_dict for the lowest validation loss (or highest validation accuracy).
No, you shouldn’t do it, since mixing the training and validation set would give you a better “validation” loss than you would expe… |
Elocin | Hi, I’m having problem training network of the following structure (structure inspired by a recent paper):Given input X, Y, we want to first find a hidden variable based on X:X → fc1 → fc2 → hiddenThen we want to slice the hidden variable so that we can assign them as weights/bias to fc3, fc4And then we compute:Y → fc3... | ptrblck | Assigning the tensors to the state_dict keys won’t change the actual parameters, if you don’t reload the state_dict.
Based on the description of the use case, I think you could use the functional API and directly use the fc3 parameters:
fc3weight = (weights[0:100]).reshape([1, 50,2])
fc3bias = wei… |
Ankur_Singh1 | I have video data stored in a Numpy array each of shape (1, 16, 100, 100, 3). The array is huge and every time I load it, I get a memory error.Is there a way using Pytorch to load these videos in batches without actually loading the Numpy array so that I don’t get the memory error.Thanks. | ptrblck | Assuming this numpy array is stored locally as an npy file, you could use np.load with themmap_mode, which would allow you to load sliced from the disc without reading the whole array into memory:
mmap_mode {None, ‘r+’, ‘r’, ‘w+’, ‘c’}, optional
If not None, then memory-map the file, using the g… |
Jimmy2027 | Hi, I have a highly imbalanced image dataset and would like to use the WeightedRandomSampler to sample from my dataset such that the model sees approximately each class the same number of times. However since my classes are sicknesses present in some images, I have three classes for three sicknesses and a class for no ... | ptrblck | The WeightedRandomSampler expects a weight tensor, which assigns a weight to each sample, not the class labels.Hereis an example of its usage.
Based on your description it also seems that you are working on a multi-label classification, where each sample might belong to zero, one, or more classe… |
durden | Hi,Let’s say I have a tensor with shape (32,), e.g.X = [ 0.0379, -0.0372, 0.0277, -0.1918, -0.0679, 0.0858, 0.0655, 0.2807,
-0.1375, -0.0066, 0.1309, 0.0893, 0.0757, 0.1891, 0.2998, -0.1810,
-0.0809, 0.1543, -0.0852, -0.1351, 0.0900, -0.1985, -0.0525, 0.0582,
0.0410, 0.3986, 0.3757, 0.244... | ptrblck | You could use np.digitize to create the indices of the bins and then use the one_hot method as seen here:
x = np.array([ 0.0379, -0.0372, 0.0277, -0.1918, -0.0679, 0.0858, 0.0655, 0.2807,
-0.1375, -0.0066, 0.1309, 0.0893, 0.0757, 0.1891, 0.2998, -0.1810,
-0.0809… |
hongjunchoi | Hi, I’d like to make the dataloader that samples the minibatch consists of specific class all the time.For example, if the batch size 32, and the class label is 4(cat, dog, truck, ship), I want to make the minibatch as 4examples of cat, 12 examples of dog, 4 examples of truck, 12 examples of ship.Is there any solution... | ptrblck | You could create a custom sampler, which is responsible to create the indices passed to Dataset.__getitem__. This custom sampler could use the target to create the valid indices for each batch such that the desired classes will be used. |
amaleki | considera=torch.tensor([0, 1, 2, 3, 4], device='cuda')
b=torch.tensor([4, 5, 6, 7, 8], device='cuda')
c=torch.tensor([0, 0, 0, 1, 1, 3, 4], device='cuda')how can I getd=torch.tensor([4, 4, 4, 5, 5, 7, 8], device='cuda')without converting to regular list, or offloading to cpu?(if they were regular lists, something as si... | ptrblck | torch.gather should work fine:
b = torch.tensor([4, 5, 6, 7, 8], device='cuda')
c = torch.tensor([0, 0, 0, 1, 1, 3, 4], device='cuda')
res = torch.gather(b, 0, c)
print(res)
> tensor([4, 4, 4, 5, 5, 7, 8], device='cuda:0') |
spring | Hi,I want to apply the residual link used in ResNet([1512.03385] Deep Residual Learning for Image Recognition) to a simple model. Can I just add the input x and the output value passed through the linear layer in the element-wise direction as shown below?Is there anything else I need to do more?class neuralNet(torch.nn... | ptrblck | Seems to be a double post fromherewith a potential answer. |
spring | Hi,I want to apply the residual link used in ResNet to a simple model. Can I just add the input x and the output value passed through the linear layer in the element-wise direction as shown below?Is there anything else I need to do more?class neuralNet(torch.nn.Module):
def __init__(self, input_size, hidden_size, ... | ptrblck | Your approach should work and the torchvision implementation of ResNet uses a similar approach as seenhere. |
Feng_Liang | Hi! I am now trying to measure some baseline numbers of models on ImageNet ILSVRC2012, but weirdly I cannot use pretrained models to reproduce high accuracies even on the train set. It seems my preprocessing is correct. Can you please point out what goes wrong my codes? Thank you very much!import numpy as np
import tor... | ptrblck | If you are trying to reproduce the evaluation performance, I would recommend to call model.eval() so that dropout would be disabled and the internal batchnorm stats would be used.
Theofficial ImageNet codehas also an evaluation mode, which should reproduce the numbers. |
PhysicsIsFun | Hello community,I am working on a simulation with different interacting neural networks. Down below you see a training procedure of this whole system.Without going into the details of what I am trying to do, I want to know why the termtheta_1.data - theta_m.dataevaluates to 0 the whole time (see code below). It is supp... | ptrblck | Yes, in your approach you would clone the reference to one model and thus all nrworkers models would refer to the same parameters.
My approach initialized nrworkers different models, which is your desired behavior, if I understand the use case correctly.
Here is a small example:
# reusing the sam… |
jerly-hjzhou | import torch
from LeNet5 import LeNet5
model = torch.load('LeNet5.pth') # 加载模型
layerWeight = model.state_dict()['conv1.0.bias'].clone()
print("----layerWeight is ",layerWeight)
print("----model is ", model.state_dict()['conv1.0.bias'])
model.state_dict()['conv1.0.bias'][0] = 1
print("++++layerWeight is", layerWeigh... | ptrblck | The error is raised, since you are not calling the model.state_dict() method.
That being said, a direct assignment will most likely not work and you could use:
sd = model.state_dict()
sd[key] = layerWeight
model.load_state_dict(sd)
instead. |
Yun_Lee | Hi,I want to change pixel value in random way! (pixel-shuffling)For example,if I use CIFAR10 data,then I could get [3,32,32] pixel tensors, and each pixel can get integer value between [0~255]What I want to do isI want to make new mapping! for 256 values. This can be named pixel-shuffling.for example, [0,1,2,255] → ran... | ptrblck | You could probably directly index the mapping as seen here:
# create input
x = torch.arange(2*3*32*32).to(torch.uint8)
x = x.view(2, 3, 32, 32)
print(x)
# create mapping by shifting it by 1
mapping = torch.arange(0, 256, dtype=torch.uint8) + 1
# mapping[index] would contain the new value
# index … |
mohit117 | I have tensors of BxCHxW where B is the batch. Then are the following codes equivalent?l1_loss = torch.nn.L1Loss()
loss = l1_loss(pred,gt)andl1_loss = torch.nn.L1Loss()
for idx in range(B):
if idx==0:
loss = l1_loss(pred[idx,:,:,:],gt[idx,:,:,:])
else:
loss = l1_loss(pred[idx,:,:,:],gt[idx,:,:,:]) + loss
... | ptrblck | Yes, this seems to be the case for random input values:
pred = torch.randn(10, 10, 10, 10)
gt = torch.randn(10, 10, 10, 10)
l1_loss = torch.nn.L1Loss()
loss1 = l1_loss(pred,gt)
for idx in range(pred.size(0)):
if idx==0:
loss2 = l1_loss(pred[idx,:,:,:],gt[idx,:,:,:])
else:
loss2 = l1_… |
callahman | I have a custom Dataset I’m trying to build out. The actual details of my Dataset are below, but for now I’m going to focus on the following example code.The goal is to load some data into __getitem__() and segment the array into several samples which I can then stack and output with the batch.from torch.utils.data imp... | ptrblck | Assuming the returned tensor contains the desired values, you could flatten it in the DataLoader loop via:
for batch in dls:
sample = batch['sample']
sample = sample.view(-1, 5)
print(sample.shape) # should print [4, 5] now
Using a custom collate_fn would probably also work, but I thi… |
Mona_Jalal | Please also check here:After I install the repo using:$ pip install .and run my code, I get the following error:Running setup.py install for torch-encoding ... done
Successfully installed Pillow-8.1.0 certifi-2020.12.5 chardet-4.0.0 idna-2.10 nose-1.3.7 portalocker-2.2.0 requests-2.25.1 scipy-1.6.0 torch-encoding-1.2.2... | ptrblck | The error is raised by import encoding, which seems to be a custom script in your repository, so you would have to make sure it’s able to import all modules in its __init__.py. |
Praveen_K | Here I’m trying to view my images after performing someDataLoaderoperation.class Classification(Dataset):
def __init__(self, df, length, transform=None):
self.df = df
self.data_len = len(self.df)
self.len = length
self.transform = transform
def __getitem__(self, index)... | ptrblck | Instead of squeeze, which tries to remove a dimension with size=1, you could index the images in the batch in a loop:
for batch_idx, (inputs, labels) in enumerate(train_loader):
print(inputs.shape) #torch.Size([2, 3, 224, 224])
for idx in range(inputs.size(0)):
input = inputs… |
ashwani-bhat | I know model.train() is called at the start of every epoch. But can I call model.train() after every batch. My code is working when I called it after every batch. I just wanted to know if there are any downsides to it.Something like this:for every epoch:
for every batch:
model.train()
# some line... | ptrblck | You could call it after each batch, but this would not be necessary, if you haven’t called model.eval() between these calls.
Note that model.train() changes the internal training flag, which then changes the behavior of some modules (e.g. dropout will be disabled during evaluation). |
hrushi | I have a custom layer. Let the layer be called ‘Gaussian’class Gaussian(nn.Module):
def __init__():
super(Gaussian, self).__init__()
#@torch.no_grad
def forward(self, x):
x = x + torch.rand(x.shape)
x[2:] = x[2:] + x[1] # Some similar operations are also performed
return x
cnn_model = ... | ptrblck | Both approaches would break the computation graph and the previous layers wouldn’t get a valid gradient.
You could try to adaptthis workflow(or write a custom autograd.Function and define the backward method manually). |
Shantanu_Nath | I don’t know what is actual error. Why is it showin:Capture1468×362 39.5 KBHere is My Script:def train_one_epoch(epoch, model, optimizer,loss, train_loader, device, train_data):
print('Training')
model.train()
train_running_loss = 0.0
train_running_correct = 0
for i, data in tqdm(enumerate(train_loa... | ptrblck | This line of code is creating the issue:
loss = loss(outputs, target)
since loss is passed as an argument to train_one_epoch.
Change the loss function object name to criterion in train_one_epoch and it should work. |
MasLiang | When I wrote:torch.round(torch.tensor(0.5))I think it will be ‘1’. But I got ‘0’.And when I wrote this:torch.round(torch.tensor(1.5)I got the correct value ‘2’.What happened to ‘0.5’? | ptrblck | I think the torch.round operation sticks to numpy’s implementation, which explains:
For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. Thus 1.5 and 2.5 round to 2.0, -0.5 and 0.5 round to 0.0, etc. Results may also be surprising due to the inexact re… |
gabrieldernbach | I am using a ResNet50 as feature extractor and I would like it to run it with cudnn.benchmark=True, as I know the input shape does not change. As the number of created embeddings can differ, the following classifier will have a variable-length input, so I would prefer to set cudnn.benchmark=False for it.The documentati... | ptrblck | You can use the context manager to enable/disable benchmark for a region:
with torch.backends.cudnn.flags(enabled, benchmark, deterministic, allow_tf32):
some_layer |
Hasan_Sait_ARSLAN1 | Hi,I have a very large dataset to train my model. I would like to get n different random batches from the DataLoader at every different epoch. How can I do it?Thanks, | ptrblck | You could create an iterator via loader_iter = iter(loader) and get the next batch via batch = next(iter). If you’ve set shuffle=True in the DataLoader, these batches will contain random samples. |
AlphaBetaGamma96 | Hi All,I’ve been starting to run my code on a GPU and started to change the default dtype viatorch.set_default_type(torch.half). However, because my model uses atorch.slogdetfunction within it. It doesn’t seem to work, I assume becausetorch.halfisn’t supported bytorch.slogdet? (Or is to do with LU decomposition that mi... | ptrblck | Linear algebra methods are usually unstable in reduced precision, so you should use float32 for these kind of operations.
I don’t think float16 support will be added to lu_cuda for the aforementioned stability reasons. |
Gerrit | I am aware that some others got a similar RuntimeError message, but unfortunately I was not able to fix it yet. Maybe someone else has a hint ?I want to feed an input feature vector containing 16 features to the network, pass it through some hidden layers (just one for now) and finally get an output in one hot vector f... | ptrblck | In your current forward implementation you are passing x to F.softmax so that the actual model will not be used.
Also, nn.CrossEntropyLoss expects raw logits, as internally F.log_softmax will be applied, so remove the F.softmax and return out directly.
If you are still facing a shape mismatch erro… |
LostAtlas | Last week i implemented a Resnet Block for my SRGAN code and i was doubtful about one aspect of the implementation.When you pass the input through the residual skip connection, do you detach that from the computation graph ( Like var.detach() in Pytorch) or do you let it persist in the graph?If so, does this mean the d... | ptrblck | I’m not familiar with the usage in SRGAN, but in ResNets the identity used in the skip connections is not detached from the computation graph as seen e.g.here. |
hanbit | Hi, I have an a100 machine and the configuration for MIG is following.GPU 0: A100-SXM4-40GB (UUID: GPU-b428bd3e-1cd2-38b1-833a-bae2ac1edf60)
MIG 7g.40gb Device 0: (UUID: MIG-GPU-b428bd3e-1cd2-38b1-833a-bae2ac1edf60/0/0)
GPU 1: A100-SXM4-40GB (UUID: GPU-67129a8b-fff4-5944-eada-c4f04ef3871b)
MIG 7g.40gb Device 0: (UU... | ptrblck | This is expected behavior, as MIG doesn’t support multiple compute instances subscription for processes.
If no GPUs are in MIG mode, all devices should be visible. Otherwise, if one of the devices is in MIG mode, the GPUs in non-MIG are invisible. |
thejas_karkera | TCGA-2Z-A9J9-01A-01-TS11000×1000 43.2 KB | ptrblck | This codeshows an example of the transformation from colors to class indices. |
zeyuyun1 | I am looking for the implementation fortorch.nn.functional.layer_norm, it links me to thisdoc, which then link me tothis oneBut I can’t find where istorch.layer_norm.According to the documentation, it seems like the math is following:x = torch.randn(50,20,100)
mean = x.sum(axis = 0)/(x.shape[0])
std = (((x - mean)**2).... | ptrblck | You can find the (CPU) C++ implementationhere. |
Tamme_Wollweber | I am not able to run the following lines:import torch, torchvisionmodel = torchvision.models.resnet18(pretrained=True)The error is the following:Traceback (most recent call last):
File "/home/tamme/anaconda3/envs/deep/lib/python3.8/site-packages/IPython/terminal/ptutils.py", line 113, in get_completions
yield fro... | ptrblck | It seems the be related to this issue:
Try to downgrade jedi to 0.17.2 via:
pip install jedi==0.17.2 |
J_Johnson | Hello!If I want to add more neurons to a layer inside of a model during training, do I only need to update themodel.parameters()for each layer(weights and biases) after backpropagation, or is there more to it than that? If so, what would I need to do in addition to resizing the parameter tensors? | ptrblck | Since you are changing the parameters, you would need to pass these new parameters to the optimizer (or create a new one). The running stats in this optimizer would be lost in this case (if it’s using internal estimates). |
Hagar-Usama | Hello,I am trying to add more layers to inception v3 to fit my dataset. Yet, I don’t figure out the Runtime Error. my input is (3* 256 * 256)model = models.inception_v3(init_weights=True, pretrained=False)
fc_feat = model.fc.in_features
model.fc = nn.Sequential(
nn.Linear(fc_feat, 512),
nn.ReLU(),
nn.Line... | ptrblck | The original Inception model expects an input in the shape [batch_size, 3, 299, 299], so a spatial size of 256x256 might be too small for the architecture and an empty activation would be created, which raises the issue. |
Samuel_Bachorik | Hello iam trying to train my model with my NVIDIA GTX 770. I am getting this error and i cant find way to make this work. It says my GPU is old. It is possible to make this GPU work with PyTorch ?thank youFound GPU0 GeForce GTX 770 which is of cuda capability 3.0.
PyTorch no longer supports this GPU because it is t... | ptrblck | You won’t be able to use PyTorch in its current version with this GPU architecture, as the min. compute capability is 3.5.
I would recommend to use e.g. Colab with the free GPU runtimes. |
Kroshtan | Relatively simple question, I believe: Due to the structure of my model, I cannot use inplace operations, but I would like to use the fill_ function from torch.Tensor. Is there an out of place variant or similar functionality available? For now I replaced some calls to fill_ with x.fill_(0) with x = torch.zeros(x.size)... | ptrblck | You could use torch.full_like instead of the inplace fill_ operation. |
Toshi | Hi, I’ve been trying to implement masking on gradients over some custom layer weights in my network, and I implement it in the following way (before start of each epoch/training step).cur_hooks = {}
for n,p in net.named_children():
if isinstance(p, Conv2d) or isinstance(p, Linear):
gradient_mask = (... | ptrblck | Thanks for the code snippet.
The approach using a dict might work, alternatively, you could also use:
h = module.weight.register_hook(lambda grad, gradient_mask=gradient_mask: grad.mul_(gradient_mask))
Your current code runs into a known Python limitation of using lambda functions, since names in… |
VirginieBfd | Hi, can someone ping me to an example of partial transfer learning with EfficientNet? For instance, unfreezing the last two blocks of the network?Thanks in advance! | ptrblck | You can freeze all parameters of the model first via:
for param in model.parameters():
param.requires_grad_(False)
and later unfreeze the desired blocks by printing the model (via print(model)) and use the corresponding module names to unfreeze their parameters. E.g. assuming the last two “blo… |
a_bear_paw | Hi,I need to unload model which loaded by torch::jit::load() with C++. But I couldn’t find anything about it just like ‘torch::jit::unload()’.In my C++ code, there are two functions and provided api using pybind11:#include <iostream>
#include <vector>
#include <string>
#include <torch/torch.h>
#include <torch/script.h... | ptrblck | Yes, you can delete the model by running del model in the Python script without shutting it down. |
blackberry | PyTorch’sdata loader uses multiprocessing in Pythonand each process gets a replica of the dataset. When the dataset is huge, this data replication leads to memory issues.Normally, multiple processes should use shared memory to share data (unlike threads). I wonder if there is an easy way to share the common data across... | ptrblck | If you are lazily loading the data (which is the common use case, if you are dealing with large datasets), the memory overhead from the copies might be small in comparison to the overall memory usage in the script.
That being said, you could try to use shared arrays as describedhereinstead. |
jahan123 | If I modify thestem()for torchvision models, will I be able to use the pretrained wieghts?I am changing the input layer channels:class modifybasicstem(nn.Sequential):
"""The default conv-batchnorm-relu stem
"""
def __init__(self):
super(modifybasicstem, self).__init__(
nn.Conv3d(1, 64, k... | ptrblck | Yes, your code would replace the .stem module only while all other layers would still use their pretrained parameters. |
finewith_me | I want W to get updated, and as you can see, “x” variable acts as an index variable, which helps in getting relevant weights from W and then combine them to get predictions. But the way I have done it does not seem to update “W”. Also note that if I make requries_grad=False where it is True now in the following code, I... | ptrblck | You would have to initialize W as an nn.Parameter or set it requires_grad attribute to True in the creation.
Also don’t wrap outputs in new tensors, as this will detach the computation graph.
This code snippet should work:
x=[torch.tensor([0,1]),torch.tensor([[2,3],[0,1]]),torch.tensor([4,5])]
W=… |
skerlet_flandorle | I’m making my own dataset for rnnI don’t know where the internal state (time) of GRU startsThe size is 1 batch = 100,256In pytorch’s GRU, which do you start from right (deta [batch] [0]) or left (deta [batch] [100])? | ptrblck | RNNs expect an input in the shape [seq_len, batch_size, features] in the default setup.
The temporal dimension is thus in dim0 and the first time step would be at index 0. |
MasLiang | I use softmax and then I use log to mimic cross entropy when I try to implement knowledge distillation.soft_old_output = soft_target.clone()/T
soft_new_output = outputs.clone()/T
soft_new_output.retain_grad()
outputs_S = F.softmax(soft_new_output,dim=1)
outputs_S.retain_grad()
outputs_T = F.softmax(soft_old_output,dim=... | ptrblck | The small absolute error is most likely created by the limited numerical precision using flaot32 and you should get a smaller error using float64.
Also note, that using torch.log(torch.softmax(...)) is numerically less stable than F.log_softmax, as the latter applies the log-sum-exp trick to increa… |
Celmar | The last layer of my model isself.linear = nn.Linear(4096, 2). Usually to find out which classdatabelongs to I writeoutput = model(data) #which return a tensor of size 2
pred = output.data.max(1, keepdim=True)[1]Only I want the probability thatdatabelongs to the first or second class, so I thought I would write :output... | ptrblck | nn.Softmax is an nn.Module so you would either have to create the module first and call it with output or use F.softmax instead:
pred = torch.nn.Softmax(dim=1)(output)
# or
pred = F.softmax(output, dim=1) |
Wanderer3 | I am trying to use a pre-trained VGG16 model to classify CIFAR10 on pyTorch. The model was originally trained on ImageNet.Here is how I imported and modified the model:from torchvision import models
model = models.vgg16(pretrained=True).cuda()
model.classifier[6].out_features = 10and this is the summary of the modelpr... | ptrblck | Changing the out_features attribute of the linear layer will not recreate the parameters, so you would need to assign a new layer instead:
model = models.vgg16(pretrained=True)
in_features = model.classifier[6].in_features
model.classifier[6] = nn.Linear(in_features, out_features) |
Geoffrey_Payne | I see this line of codelab=lab.view(-1)I am wondering what this code does? I put a breakpoint on it, and as far as I can see the contents of lab are the same both before and after I execute the code. So does this code make any difference? | ptrblck | The view(-1) operation flattens the tensor, if it wasn’t already flattened as seen here:
x = torch.randn(2, 3, 4)
print(x.shape)
> torch.Size([2, 3, 4])
x = x.view(-1)
print(x.shape)
> torch.Size([24])
It’ll modify the tensor metadata and will not create a copy of it. |
acoder_acoder | Hello!I find a really tricky situation for thedropoutfunction in the pretrained GoogLeNet. The output results between directly executing the whole model and executing the model layer by layer are different. It seems that when executing the model layer by layer, thedropoutfunction does not work while it works if executi... | ptrblck | Since this attribute is set to True in your example, the input will be transformed.
Using it also yields the same results:
x = torch.randn(10, 3, 224, 224)
glnet = models.googlenet(pretrained=True)
glnet.eval()
res = glnet(x)
out = x
if glnet.transform_input:
out = glnet._transform_input(out… |
Celmar | Hello,I modified Pix2Pix in order to have a loss style instead of an L1 loss (for theoretical reasons). When I test my loss style between two images of my training set, no problem, it works well but in my network I get the errorRuntimeError: Given groups=1, weight of size [64, 3, 3, 3, 3], expected input [1, 2, 256, 25... | ptrblck | Based on the weight shape I guess the error is raised by an nn.Conv3d layer. Could you check where such a layer is used in this config and make sure the input to it has 3 valid channels? |
iamneerav | My loss function has weird spikes in it that keep on decreasing. I do not understand what inference should I make from this.This is the plot (zoomed in on y-axis)new9000×3500 1.01 MBand the follwing is the original loss plotnew19000×3500 499 KBI am using a U-Net architecture to train data of the shape (batch_size, 3, 3... | ptrblck | You could try to capture the iteration loss spikes and manually check, which samples were included in the current batch, which might yield more information. E.g. it could be “bad” or “hard” samples, which create a high loss as well as non-optimal gradients so that the following iterations are used t… |
Deeply | I need to change the weights at specific layers of ResNet-152 during training.I think there has been a similar question sometime earlier, but I cannot find it! | ptrblck | Would you like to change the weights manually?
If so, you could wrap the code in a torch.no_grad() guard:
with torch.no_grad():
model.fc.weight[0, 0] = 1.
to prevent Autograd from tracking these changes. |
hanhaowen | If the input tensot of torch.nn.functional.binary_cross_entropy is zero , and the target tensor is 1.0, the output will be 100.Here is my code:input=torch.tensor(0.0)target=torch.tensor(1.0)loss=F.binary_cross_entropy(input,target)print(loss)#tensor(100.)so I want to know how does the function proceed when the input is... | ptrblck | Based on the description, the theoretical output in the range [-Inf, +Inf] is clipped to [-100, +Inf], if I’m not misunderstanding it. Thus the actual value depends on the calculated loss, but is clipped at -100 in its minimum. |
manurare | Hi,I have a loss function that looks like this:disp_diff = (torch.max(eval_target[:, -1:, ...], eval_source[:, -1:, ...]) /
torch.min(eval_target[:, -1:, ...], eval_source[:, -1:, ...])) - 1
disp_diff[disp_diff != disp_diff] = 0
loss = torch.sum(disp_diff, dim=[2, 3])The max/min operation can be (0/0) = NaN. That’s ... | ptrblck | I think you would have to avoid running into these invalid values, as manipulating the output afterwards would still run into the invalid operation in the backward pass, if I’m not mistaken.
Here is a small code example:
x = torch.randn(10, requires_grad=True)
d = torch.randn(10)
d[0] = 0.
out = … |
Saurav_Gupta1 | I am trying to train a model on multiple GPUs. I have 2 Tesla k40c and 1 GeForce GTX 1080. My PyTorch version is 1.7.1 with CUDA 11.2.PyTorch 1.3.1 onwards has stopped support for GPUs with compute capability of 3.5, which means I am unable to use Tesla k40c. Is there any way I can use Tesla k40c with CUDA 11.2 and PyT... | ptrblck | You can specify multiple GPU architectures by building with:
TORCH_CUDA_ARCH_LIST="3.5 6.1" python setup.py install
where you can pass multiple architectures to the env var (as well as +PTX). |
algol | I am trying to train several networks on similar datasets, and there are several constraints on the outputs that are common, even if the actual network outputs will be different. However, I don’t necessarily know the details of the relationship beforehand, and I want to give the parameters associated with the constrain... | ptrblck | This approach would pass the same param_mat to all optimizers, which would update it with its gradient and I assume that’s the use case you are looking for. |
vadimkantorov | Often modules have structure like this (so thatstate_dict()key names are readable):class MyModule(nn.Module):
def __init__(self):
super().__init__()
self.module1 = nn.Linear(1, 4)
self.act1 = nn.ReLU()
self.module1 = nn.Linear(4, 8)
self.act2 = nn.ReLU()
def forward(self, x):
x = self.modul... | ptrblck | Would it work to pass the OrderedDict directly to nn.Sequential as described in thedocs?
# Example of using Sequential with OrderedDict
model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(1,20,5)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20,64,5)),
('r… |
robz | I would like to add a tensor to a model so thatmodel.to(device)also moves the tensor to the device.register_bufferseems to do this; however, I don’t want the tensor to be inside the model’sstate_dict. Is there a method to do this?My specific application is that I have a model that uses a transformer encoder. For conven... | ptrblck | You could use self.register_buffer and set the persistent argument to False.
From thedocs:
persistent (bool) – whether the buffer is part of this module’sstate_dict. |
AOZMH | There are a fewdiscussionson the difference between Adam(weight_decay=0.01) and AdamW() which point out that the implementation of weight decay in AdamW is the decoupled weight decay, different from the raw regularization of Adam.However, I consulted the officialdocumentationof Adam & AdamW and noticed that the impleme... | ptrblck | This issue should be solved inthis PR. |
Altiki | Hello everybody,I am trying to rewrite a simulation code written with Tensorflow using Pytorch.I am new to Pytorch and I am still learning to work with tensors in general.I am stuck at rewriting tf.while_loop(), which, as I managed to understand, is a special function in Tensorflow:t_out,v_out,s_out,m_out,d_out,f_s_out... | ptrblck | You can use the Python while loop in PyTorch directly.
PyTorch doesn’t use sessions and will be eagerly executed. I.e. if you run a PyTorch operation (in the default mode), the result is directly available (similar to e.g. numpy). |
thnguyen996 | I tried to add gaussian noise to the parameters using the code below but the network won’t converge. Any though why? I used cifar10 dataset with lr=0.001import torch.nn as nn ... | ptrblck | Injecting noise into the model might act as a regularizer, but note that your current noise is static and you would most likely want to resample it in each forward pass. I don’t know how large the stddev should be to work properly. |
ambareeshravi | Is it possible to implement One Class SVM as a part of a Neural Network in PyTorch?I am doing an experiment for my research on outlier detection and I need to implement One Class SVM as a layer and its objective function as apart of the main objective / loss function. I know I could use ScikitLearn and LibSVM for the s... | ptrblck | You could try to use e.g.nn.MultiLabelMarginLoss, which is the multi-classification hinge loss and create the desired targets for your “One Class SVM”. |
Hypernova | Model shows different predictions after training without weight updateDear Community,
i encountered some none-intuitive behaviour. I load a model, set it to evaluation mode and predict a single image using model(input). Then, I set the model to training mode and predict a single image again. (Note that there is no .ba... | ptrblck | Theanswerfrom the linked post explains, that the running statistics in batchnorm layers will be updated during training and used during evaluation (model.eval()).
If you want to keep these stats constant, use model.eval() and don’t perform any forward passes while the model is in training mode. |
Levon | Hi,Please help me solve the following confusion:I have 4 filters of (4,4) size. The values of these filters I want to assign to my conv2d weights and then visualize them.Below I define my model for greyscale image. When I run the code - it works correctly.But when I change the out_channels from 4 to 5 or 2, I expect th... | ptrblck | Thanks for the follow-up. I assume you think it should be disallowed to pass a new weight kernel with a different number of filters, since the original layer was initialized with another number of kernels?
If so, then note that it’s not disallowed to manipulate the underlying parameters (at your ow… |
Pyroka | Hi,so i have an unbalanced dataset of 2 classes. I searched for solutions and came across theWeightedRandomSamplerwhich many people seem to use.However i do not fully understand what it is used for: As far as i understand the WeightedRandomSampler makes sure (if correctly used), that in each Batch there is approximatly... | ptrblck | That’s one use case, but I wouldn’t say that it’s the only correct one. As the name suggests this sampler is used for weighting the sampling strategy, not only balancing it.
Yes, your description is correct. If you want to have balanced batches, you should not use replacement=False.
Yes, that m… |
Rohi | I imported Cifar10 dataset from torchvision.datasets, I was expecting the pixel values should be between [0-255], but I can see values as decimal. I belive I havent done any normalization.Is it the correct data which I am seeing, or some transformations are happening on it?below is the code,image952×830 44.8 KB | ptrblck | If you are working on a multi-class classification, which I assume since you are using the CIFAR10 dataset, then the target is expected in the shape [batch_size] containing the class indices in the range [0, nb_classes-1], so it’s not one-hour encoded.
The torchvision.datasets` CIFAR10 dataset will… |
JisongXie | Originally, I want to optimize my code, figure out which operation is time consuming, to make my code run more fast.This is my original code. It’s just some feature extracted to be inferred by model, and then compute some distances of the embeddings. It works with GPU.image1277×780 77.5 KBI add time called almost each ... | ptrblck | CUDA operations are executed asynchronously, so you would need to synchronize the code before starting and stopping the code manually via torch.cuda.synchronize() or use a built-in utility such as torch.utils.benchmark from the nightly/master, which will add it for you (as well as warmup iterations)… |
over9k | Hi,I am currently keeping track of training and validation loss per epoch, which is pretty standard. However, what is the best way of going about keeping track of training and validation loss per batch/iteration?For training loss, I could just keep a list of the loss after each training loop. But, validation loss is ca... | ptrblck | That’s right and is the reason, why the validation loss and metric is usually calculated once per epoch.
The idea of calculating the validation loss is to get a signal of the model’s performance on “unseen” data. In the best case the validation loss should closely stick to the final test loss (not… |
CBMadsen | I have now been stuck on this problem for 2 days and it seems to be a almost un-googlable problem. I know that pytorch does not support 2.7 since version 1.4 and I know that 2.7 has been deprecated, but I am trying to replicate the code from this repository:GitHub - XiSHEN0220/ArtMiner: (CVPR 2019) Pytorch implementati... | ptrblck | As you’ve already mentioned, the current PyTorch binaries are not built anymore for Python2.7.
I would guess the right approach would be to update the repository to use Python>=3.6.
Alternatively, you could try to build PyTorch from source using Python2.7 (with potentially some needed fixes) at yo… |
localh | I am trying to generate three separate torch data sets from the torch Dataset class but I am not sure how to do it or if it is possible, owing to__getitem__'s functionality. I would like to have separate torch data sets that I can then pass into data loaders on their own. Can I return 3 separate torch data sets from th... | ptrblck | Usually you could create a separate Dataset instance for the training, validation, and test splits.
Based on your code snippet you could pass an argument to the __init__ method and use it to create the corresponding split (e.g. by passing train, dev, or test). |
Celmar | Hello,would you know how I can adapt this code so that sizes of tensors must match because I have this error:x = torch.cat([x1,x2],1) RuntimeError: Sizes of tensors must match except in dimension 0. Got 32 and 1 (The offending index is 0).My images are size 416x416.Thank you in advance for your help,num_classes = 20
cl... | ptrblck | I cannot reproduce this issue by using an input tensor of [batch_size, 3, 416, 416] and am running into a shape mismatch error before.
Changing x.view(-1, 2048) to x.view(x.size(0), -1) and adapting the expected in_features in self.linear works:
num_classes = 20
class Net(nn.Module):
def __ini… |
oasjd7 | If the accuracy for each class of my model is [0.7, 0.8, 0.2], can I improve the performance of the last class by applying the weight as [1,1,2] in cross-entropy ?When I applied the weight as [1,1,2], I thought the loss would be different from that of ces1. But it gives the same value. Why is that?ces1 = nn.CrossEntrop... | ptrblck | The weighting should balance the losses and might thus also balance the accuracy. I.e. while the class2 accuracy might increase the other two might decrease.
Your current target might not use the class2 index. This code shows the difference:
class_weights = torch.tensor([1., 1., 2.])
ces1 = … |
sh0416 | Hi,Is the “register_forward_hook” exist for tensor type?I couldn’t find it.Thanks, | ptrblck | As@albanDexplained, you cannot register a hook on a tensor, as it’s already available.
Based on your previous code snippet I guess you could use an nn.Identity layer, pass x to it after the exp operation and register a hook on this “fake” layer. I don’t think it would be cleaner than storing the … |
aatiibutt | I am training CNNs through transfer learning, following pytorch transfer learning tutorial. As shown below, after completion of training, type error occurs.I shall be grateful, If anybody help me out. | ptrblck | The error is raised, since train_model doesn’t return anything, so you might want to add a return statement. This code snippet raises the same error:
def fun():
print("don't return anything")
fun() # works
a, b = fun() # fails
> TypeError: cannot unpack non-iterable NoneType object |
Hacking_Pirate | Hi,I am trying to make an image classification model. To open the image I am usingImage.open(img_path).But I am getting this error:stack expects each tensor to be equal size, but got [200, 200, 3] at entry 0 and [200, 200] at entry 10.But when I use CV2 to open the image it works fine, like this:img = cv2.imread(img_pa... | ptrblck | PIL would check the image format, in particular the number of channels, and will return 3 channels for RGB images and will remove the channel dimension for grayscale images, which is the case for the image in the shape [200, 200].
You could use Image.open(path).convert('RGB') to transform the grays… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.