user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Josh_Lazor | Hello all,I have a working Pytorch ConvNet program. It tests Datasets and runs rather slow, but effectively.Would anyone know how to test images separately? I want to test 1 image instead of n number of images.Thank you | ptrblck | You can load and process a single image, e.g. via PIL.Image.open and torchvision.transforms.
Once you have created the image tensor for this single input image, you can add a batch dimension via x = x.unsqueeze(0) and pass it to the model.
Let me know, if this works for you. |
TAF | I tried this but it does not work | ptrblck | You might not have deleted all references to all parameters and tensors, so these objects might still hold the memory.
Also, another application might of course use the GPU memory (but I assume you are sure that PyTorch uses it). |
NIkolaStaykov | Which modules are affected by the modes except BatchNorm and Dropout? I was wondering in which cases the two modes are interchangeable. | ptrblck | The train() and eval() call change the internal self.training flag, so you could grep for it in the source folder (grep -r self.training).
Currently it seems these modules are affected by it in the PyTorch core:
Quantization modules
Dropout
InstanceNorm
BatchNorm
RNN (probably only if using cudnn… |
algeriapy | When I tried to extract deep features using trained inception_v3 modelmodel = torchvision.models.inception_v3(pretrained=True)model.fc = nn.Linear(2048, 1)model.load_state_dict(torch.load(’./models/Beauty_inception_reg.pt’))feature_extractor = torch.nn.Sequential(*list(model.children())[:-1])I got the following error :... | ptrblck | Wrapping child modules into an nn.Sequential container will only work in simple use cases, where each module is called sequentially and no functional calls are used in the forward method.
As you can seehere, the Inception model uses some functional pooling layers, conditions, dropout, and a flatte… |
syomantak | I want to do a conv1D operation but on an image. Let’s say the data is of size(1,1,H,W). Treat this as a data of size(1,1,H)W times, and doConv1D(1,1,k)on each and stacking the outputs back. Basically, it is equivalent to doing a Conv2D with kernel size =(k,W), however, with each column of the kernel equal. It is like ... | ptrblck | Wouldn’t your approach be equivalent to use a nn.Conv2d with a kernel size of (k, 1)?
This would also only use the height of the kernel and apply it basically to each “column”.
Let me know, if I misunderstood your use case. |
BlueTurtle | I have had a lots of problems with this notebook but hopefully this is the last one:I now have:All my inputs as tensorsBoth the data and model (including fc) on the GPUResized all the images to the same sizeChanged requires_grad = Truefor the fcMy model will only do one forward pass though before sitting idle. I think ... | ptrblck | Try to add a print statement in the validation loss or profile each step.
The Kaggle notebook look approx. 1 second per validation step, so depending on the size of the validation dataset, this might take some time. |
aarrvv | I am learning pytorch and coded a minimal classifier to play with:import torch
import numpy as np
import matplotlib.pyplot as plt
numclasses, count = 8, 200
x = torch.randn(count, 4)
y = torch.randint(0, numclasses, size=[count])
dataset = torch.utils.data.TensorDataset(x, y)
dataloader = torch.utils.data.DataLoader(... | ptrblck | The larger the batch size, the less noise the parameter updates will include.
Often this noise is beneficial to reach a better final accuracy, but it might depend on your use case.
You could find some articles, which compare gradient descent, batch gradient descent, and stochastic gradient descent… |
sgaur | HiI am trying to take weighted average of weights for last 5 epochs but all of the wights (where require_grad = True) are same.> class resnet34(nn.Module):
> def __init__(self):
> super(resnet34,self).__init__()
> self.arch = models.resnet34(pretrained=True)
> self.arch.fc = nn.Linear(self.a... | ptrblck | After you’ve stored the state_dicts you could iterate the keys of them and create a new state_dict using the mean (or any other reduction) for all parameters.
This code snippet shows a small example:
# Setup
state_dicts = []
model = models.resnet18()
optimizer = torch.optim.SGD(model.parameters(),… |
ericrhenry | Valgrind is my go-to for wrangling possible memory leaks. It is a beautiful piece of software, but is unfortunately (and necessarily) imperfect. I just ran a libtorch-based application through a relatively brief optimization of a CNN model, and it generated a fair number of loss records. Fortunately, all of them appear... | ptrblck | Thanks for the analysis and I think that (same as with your last check) it would be worth creating an issue on GitHub to track it. |
mayool | Hey everyone,i am currently working with the torchvision.models.segmentation.deeplabv3_resnet50() model.It consists of:a backbone (Resnet)a classifier (DeeplabHead)interpolation (biliniar to make sure output_size = input_size)what really confuesed me was the interpolation part.For testing I inserted an image of size 27... | ptrblck | Thepaperexplains the interpolation strategy as well as the usage of transposed convolutions in a couple of sections.
This section might be interesting:
We have adopted instead a hybrid approach that strikes a good efficiency/accuracy trade-off, using atrous convolution to increase by a factor o… |
DJ_1992 | Hi,I am trying to use WeightedRandomSampler in this wayclass_sample_count = [39736,949, 7807]weights = 1 / torch.Tensor(class_sample_count)weights = weights.double()sampler = torch.utils.data.sampler.WeightedRandomSampler(weights=weights,num_samples=?,replacement=False)dataloaders = {x: torch.utils.data.DataLoader(imag... | ptrblck | The weights tensor should contain a weight for each sample, not the class weights.
Have a look atthis postfor an example. |
chaslie | Hi,If i have a one hot vector of shape [25,6] and a data input of [25,1,260,132] how do i concatanate into a single tensor to feed in to the encoder of a convolutional VAE?like wise the lat_dim tensor is [25,100] how to concatanate to feed into the decoder of the convolutional VAE?Chaslie | ptrblck | Sorry for not being clear enough.
You could pass both tensors to the forward method and concatenate the activations as seen in this dummy code:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv = nn.Conv2d(1, 1, 3, 1, 1)
self.lin = … |
Yashas | The initialization is layer-dependent. How does pytorch seed the RNGs by default?If I have to train a model N times to see the average performance of the model, do I have to have special code to ensure that the initializations are different? Can I assume that I have different initialization on each training run? | ptrblck | I don’t think PyTorch seeds the code by default, as this would mean you could get deterministic result for each run, which is not the case.
You can execute this core repeatedly in your terminal and will get different values:
python -c "import torch; print(torch.randn(10))" |
GB_K | Hello PyTorchers.I used the word PyTorcher meaning the person uses Pytorch.I am not sure this expression is appropriate, so comment to me about this, please XDFor my task (face detection), I am using two deep learning framework, Pytorch and MXNet.Please look at the diagram below to help your understanding.image956×299 ... | ptrblck | Thanks for the information.
In that case you are adding synchronizations, as numpy uses CPU arrays. Your workflow would therefore probably be:
load data on CPU -> transfer to GPU and use MXNet model -> transfer back to CPU -> transform to PyTorch tensor and transfer back to GPU -> use forward pas… |
s_n | Hi,I have a class for my model that uses some other model in it. For example:class Mynet1(nn.Module):definit(self):super(NN_model, self).init()self.fc1 = nn.Linear(4160, 500)class Mynet2(nn.Module):definit(self, Mynet):super(NN_model, self).init()self.fc1 = nn.Linear(4160, 500)self.layer = Mynet(…)mynet1=Mynet1()model ... | ptrblck | nn.DataParallel will split the input tensor in dim0 and will send each chunk to the corresponding model replica on a specific device.
I.e. your model’s forward will get an input of the shape [batch_size//nb_gpus, *].
If you need to create y1 and y2 inside the forward method, you should also consi… |
LeErnst | Hello together,i have a ReLU-NN class as follows20 class ReLU_NN(tr.nn.Module):
21 '''
22 Class for a ReLU-NN with variable size.
23 Inpu... | ptrblck | You have a recursion in your code, as you are overriding PyTorch’s load_state_dict method and are calling it inside via:
model.load_state_dict(tr.load(PATH))
which will call the method again with the state_dict instead of the PATH.
Rename your method to my_load_state_dict or any other name and it… |
Ahmed_Abdelaziz | Hi all,I am trying to convert this tensorflow code into pytorch. For example, I converted the below tensorflow codetf.get_variable("char_embeddings", [len(data.char_dict), data.char_embedding_size]), char_index) # [num_sentences, max_sentence_length, max_word_length, emb]intoclass CharEmbeddings(nn.Module):
def _... | ptrblck | Probably yes, but you should compare the default arguments to both methods, as each framework might use other defaults.
self.embeddings is not created as an nn.Parameter, so Autograd won’t calculate the gradients for this tensor. You could use:
emb = torch.empty(len(...))
nn.init.xqavier_uni… |
Vatsal_Malaviya | I have not changed any gradient explicitly to false in grad_fn of tensors.Refer Link for all the code fileCode Linkmain.py as follows:import torch
from DataLoader import *
from model import *
from torchvision import transforms
from torch.utils.data import DataLoaderPreformatted text
import os
#HYPER-PARAMETERS
batchs... | ptrblck | The output of torch.argmax doesn’t have a backward function, so you are breaking the computation graph in:
output = torch.argmax(output,dim=1)
Try to pass the model output directly to the criterion instead. |
Cirets0h | Due to certain data I want my network to only learn on losses that are lower than 1. For that I use the following code:def train(img, label):
x = self.net(img)
loss_val = self.loss(x, label)
self.optimizer.zero_grad()
if loss_val < 1:
loss_val.backward()
self.optimizer.step()Is t... | ptrblck | Each forward pass will create a new computation graph.
To double check your use case, you can print the gradients via:
for name, param in net.named_parameters():
print(name, param.grad)
You can print it at different places to see, if the gradients are valid or have been zeroed out. |
phiwei | Hi,I have noticed that my dataloader gets slower if I add more workers compared to num_workers=0.My dataset definition is quite simple:class Dataset(torch.utils.data.Dataset):
def __init__(self, file_paths, labels, transform=None):
self.file_paths = file_paths
self.labels = labels
self.tran... | ptrblck | If you are using multiple workers, the Dataset will be copied, if I’m not mistaken.
The first iteration would include these copies as well as the first batch creation in each process, which might be slow.
However, the following iterations should be faster.
Are you consistently seeing a slowdown u… |
Haimin_Hunter_Zhang | I have read the documentation of torch.nn.AdaptiveAvgPool2d, and I understand how to use this function now. But I don’t get how this function works. Can help be provided to explain the algorithm of AdaptiveAvgPool2d?Much appreciated. | ptrblck | @tomexplains it beautifully inthis post. |
Qu_Yukun | I try to train a two-stram network. I have two models, and I hope I can use the sum output of the two models to update the two models.Now I have two models, get their loss respectively: they are loss1 and loss2.And then I add the two loss values: loss = loss1 + loss2.The question is that:loss.backward() will update wic... | ptrblck | The loss.backward() call will let Autograd calculate the gradients for both models, as the final loss is a sum of both partial losses.
You can also verify it by printing the gradients of some parameters of these models after the backward call. |
Absurd | Supports that x is a tensor with shape = [batch_size, channel_number, height, width], some may be positive value and others may be 0. And I only want to keep the value of top 10% positive values of each channel and make others 0. But the problem is that the number of pixels of positive value in each channel is differen... | ptrblck | It shouldn’t matter, if some values are positive and others zero, since the result tensor would also contain zeros. So even if the top 10% includes zeros (if not enough positive values were found), you wouldn’t change the output, would you?
If that’s the case, this code should work:
# Setup
x = to… |
sebastienwood | Hi,I am considering the use of gradient checkpointing to lessen the VRAM load. From what I understand there were some issues with stochastic nodes (e.g. Dropout) at some point in time to apply gradient checkpointing.However I have a kind of Bayesian Neural Network which needs quite a bit of memory, hence I am intereste... | ptrblck | Thanks for the link!
While this notebook gives you a really good example of the usage, note that it’s a bit outdated by now and if I’m not mistaken,@mcarilli’sPRshould have enabled the bitwise accuracy between standard models and checkpointed models.These testsalso should verify this behavior… |
yeedTorch | I am just starting out with libtorch and pytorch as well, so I apologize if I haven’t searched enough for an answer before posting.Looking at some examplary code found online and trying that on my own machine I have stumbled upon this expression: target.eq(pred).sum().template item<int64_t>();I have never seen a .templ... | ptrblck | The template keyword is to disambiguate the actual call, as otherwise the expression might be understood by the compiler as item less-than int64_t greater-than ().This postgoes into detail and can explain it way better than I can. |
ed-fish | I have a multi-label problem where I need to calculate the F1 Metric, currently using SKLearn Metrics f1_score with samples as average.Is it correct that I need to add the f1 score for each batch and then divide by the length of the dataset to get the correct value. Currently I am getting a 40% f1 accuracy which seems ... | ptrblck | I don’t think you can simply calculate the average of the F1 score, as shown in this small dummy example:
preds = np.random.randint(0, 2, (100,))
targets = np.random.randint(0, 2, (100,))
f1_ref = f1_score(targets, preds)
f1_running = 0
batch_size = 10
for i in range(0, preds.shape[0], batch_siz… |
LeErnst | Hello together,lets say we have aReLU-NNclass and for the training phase atraining_backendclass which handles all the optimization data and so on. Within thetraining_backend__init__method there are the following assignments:self.model = model # a NN-model of class ReLU-NN
self.optimizer = torch.optim.LBFGS(self.model.p... | ptrblck | Yes, you would need to create a new optimizer for the new model, as the old optimizer stores references to the initially passed parameters.
Alternatively, you could add the new parameters via add_param_group, but I don’t think you would have any benefit from it. |
GB_K | Hello. I am newbie for PyTorch.I think I fall in love with PyTorch these days, but I don’t know why XD.I coded softmax classifier. But I am not sure it is trained correctly.I get weird accuracy and loss values from the plot.My model code is as follows:import numpy as np
import torch
use_cuda = torch.cuda.is_available... | ptrblck | nn.CrossEntropyLoss() expects raw logits as the model output, as internally F.log_softmax and nn.NLLLoss will be applied, so you should remove the F.softmax in your model.
Also, the target is expected to have the shape [batch_size] and contain class indices in the range [0, nb_classes-1], so these … |
John_J_Watson | I am trying to build a small siamese network (with an aim to get encodings from the last/pre-last layer) and would like to use a pretrained model + the extra layers needed to get the encodings.I have something like this at the moment, but the results dont look great, so I now wonder if this is the correct way to build ... | ptrblck | Your new use case seems to use the penultimate activation tensors as an extracted feature.
While your approach would return the feature tensor before the pooling layer (which will thus be bigger), my proposed approach would apply the pooling and thus yield a smaller activation.
I don’t know, how y… |
ActonMartin | when I use a pytorch-template for my dataset, some errors just like monster on the way. When I solve one, another one is coming and say hello to me. But this error make me feel wondering.I just write my dataset dataloader in dataloader/dataloaders.py;make a new loss in model/loss.pyTHE ERROR HINTS ISTrainable parameter... | ptrblck | It seems that img is a ByteTensor, which you are trying to normalize with floating point values.
This simple code snippet will raise the same issue:
img = torch.randint(0, 255, (3, 24, 24)).byte()
img.add_(torch.tensor(1.))
Try to transform img to a FloatTensor via img = img.float() before normal… |
henry_Kang | Hello. I am currently using the 2 GPU machines in the lab.The first one, it has 2 Titan V.Second, the other has 4 Titan V.When I train the same dataset but 2 times bigger batch size but 2 titan V result is better.The network is Mobilenet V3 based network.I have read some articles, and they said that Sync batch normaliz... | ptrblck | I’ve seen some experiments for large scale systems, where the learning rate was adapted to the batch size as seen inTraining ImageNet in 1 hour.
However, this effect should be much smaller in your setup. Might still be worth a try to lower it and see, if it changes the convergence. |
Michael-Equi | Hello,I am new to pytorch and am trying to implement a custom neural network that includes and LSTM for a robot navigation task. I need to initialize the LSTM’s hidden state with the output of an upstream model. When I try to set the initial hidden state I get the errorIndexError: index 1 is out of bounds for dimension... | ptrblck | nn.LSTM expects the a tuple with the hidden_state and cell_state as the second argument, so this code should work:
x, hidden = self.lstm(actions, (torch.zeros(1, 2, 128), torch.zeros(1, 2, 128)))
Unrelated to this problem, but note that you are reassigning x and this the output of self.input_fc wi… |
Valerio_Biscione | When I want to do transfer learning, I set the require_grad = False and only pass the other parameters to the optimizer. But what happens if I only do one of these two steps?What happens if I set several modules’ reguire_grad = False but then I pass all net.parameters() to the optimize.What happens if I keep the requir... | ptrblck | They will yield the equivalent results, yes.
Filtering out the parameters is explicit and could thus increase the code readability and will also avoid iterating over parameters without a grad attribute in the step method.
Approach (1) would allow you to unfreeze the parameters later in training di… |
mohit117 | I was going through thefollowing informationon reducing learning rates in PyTorch to really low value like 1e-9.And I am amazed why doingloss = loss/100is equivalent to reducing learning rate by 100? The full snippet is below.outputs = model(batch)
loss = criterion(outputs, targets)
# Equivalent to lowering the learni... | ptrblck | If you scale the loss, you’ll also scale the gradients.
In a simple use case, this can be used instead of changing the learning rate, as seen here:
# Setup
torch.manual_seed(2809)
lin = nn.Linear(2, 2, bias=False)
x = torch.randn(1, 2)
# Standard approach
out = lin(x)
loss = out.sum()
print(loss… |
Qinru_Li | Say in the forward() pass, I generate the network predictions like the followingdef forward(self, input):
conditions = [1, 2, 3, 4, 5]
out_dict = {}
for c in conditions:
output = self.network( (input, c) )
out_dict[index of c] = output
return out_dictNow from the ground truth, we ... | ptrblck | The print statement might be buggy, if you are directly printing c in the lambda expression as explainedhere, so you might need to assign the value of c as a new argument to the lambda function via:
lambda grad, c=c: print(c, grad) |
lkchenxicvi | I wanto update BatchNorm2D after loss.backward.But this problem cannot be solved.Code show as below.def updateBN():for m in model.modules():if isinstance(m, nn.BatchNorm2d):m.weight.grad.data.add_(0.001*torch.sign(m.weight.data)) # L1train:model.zero_grad()output= model(input)loss = nn.BCEloss(output,target)loss.backw... | ptrblck | This dummy code snippet seems to work, if I use updateBN and BN_grad_zero after the backward call:
def updateBN():
for m in model.modules():
if isinstance(m, nn.BatchNorm2d):
m.weight.grad.add_(torch.sign(m.weight))
def BN_grad_zero():
for m in model.modules():
… |
MUnique | Hello,I have a tensor in size of (BTCHW) in which B is the batch size, T is the number of frames of the video, C the number of channels, and H,W the spatial size. This tensor is the extracted feature map of testing some videos on a pre-trained network. As the number of frames may vary from a video to another I wanted t... | ptrblck | You could permute the dimensions and use the temporal dimension as a “fake” spatial dimension.
Afterwards you could permute it back to the original shape.
Let me know, if this would work for you. |
Romina_Baila | Hi there!I am fairly new to Pytorch and I am trying to provide a different learning rate for the parameters from BERT, and the rest of the model’s parameters to have the same lr.My model class looks like this (it’s from a tutorial):class BERTGRUModel(nn.Module):
def __init__(self,
bert,
... | ptrblck | The dropout layer doesn’t have trainable parameters, but besides that the code looks alright.
Since your model is training with the “standard” approach, could you use your per-parameter optimizer with the same learning rate for all parameters, as you’ve used in the working approach?
Assuming your … |
complexfilter | import torchx = torch.tensor(5., requires_grad=True)y = 2xxx.data*=6y.backward()print(x.grad) | ptrblck | The manipulation of the .data attribute cannot be tracked by Autograd and can yield wrong results (as in this case) and other unexpected side effects.
Remove the x.data manipulation and it should work. |
tirthasheshpatel | I have been trying to implement convolutional VAE in PyTorch for a while now and am somehow not able to correctly train my network. Here’s the encoder, decoder, and training loop. I am training the model on MNIST dataset.Encoder output: Two tensors (loc, logvar) of shape[batch_size, latent_dims]Decoder output: Image of... | ptrblck | You are right and it shouldn’t make a difference, as the computation graph will be the same.
It might be a typo or copy-paste issue, but your optimizer in the first approach takes the parameters from model, which is undefined. It should get the parameters of encoder and decoder so that it can upda… |
julioeu99 | a=[]
for ne, naa in zip(ne, naa):
de+=distance.euclidean(naa,ne)
a.append(de/size_batch)
print(*a, sep = ", ")I wanted to put all data inside the array, and print whats inside it.I think the array is overwriting, and its stuck on the first position. How can i store all values in this array?I tried this to:v=0
a.ins... | ptrblck | Ah sorry, I missed the errors.
You are currently overwriting ne and naa in the loop, so use other variable names for the single elements and also move the a.append call inside the loop:
for ne_, naa_ in zip(ne, naa):
de+=distance.euclidean(naa_,ne_)
a.append(de/size_batch) |
sh0416 | Is the Adam’s state dict work correct when we use DDP???I think there is no sync for the optimizer. Do I have to make code for this manually?Thanks, | ptrblck | DDP should synchronize the gradients in the backward using AllReduce operations, such that each optimizer should use the same model parameters as well as gradients, thus also creating the same internal states.
I don’t think there is a need to synchronize the optimizer’s state, but@mrshenlimight c… |
henry_Kang | Hello. I am dealing with the multi-class segmentation.I used to handle the binary class for semantic segmentation.In the binary, I use the binary mask as the target.However in the multi-class, it looks like I need some change.DSC_39741280×720 1.62 KBThis is my mask.I have 5 classes which are Red, Green,Blue, white and ... | ptrblck | Assuming pipe is a DataLoader object, you could iterate it once and collect all targets via:
targets = []
for _, target in pipe:
targets.append(target)
targets = torch.stack(targets)
and calculate the class distribution later.
I hope that the target tensors are not too big to fit into your RA… |
Neofytos | I have reimplemented BatchNorm1D based on the implementation provided by@ptrblck(greatly appreciated!), here:pytorch_misc/batch_norm_manual.py at master · ptrblck/pytorch_misc · GitHubIn order to verify identical behaviour with the nn.BatchNorm equivalent, I initiate 2 models (as well as 2 optimizers), one using MyBatc... | ptrblck | Ah OK.
The backward pass of repeat_interleave is not deterministic as explained in the linked docs:
Additionally, the backward path for repeat_interleave() operates nondeterministically on the CUDA backend because repeat_interleave() is implemented using index_select() , the backward path fo… |
ryoma | How can I assign forward-adaptive learning rates to modules in sequential?I know in normal case, we can use optimizer and make this like"params" : model.a.parameters(), 'lr' : lr / 100, but I wanna use different learning-rate for loss1 and loss2 which went through the same module.class X(nn.Module):
def __init__(sel... | ptrblck | The loss calculation is independent from the optimization step (parameter update) in general.
You could create two optimizers with the specified learning rates and apply them sequentially, if that would fit your use case:
optimizer1.zero_grad()
loss1.backward(retain_graph=True) # calculate gradien… |
feiland | Hi there,I am using code from a CIFAR classification problem (num_classes = 10) and want to use the code for my dataset (CheXpert with num_classes = 3). Therefore, I changed the num_classes in the ResNet model from 10 to 3.class ResNet(FitModule):
def __init__(self, block, num_blocks, num_classes=3): #changed fr... | ptrblck | For 3 classes, your target should have the shape [batch_size] (which seems to be correct) and contain the values [0, 1, 2]. It seems you are using a value of 3, which will raise this error, as this would mean you are using 4 classes (note that the class index starts at 0). |
mohit117 | Hello,I am confused when to use conv.weight.data VS conv.weight. For example the followingcodeuses,nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')but I also see at many placesnn.init.kaiming_normal_(m.weight.DATA, mode='fan_out', nonlinearity='relu')Whic one to use? I am using PYTORCH 1.3.1.To in... | ptrblck | Don’t use the .data attribute as it might yield unwanted side effects.
While you will be able to manipulate the underlying data without raising an error, Autograd won’t be able to track these operations and you might run into a variety of issues later (we had quite a few of these issues already her… |
sh0416 | Code:model0 = nn.Linear(10, 10)
model1 = nn.Linear(10, 10)
model2 = nn.Linear(10, 10)
model3 = nn.Linear(10, 10)
input = torch.rand(128 ,10)
output = model3(model2(model1(model0(input))))
model0.to('cuda:0')
model1.to('cuda:1')
model2.to('cuda:2')
model3.to('cuda:3')
pred = model3(model2(model1(model0(input.to('cuda:0'... | ptrblck | This small difference is most likely a result of the limited floating point precision, which can be seen e.g. by changing the order of operations:
x = torch.randn(10, 10, 10)
sum1 = x.sum()
sum2 = x.sum(0).sum(0).sum(0)
print(sum1 - sum2)
> tensor(-3.8147e-06)
Avoiding these differences is espec… |
David_Hresko | Hi I am trying to use thishttps://pytorch.org/tutorials/intermediate/memory_format_tutorial.htmlon my model. But the channels are still not converted. Can you help me ? Is it even possible to convert ?Here is my GAN generator model:class UNetDown(nn.Module):
def __init__(self, input_size: int, output_filters: int, ... | ptrblck | Thanks for the update!
There seems to be a small misunderstanding.
You should still create the tensors in the default format [N, C, H, W] and just call to(memory_format=torch.channels_last) on it, so that your code changes would be minimal.
This code works for me:
model = Generator((2048, 1, 2))… |
cevvalu | Hi, i am trying to get next predicted word in the sequence. Is it possible to get maximum value from dense layer’s output without softmax since i am not doing any classification | ptrblck | That is correct. It will apply F.log_softmax internally, so you shouldn’t add a softmax layer in your model. |
vdw | I’m trying my hands on Siamese Network models. After searching for some examples, this seems to be the common way to set up the modelclass SiameseNetwork(nn.Module):
def __init__(self, core_model):
super(SiameseNetwork, self).__init__()
# Define layers
self.layer1 = ...
self.layer2 = ...
...
... | ptrblck | That’s a weird issue.
I tried to reproduce it using your code snippets, but they seem to work fine:
class SiameseNetwork(nn.Module):
def __init__(self):
super(SiameseNetwork, self).__init__()
# Define layers
self.layer1 = nn.Linear(1, 1)
self.layer2 = nn.Linear(… |
Jack_Rolph | I have to perform the operation:I have two tensors that I want to multiply in this way,AandB:A = torch.randn(B,C,j,i)
B = torch.randn(B,C,j,k)
C = AxB
C.shape = torch.Size(B,C,j,i,k)Where I have assumed the shape of the output tensor based on the indices of the equation.What is the function that I should use to produce... | ptrblck | Would this code work?
B, C, i, j, k = 2, 3, 4, 5, 6
A = torch.randn(B,C,j,i)
B = torch.randn(B,C,j,k)
C = torch.matmul(A.unsqueeze(4), B.unsqueeze(3))
print(C.shape) |
Arjun_Gupta | From the documentation: “brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]”brightness by default is set to 0. This means that the brightness factor is chosen uniformly from [1, 1] meaning that brightness factor=1. The other parameters (contrast, saturation, hue) also seem to be constan... | ptrblck | You could use the staticmethod get_params to apply the same “random” transformation via:
img = transforms.ToPILImage()(torch.randn(3, 224, 224))
color_jitter = transforms.ColorJitter(brightness=0.1, contrast=0.1, saturation=0.1, hue=0.1)
transform = transforms.ColorJitter.get_params(
color_jit… |
mathematics | As official doc gives example to upscale the imagepixel_shuffle = nn.PixelShuffle(3)
input = torch.randn(1, 9, 4, 4)
output = pixel_shuffle(input)
# torch.Size([1, 1, 12, 12])As it mutilplies by input, I wanted to use 2 or any other input , giving erorRuntimeError: invalid argument 2: size ‘[1 x 2 x 2 x 2 x 4 x 4]’ is ... | ptrblck | You won’t be able to convert 512 channels to 3 given the formula fromthe docs.
input [N, L=C*factor**2, H_in, W_in]
output [N, C, H_out=H_in*factor, W_out=W_in*factor]
For your setup you would need to calculate:
3 * factor**2 = 512
factor**2 = 512/3
factor = sqrt(512/3)
factor ~= 13.07 # not an … |
Landu | i’m using both of save_image() and Summarywriter.add_image()i made an image from several images. ( N,C,H,W->C,HN,WN)but i found that MNIST (1,H,W) works well in both, but color image doesn’t work wellhere’s the images스크린샷, 2020-05-25 07-36-27808×396 466 KBthe left one is using add_image() (on tensorboard)and the righ... | ptrblck | save_image “unnormalizes” the image via:
ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()
I don’t know, if add_image of TensorBoard does the same, but it looks like the colors might be clipped, so you could try to apply the same method as in save_image.… |
vaseline555 | Dear folks,hello, I am a quite newbie in deep learning with PyTorch…I am trying to build an image classification model using PyTorch,but in the process of pre-processing dataset, I’ve stuck with a problem.Problem)I want to read a bunch of.npyfiles in a directory (e.g. ‘/training’)One of the.npyfiles consists of tensors... | ptrblck | There are different way of handling this use case.
The simplest would be to load the complete data into memory and just use some conditions on the index to select the right numpy array where the current sample is located to load it.
The other approach would be to create a separate Dataset for each… |
saluei | I have two functions for calculating entropy in first one (named: ImageEntropy_gpu) use torch.histc function and run it in GPU (nvidia 2070) and in second one (named: ImageEntropy_cpu) use numpy library and run at CPU (i7-7800x)def ImageEntropy_gpu(img):sz=img.view(-1).size()[0]hist_probability=torch.histc(img.view(-1... | ptrblck | The performance will depend on the workload you are deploying to the device.
While small workloads will be faster on the CPU due to the kernel launch latency on the GPU, you should see a speedup for bigger sizes.
Using this code:
nb_iters = 100
for device in ['cpu', 'cuda']:
for s in torch.l… |
collinarnett | I’m reading this paper on a DCGAN and the authors write:For upsampling by the generator, we use strided convolution transpose operations instead of pixelshuffling [43] or interpolation, as we found this to work better in practice. We set the slope of theLeakyReLU units to 0.2 and the dropout rate to 0.1 during training... | ptrblck | I don’t think “downscaling” is referring to the spatial size, but to a multiplicative factor.
Here normalization is mentioned:
which seems to point towards using a constant factor for the downscaling via:
act = act * 1/factor |
darylnak | Suppose I have the following tensors:x =
[[1,2,3],
[4,5,6],
[7,8,9]]
y =
[[11,21,31],
[41,51,61],
[71,81,91]]
z=
[[1],
[2],
[0]]Wherex,yare both(h,w)andzis(h,1). I want to create a new tensorkthat it is a copy ofxexcept I want to copy thez[i][0]column at rowifromyinto rowiat columnz[i][0]inx. Thus, using the ... | ptrblck | A combination of gather and scatter_ should work:
x = torch.tensor([[1,2,3],
[4,5,6],
[7,8,9]])
y = torch.tensor([[11,21,31],
[41,51,61],
[71,81,91]])
z = torch.tensor([[1],
[2],
[0]])
k … |
Naveen | I am getting above error my torch error, my torch version are torch 1.4.0+cputorchvision 0.5.0+cpu.any help?Thanks | ptrblck | This method was introduced in 1.5.0 so you would need to update PyTorch to the latest stable version. |
Aaditya_Chandrasekha | I am trying to invoke a gradient clipping in C++ similar to this line of code in Python :torch.nn.utils.clip_grad_norm_(Net.parameters(),0.2)In C++ I am callingtorch::nn::utils::clip_grad_norm_(Net->parameters(), 0.2);Can anyone kindly verify that this is the right call ? | ptrblck | The usage look correct and is also used in this way inthis test. |
Shubhankar | FeatureIt would be really helpful if we can implementsetattrmethods in respective classes (say transforms.transform.Normalize) so that attributes of objects can be set recursively say for example by using a loop.MotivationIt would be helpful to loop through multiple attributes and set them on the fly in order to compar... | ptrblck | You should be able to directly access the attributes of the transformations, as they are implemented as Python classes:
norm = transforms.Normalize(mean=torch.tensor([0.5, 0.5, 0.5]),
std=torch.tensor([0.5, 0.5, 0.5]))
print(norm)
norm.mean = torch.tensor([1.5, 1.5, 1.5]… |
justanhduc | Hello. How can I tile/repeat a tensor in such a way that each value is tiled/repeated a different number of times other than looping then concatenating?For e.g., fromtorch.Tensor([0, 1]), how can I tile the first value two times and the second three times to gettorch.Tensor([0, 0, 1, 1, 1]). Thanks in advance! | ptrblck | torch.repeat_interleave should work:
x = torch.tensor([0, 1])
print(torch.repeat_interleave(x, torch.tensor([2, 3])))
> tensor([0, 0, 1, 1, 1]) |
cevvalu | Hi, trying to plot training and test loss in same graph, any advice? | ptrblck | You could use matplotlib.pylot to plot multiple graphs in the same plot.
Alternatively, PyTorch has also TensorBoard as well as Visdom support. |
Hari_Krishnan | I’m trying to implement a variant of capsule network where the matrix multiplication is replaced by element-wise multiplication with a vector. During training (mostly after the first backpropagation) the outputs become nan. I tried using gradient clipping, but it didn’ work. I’m working with MNIST dataset and I’m norma... | ptrblck | The values of squared_norm in PrimaryCaps explode and create the NaNs.
In the last iteration before the NaNs are raised PrimaryCaps creates tensors with these statistics:
print(squared_norm.min(), squared_norm.max())
> tensor(1.4527e+20, device='cuda:0', grad_fn=<MinBackward1>) tensor(5.3600e+26, … |
CesMak | Hey there,I get the following runntime error:Traceback (most recent call last):
File "ppo_witches_multi2.py", line 420, in <module>
learn_single(ppo1, update_timestep, eps_decay, env)
File "ppo_witches_multi2.py", line 269, in learn_single
ppo.my_update(memory)
File "ppo_witches_multi2.py", line 174, in m... | ptrblck | You would have to lower the memory footprint e.g. by reducing the batch size during training or using a smaller model.
However, let’s first make sure you are not leaking memory.
Are you running out of memory in the first iteration or are you seeing an increase in the memory usage during training?
… |
rsomani95 | I’m trying to combine multiple related datasets and models into one giant model. Here’s what the architecture looks like:Screenshot 2020-05-23 at 11.58.54 PM732×470 8.73 KBFor eachhead, there’s a dataset with the following structure:Screenshot 2020-05-24 at 12.01.52 AM360×652 7.43 KBI’ve referred to the following 2 sou... | ptrblck | One possible approach would be to create two separate DataLoader and use their iterators directly via:
dataset_head1 = TensorDataset(torch.randn(10, 1), torch.randn(10, 1))
dataset_head2 = TensorDataset(torch.randn(10, 1), torch.randn(10, 1))
for epoch in range(2):
print('epoch ', epoch)
#… |
Anuj_Daga | RuntimeError Traceback (most recent call last)
<ipython-input-3-0c9f361b4bf0> in <module>
260 if __name__ == "__main__":
261 for epoch in range(1, epochs + 1):
--> 262 train(epoch)
<ipython-input-3-0c9f361b4bf0> in train(epoch)
239
240
--> 241 loss.bac... | ptrblck | Just for the same of debugging, I would split the pow operations, which are applying a root to the input, and add an assert statement for the input to check for negative values. |
fulltopic | Hi,I had pre-trained a RNN with BatchNormalization with collected data. In training, the input was in sizes of {batchSize, seqLen, others} so that the num_features of BatchNorm layer is seqLen (a fixed number). Then I want to transfer the RNN into A3C and train it online. In this case, the input is {1, 1, others} in r... | ptrblck | If you are dealing with a different number of features for the batchnorm layer, you could add a condition into your model, which would then pick the right batchnorm layer for the current input.
I’m not familiar with your use case, but maybe it would also make sense to slice and copy the batchnorm l… |
Enric_Moreu | Hello!For the last 2 weeks I’ve been stuck trying to count balls from a synthetic dataset I generated.When I set a batch size higher than 1, the network predicts the average value all the time.Otherwise, the network works great in train/valDataset: 5000 images with grey background and blue balls of the same size around... | ptrblck | Thanks for the executable code, that was really helpful.
You are accidentally broadcasting the loss, since you have a mismatch in the output and target tensors.
While your output has the shape [batch_size, 1], the target has [batch_size].
This yields to a broadcasting as seen here:
# your code w… |
KeisukeShimokawa | After reproducing the FQGAN implementation, CUDA out of memory occurred while training the model.However, when I removed the feature quantization part that I implemented myself and ran it, no error occurred.This means that the error occurs either in the model I implemented or in the FQ part where the loss value is adde... | ptrblck | One possibility of an increased memory usage might be the storage of the computation graph.
embed, cluster_size, and ema_embed are created as buffers, which would register the tensors without making them trainable (their requires_grad attribute would be False).
However, in the forward method you a… |
themoonboy | Let me use a simple example to show the caseimport torch
a = torch.rand(10000, 10000).cuda() # memory size: 865 MiB
del a
torch.cuda.empty_cache() # still have 483 MiBThat seems very strange, even though I use “del Tensor” + torch.cuda.empty_cache(), there are still more than half memory left in CUDA side (483 MB i... | ptrblck | If you are checking the memory via nvidia-smi, note that the CUDA context will also use memory.
The allocated and cached memory will be freed using your code snippet:
print(torch.cuda.memory_allocated())
print(torch.cuda.memory_cached())
> 0
> 0
a = torch.rand(10000, 10000).cuda()
print(torch.c… |
themoonboy | Hi, here is one toy code about this issue:import torch
torch.cuda.set_device(3)
a = torch.rand(10000, 10000).cuda()
# monitor cuda:3 by "watch -n 0.01 nvidia-smi"
a = torch.add(a, 0.0)
# keep monitoringWhen using same variable name “a” in torch.add, I find the old a’s memory is not freed in cuda, it still exists even... | ptrblck | a will be freed automatically, if no reference points to this variable.
Note that PyTorch uses a memory caching mechanism, so nvidia-smi will show all allocated and cached memory as well as the memory used by the CUDA context.
Here is a small example to demonstrate this behavior:
# Should be empt… |
cijerezg | I have the following code:for count, params in enumerate(agent.actor.parameters()):
print(params.grad)where agent is a class that has the neural network: actor. If I run that code, it prints the gradients, which is a tensor of size 4x5. Now, if I do something like this:for count, params in enumerate(agent.actor.pa... | ptrblck | The operations such as torch.sum and torch.abs shouldn’t change any behavior and I assume you might have used the code snippets in different parts of your original code.
Before the first backward call, all .grad attributes are set to None.
After the gradients were calculated for the very first tim… |
ericrhenry | After laying down a lot of infrastructure (C++ frontend), I am just launching into attempting to train. I am working with a 4-class image classification problem, with several thousand 41X41 images. The model is a couple of chained convolutions with rectifiers in between, followed by a MaxPool and flattening to feed int... | ptrblck | Thanks for the detailed explanation and I think your “sanity check” makes sense.
Note that I don’t have a background in numerical mathematics, so please take this post with a grain of salt.
Yes, this is correct. The optimizer stores references to all parameters and you could inspect the id() of t… |
mohit117 | Hello,I know settingtorch.backends.cudnnfor fixed input size improves performance for GPU inference. But if i want to speed up inference just on CPU does this help (for fixed input size)? | ptrblck | No, cudnn is a library on top of CUDA and works only on GPUs.
For CPU performance improvement, you could use e.g. MKL. |
2hyes | Hello.I want to detect the fabric defect using autoencoder.Actually, data size is too small to do ML, so I cropped images to patches.number of nodefect images: 85number of patch of a image: 172Then I trained the autoencoder.During training time, loss is computed for every patches, maybe # of losses are (num_epoch * # o... | ptrblck | I’m not sure if you really need to compute the mean of the losses of all patches from the same image and I would assume that you could directly use each patch separately.
During validation you would have to use all patches from the image, apply your threshold, and classify the image based on the cl… |
Jack_Rolph | Suppose I have two tensors:a = torch.randn(10, 1000, 1, 4)
b = torch.randn(10, 1000, 6, 4)Where the third index is the index of a vector.I want to take the dot product between each vector inbwith respect to the vector ina.To illustrate, this is what I mean:dots = torch.Tensor(10, 1000, 6, 1)
for b in range(10):
fo... | ptrblck | This code should work:
a = torch.randn(10, 1000, 1, 4)
b = torch.randn(10, 1000, 6, 4)
dots = torch.Tensor(10, 1000, 6, 1)
for x in range(10):
for y in range(1000):
for z in range(6):
dots[x,y,z] = torch.dot(b[x,y,z], a[x,y,0])
ret = torch.matmul(b, a.permute(0, 1, 3,… |
John_J_Watson | I am trying to use the ImageFolder class to read a bunch of images which are arranged this way:0(folder)
image01
image01
1(folder)
image01
image01
2(folder)
image01
image01Then I do something lilke:ds = torchvision.datasets.ImageFolder( root=path_to, transform=p )I can see the list of class... | ptrblck | That is expected and the target should contain the class indices, not the names.
So e.g. for three folders your target should contain values in [0, 1, 2]These target values are used to index the output of the model during the loss calculation, so they are used as numerical values instead of the… |
GeoffNN | I have a 2d TensorAof shape(d, d)and I want to get the indices of its maximal element.torch.argmaxonly returns a single index. For now I got the result doing the following, but it seems involuted.vals, row_idx = A.max(0)
col_idx = vals.argmax(0)And then,A[row_idx, col_idx]is the correct maximal value. Is there any more... | ptrblck | Alternatively, this code should also work:
x = torch.randn(10, 10)
print((x==torch.max(x)).nonzero()) |
sjt524 | Sorry for my poor English.This is my code:trainset = datasets.MNIST(‘data’, train=True, download=False, transform=transform)trainloader = torch.utils.data.DataLoader(trainset,batch_size=32, shuffle=True)Now I want to choose a part of train sets(like 3000 images and labels) from shuffled datasets every epoch. I want to ... | ptrblck | You could manually shuffle the indices using:
indices = torch.randperm(len(train_dataset))[:3000]
and pass these indices to a RandomSubsetSampler, which can then be passed to the DataLoader. |
jc711 | I am trying to reuse some of the resnet layers for a custom architecture and ran into a issue I can’t figure out. Here is a simplified example; when I run:import torch
from torchvision import models
from torchsummary import summary
def convrelu(in_channels, out_channels, kernel, padding):
return nn.Sequential(
... | ptrblck | I assume summary loops over all registered modules inside the model and prints them out.
Since you’ve registered resnet18 as self.base_model and again its first three layers as self.layer0 in an nn.Sequential container, these modules will be printed as duplicates. |
Sam_Lerman | I need a Resnet pretrained on COCO, so I opted to use:models.detection.fasterrcnn_resnet50_fpn(pretrained=True)However, all I need are the Resnet components for simple classification. How do I isolate that model without all of the extra FasterRCNN parts? | ptrblck | Yeah, but not out of the box.
Note that the FasterRCNN ResNet backbone uses FrozenBatchNorm layers, while you would most likely want to use the trainable batchnorm layers.
Also, the last linear layer is missing and the output is different.
However, there might be a hacky way to grab the backbone’… |
ptrblck | Assuming your current target is one-hot encoded in the channel dimension, i.e. it uses a 1 for the “active” class in that channel while all other channels contain zeros, you could use:target = torch.argmax(target, dim=1)to create the target with the expected class indices.If that doesn’t work for you, could you post an... | ptrblck | Assuming that you are working with 3 classes (based on the last edit of the post with the shape information), your model output should have the shape [batch_size, nb_classes=3, height, width].
To get the predicted class indices, you can use the same method:
preds = torch.argmax(output, dim=1) |
Abdulrahman | When i tried to reimplement MSELoss proposed hereLoss Pytroch Implementationwith a real example, it givesRuntimeError: derivative for argmax is not implementedalthough i take argmax with nn.MSELoss and worked.Code def my_MSELoss(predict, true):return ((predict - true)**2).mean()for epoch in range(5):losses = 0.0for da... | ptrblck | y_preds is still the argmax. You could get the gradients for the first output (which is the max value).
In that case max would be differentiable and the gradients would just flow back to the maximum value while all other values will get a 0 gradient.
Argmax on the other hand is not differentiable … |
Prasad_Raghavendra | I have been using PyTorch since about 2 weeks now (mainly due to the computing courses I have taken). But, I am not able to debug and figure out why my network is not learning.If I flatten both target and prediction, I am getting some error. If I convert both to one hot, I get multi-target not supported error. Now I am... | ptrblck | You are detaching the prediction tensor here:
y_pred1 = y_pred.data.numpy().astype("int")
Don’t use the .data attribute, as it may have unwanted side effects.
Also, once you leave PyTorch and use other libraries such as numpy, Autograd won’t be able to automatically create the backward pass for y… |
Deeply | A simple model like this one:model = torch.nn.Sequential(torch.nn.Linear(10, 1, bias=False)) | ptrblck | You would just need to wrap it in a torch.no_grad() block and manipulate the parameters as you want:
model = torch.nn.Sequential(nn.Linear(10, 1, bias=False))
with torch.no_grad():
model[0].weight = nn.Parameter(torch.ones_like(model[0].weight))
model[0].weight[0, 0] = 2.
model[0].weig… |
John_J_Watson | I am quite new to pytorch, and I am trying to create data within a dataloader and my code looks like so:a=[]
.. within a for loop
self.a.append(torch.stack([b[ith_idx][j], \
b[ith_idx][rnd_dist], \
b[rnd_cls_idx][rnd_dist_rnd_cls]]\
))
self.c.append([1,0])where, b is a python list of tensors. For example, the first ele... | ptrblck | Since you are passing two values to self.c, your expected shape would be [N, 2].
Could you explain a bit what your use case is and how self.c should be stacked to create a [500] tensor? |
nima_rafiee | HiI have an index vector like:idx_v = [1,2,4,0,3]A = [1, 1, 1, 1, 11, 1, 1, 1, 11, 1, 1, 1, 11, 1, 1, 1, 11, 1, 1, 1, 1]I want to set all elements of matrix A located before elements of idx_v vector to zero within each rowlike:At = [0, 1, 1, 1, 10, 0, 1, 1, 10, 0, 0, 0, 11, 1, 1, 1, 10, 0, 0, 1, 1]Is there any way to... | ptrblck | This code should work:
idx_v = torch.tensor([1,2,4,0,3])
A = torch.tensor([[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
torch.arange(idx_v)
res = torch.zeros_like(A).scatter_(1, idx_v.u… |
AlvinZheng | I run the following code:import torch
import torchvision
net = torchvision.models.resnet18()
optimizer = torch.optim.SGD(net.parameters(), lr=1)
lr_sche = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.1)
data = torch.rand(1, 3, 224, 224)
for epoch in range(5):
optimizer.step()
print('... | ptrblck | You should get a warning stating that you should use get_last_lr() instead of get_lr():
UserWarning: To get the last learning rate computed by the scheduler, please use get_last_lr().
This should give you the expected learning rates:
for epoch in range(5):
optimizer.step()
print… |
dachosen1 | I have a dataset with two classes and a severe class imbalance.I tried to use the weighed sampler to equalize the classes for training but only class showed during training. What did i do wrong?My dataset contains individual CSV , not images.def csv_loader(path: str) -> torch.Tensor:
data = np.array(pd.read_csv(pat... | ptrblck | The weigths tensor should contain the weight for each sample in your dataset, nor the class weights only.
Have a look atthis examplewhich shows a dummy use case. |
s_n | Is it possible that two instances of a convolutional layer in myinitmethod can share same set of weights?Ex:self.conv1 = nn.Conv2d(…)self.conv2 = MycustomConvFunction(…)So I want self.conv1 and self.conv2 to share same set of weights.Actually I want self.conv2 for inference and self.conv1 for training. | ptrblck | The most elegant way would probably be the functional API, which would only create a single weight parameter and just use it when it’s needed.
Alternatively, you could assign the weight parameter to your modules as describedhere. |
csblacknet | I tried the stackoverflow and other threads in forum but still my issues wasn’t resolved. I am a starter please help me understand what went wrong.id_2_token = dict(enumerate(set(n for name in names for n in name),1))
token_2_id = {value:key for key,value in id_2_token.items()}
print(len(id_2_token))
print(len(token_2_... | ptrblck | You cannot pass indices higher than embedding_dim-1, since the embedding layer is working as a lookup table. The input is used to index the corresponding embedding vector, so you should set embedding_dim as the highest value you would expect in your use case. |
SubhankarHalder | Hello!I am using Squeezenet 1_1 Model pretrained model to train a custom dataset with 4 classes. I used the following commands to instantiate the modelMODEL = models.squeezenet1_1(pretrained=True)
MODEL.classifier[1] = nn.Conv2d(512, self.num_classes, kernel_size=(1, 1), stride=(1, 1))Then, I write my training script, ... | ptrblck | Since you didn’t freeze any parameters, all should be trained as long as you pass them to the optimizers.
Pooling layers do not have any parameters.
You can check the updated parameters by creating a deepcopy of the state_dict before training and compare it to the state_dict after training:
state… |
Abhishek_Kishore | I read some posts about ModuleList and all of them said that adding modules to ModuleList gives access to parameters of the Neural Network but in “Training a classifier” example of 60 mins pytorch tutorial the modules are not added to any ModuleList and still the parameters could be accessed usingoptimizer = optim.SGD(... | ptrblck | Yes, that’s the difference between a Python list and an nn.ModuleList.
As explained in the linked topics, the parameters wrapped in a plain list won’t be registered, while the parameters from all modules inside an nn.ModuleList will be registered.
So if you want to use a list-like container, then … |
chetan06 | I am currently working on wheat detection challenge and was going through a notebook. And read something that am not gettingclass WheatTestDataset(Dataset):
def __init__(self, dataframe, image_dir, transforms=None):
super().__init__()
self.image_ids = dataframe['image_id'].unique()
self.df... | ptrblck | You can pass arbitrary numbers of arguments to a function using **kwargs as explainedhere. |
luminoussin | Hello, this is the first time I implement BCElogitLoss and I was wondering if my input is correct or not because I experienced a sudden spike of loss in during my training for classification loss. I read fromLogit Explanationthat the input should be [-inf, inf] and I check my input is something like this :torch.Size([1... | ptrblck | The input and target shapes look as if you were dealing with a multi-label classification use case, i.e. each sample might belong to zero, one, or more classes.
If that’s the case, then your approach should be correct.
However, the example targets seem to be one-hot encoded, which looks like a mul… |
martinr | Hi! I have a problem that one layer in my model takes up ca 6 GB of GPU RAM for forward pass, so I am unable to run batch sizes larger than 1 on my GPU.Of course, I am not interested in running the model with batch_size 1 and looking how to improve.I was thinking about “emulating” larger batch size. E.g., passing 10 si... | ptrblck | This postgives you some examples with advantages and shortcomings. |
olisp | I am trying to assign different weights to different classes, so I have modified my loss criterion as such:I had to convert the weight tensor to doubletorch.DoubleTensor(weight)since mymodelis already moved todouble().Am I doing this correctly ?weights = [0.4,0.8,1.0]
class_weights = torch.DoubleTensor(weights).cuda()... | ptrblck | This should be correct, yes. Are you seeing any issues using this code? |
arianhf | I am trying to implementthispaper.I have written the following code but since this is my first try, I am not sure about the code I have written.class myDataset(Dataset):
...
def __getitem__(self, idx):
self.item = self.sequences_1[idx] + self.sequences_2[idx]
return self.item, self.labels[idx], ... | ptrblck | nn.CrossEntropyLoss expects raw logits as the model outputs, so you should remove the last softmax layer in your model.
Do you have any other doubts regarding a specific part of the code? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.