user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
chinmay5
I am attempting to work on the following loss function. To my understanding, this is essentially a BCE loss function where we need to work with the weight parameter. I initially started withCounting the number of positive examples and thenweight = total_samples / number_positive_per_class. However, clearly this is not...
ptrblck
Yes, nn.BCEWithLogitsLoss can be used for binary and multi-label classification use cases.
KyleOng
Good day,How can I generate a mask tensor that has a specific ratio of 0 and 1? For example70:30of 0s and 1s in a 5 by 10 tensor will generate[[0,0,0,0,0,0,0,0,1,0], [1,1,1,0,0,0,1,1,0,0], [0,0,1,0,0,1,1,0,1,0], [0,1,0,1,0,1,1,0,0,0], [0,0,0,1,0,0,0,0,0,0]]Thanks in advance.
ptrblck
You could create the values using the defined number of samples beforehand, shuffle them, and reshape to the desired output: ones, zeros = 30, 70 x = torch.cat((torch.zeros(zeros), torch.ones(ones))) x = x[torch.randperm(x.size(0))] x = x.view(10, 10) print(x) > tensor([[0., 0., 0., 0., 0., 0., 0.,…
Phuc_Pham
I have the DataLoader class for 1 image and labels:class CoronalDataset(Dataset): def __init__(self, pet_type='interim', train=True, transform=None): train_valid = 'train' if train else 'valid' # Create the Tensor from the numpy array self.x = torch.from_numpy(np.load(f'{DATASET_DIR}/{pet_t...
ptrblck
In that case you could write a custom model and use these two inputs directly in the forward method. Here is a small example: class MyModel(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(10, 10) self.fc2 = nn.Linear(10, 10) def forw…
DanielC
I am wondering if there is existing function allow us to add two nodes sin and cos in a net like an activation function?
ptrblck
I’m not sure I understand the use case correctly, but in case you want to apply torch.cos and torch.sin on an activation you could directly do it via: def forward(self, x): # forward method of your model ... x = self.layer(x) ... x = torch.sin(x) x = torch.cos(x) ... ret…
Aakash_bhandari
I am training my transformer model and my model’s loss is “nan”. I have tried various workarounds but couldn’t figure it out. Please some help me in this.Here is my transformer model.import torch.nn as nn import torch import math class PositionalEncoding(nn.Module): def __init__(self, model_dim, dropout_rate=0.2, ...
ptrblck
If the invalid values is created in the forward pass, you could use e.g. forward hooks to check all intermediate outputs for NaNs and Infs (have a look atthis postto see an example usage). On the other hand, if you think that the backward pass might create invalid gradients, which would then creat…
icmp_no_request
Hi, when I run myTextCNNmodel (my filter size is [3, 4, 5]), it runs successfully in the 12 epochs (the total epoch number is 20), but when it starts the No.13 epoch it shows the error:RuntimeError: Calculated padded input size per channel: (4 x 100). Kernel size: (5 x 100). Kernel size can't be greater than actual inp...
ptrblck
The error points to an activation, which is too small for the specified kernel size. You would either have to enlarge your input, use a smaller kernel or remove some pooling layers.
SungmanHong
I have mobilenetV3Small ModelMobileNetV3( (features): Sequential( (0): ConvBNActivation( (0): Conv2d(3, 16, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (1): BatchNorm2d(16, eps=0.001, momentum=0.01, affine=True, track_running_stats=True) (2): Hardswish() ) (1): Inverte...
ptrblck
There are several options to remove/replace this layer depending on your use case. You could copy the source code of the model, remove the layer, change the forward method, and store this new model definition as a custom model. This would allow you to load this new model in your scripts and just tr…
ngoquanghuy
My training set is truly massive, a single sentence is absolutely long. An epoch takes so much time training so I don’t want to save checkpoint after each epoch. Instead i want to save checkpoint after certain steps.Can I just do that in normal way?
ptrblck
In case you want to continue from the same iteration, you would need to store the model, optimizer, and learning rate scheduler state_dicts as well as the current epoch and iteration. Assuming you want to get the same training batch, you could iterate the DataLoader in an “empty” loop until the appr…
WilliManFR
Hello,I have a problem that I don’t understand. It concerns the CrossEntropyLoss function. I am currently working on segmentation of a certain type of pattern in medical images. For this, I have built an architecture that returns after a softmax an array of output images of the form: [N, C, H, W] where N is the size of...
ptrblck
As you’ve already pointed out the issue is created by the missing “class dimension” in the output. In a multi-class segmentation use case nn.CrossEntropyLoss expects the model output to have the shape [batch_size, nb_classes, height, width], where each “channel” represents an activation maps, which…
krishna511
class MODEL(nn.Module): def __init__(self, attention_heads=4, attention_size=32, out_size=4): super(MODEL, self).__init__() self.conv1a = nn.Conv2d(kernel_size=(10, 2), in_channels=1, out_channels=16, padding=(4, 0)) self.conv1b = nn.Conv2d(kernel_size=(2,8), in_channels=1, out_channels=16, ...
ptrblck
I guess this error is raised during the forward pass, since the forward method definition is missing, so you would have to change call to forward.
tetelevm
Hello!I created, trained and saved my modelMyModelin Jupiter as'mymodel.pt'. But then I want to load it in another application. To do this, I created the same class in the file where I load it:class MyModel(nn.Module): def __init__(self): ... def forward(self, x): ...This file is the file with t...
ptrblck
It seems you’ve stored the model directly (not its staste_dict), so I think you would need to make sure the folder structure etc. on the inference application is the same as was used during training. The recommended way would be to store the state_dict of models instead, recreate the model object i…
Sayyed_Ali_Mousavi
Hello everyone. I am new to pytorch. I have a program that produce tensors and labels of them. I want to create a dataset (perhaps a .pt file) and use it for training. But how should i do it? How every tensor match its label? Thanks a lot.
ptrblck
Ah OK, that would fit my expectation of the error and this would work: my_x = torch.stack([torch.rand(2,2),torch.rand(2,2)]) my_y = torch.stack([torch.rand(1), torch.rand(1)]) my_dataset = torch.utils.data.TensorDataset(my_x,my_y) The error is raised, because tensors are expected, while you are pa…
negreanu1
Until now I was working with TensorFlow but for different reasons, I want to pass the code to Pytorch. I am working on this problem (tensorflow - Keras multioutput custom loss with intermediate layers output - Stack Overflow) and I don’t know if the code I have written in Pytorch does what I really want it to do, since...
ptrblck
Usually loss functions expect the model output as the first argument and the target as the second. I don’t know which loss functions you are using, but you might want to swap the order of inputs.
tejal567
I have observed that strides of input and output tensors (just before and after network inference) are different. This behavior can be observed both in python and C++. I am not sure whether this is an inherent feature or a bug.Example:input_Tensor size: [1, 3, 256, 256]input_Tensor strides: [256x256x3, 256x256, 256, 1]...
ptrblck
Thanks for the update. I haven’t reproduced the complete issue in libtorch, since you are already manually manipulating the .data attribute (which is not recommended, as it could yield unwanted issues, so wrap the code in a with torch.no_grad() block and assign the new nn.Parameter directly if nece…
111242
I have a neural network with input shape = 1000, hidden = 500, and output = 2 neurons for classification. I am trying to do transfer learning, and my pretrained model is shaped shape = 1000, hidden = 500, and output = 200 neurons. However, when I try to initialize the classification model parameters with the learnt par...
ptrblck
The model will change, but since you’ve manipulated the internal parameters manually, the in_features and other attributes won’t be changed as seen here: # default setup model = nn.Linear(10, 10, bias=False) print(model) > Linear(in_features=10, out_features=10, bias=False) x = torch.randn(1, 10) o…
Khabbab_Zakaria
I am using a modified Resnet18, with my own pooling function at the end of the Resnet.Here is my code:resnet = resnet18().cuda() #a modified resnet class Model(): def __init__(self, model, pool): self.model = model self.pool= pool #my own pool class which has trainable layers def forward(self,...
ptrblck
You would have to derive your custom Model from nn.Module as: class Model(nn.Module): def __init__(self, model, pool): super().__init__() ... to make sure all nn.Module methods and attributes are available.
TheOraware
After training model when i test model in batch using shuffle=False give me good score , when i use the same model and same test data using shuffle=True give me bad score , i am confused why it is so?dataset = pd.read_csv('Churn_Modelling.csv')I shuffle the data before splitting data into train/testfrom sklearn.utils i...
ptrblck
The running stats of batchnorm layers are updated during training using the training batch stats and the formula mentioned in thedocs, which can then be used during evaluation and makes the inference perform independent from the batch size. TheBatchNorm paperexplains this in more detail.
Parkz
I have the following model architecture, which essentially is a 5 layer LSTM that takes in 62 length strings and outputs classification predictions based on that. Because of how the data works, the first 3-5 characters are more important for the classification than the remainder of the strings. How do I get the model t...
ptrblck
The workflow to get the predictions sounds correct for the inference use case, but I assume won’t be used to train the model. Here is a small example of what I had in mind: # setup batch_size, nb_classes, seq_len = 2, 3, 4 output = torch.randn(batch_size, nb_classes, seq_len, requires_grad=True) t…
aflah02
I’m trying to build a simple MNIST Model and this is what I’ve built -training_loader = DataLoader(training_dataset, 128, shuffle = True) validation_loader = DataLoader(validation_dataset, 128) class mnistmodel(nn.Module): def __init__(self): super().__init__() self.linear1 = nn.Linear(784, 10) self.lin...
ptrblck
reshape is not an inplace operation, so you need to assign the return value to another object: xb = xb.reshape(-1, 784) Generally, I would recommend to use this approach: xb = xb.view(xb.size(0), -1) to keep the batch dimension and to get a better error message in case the feature dimension is i…
Ilya_Kotlov
Hi.I tried to look at the C code and in the code in the docs, but still didn’t figure it out,generally BatchNorm aggregates the mean and the variance of the samples it sees in train mode and then in test mode just uses them, my question is does the aggregation, i.e the updates of the mean and the variance according (in...
ptrblck
The running stats are updated during the forward pass as seen here: bn = nn.BatchNorm2d(3) x = torch.randn(16, 3, 24, 24) print(bn.running_mean) > tensor([0., 0., 0.]) print(bn.running_var) > tensor([1., 1., 1.]) out = bn(x) print(bn.running_mean) > tensor([ 0.0002, -0.0007, 0.0006]) print(bn.r…
Ray1
I am trying to do section 3 ofGoogle ColaboratoryHowever, there are two errors.When I try to train my model, I get an error for the loss function: multi-target not supported at /pytorch/aten/src/THCUNN/generic/ClassNLLCriterion.cu:15.The second error occurs when I change the hidden_dim back to 256, I get an error regar...
ptrblck
Remove the unnecessary dim1 from the target via .squeeze(1) and it should work.
lory
Hello, I have the below code which uses a fine tuned BERT model to predict if a sentence is positive or negative. I have 2 problems:The BertClassifier class is defined in another .py file where i trained and fine tuned the model. If i try to import just the class byfrom bert import BertClassifierand run the code, it w...
ptrblck
I guess the other .py file doesn’t use a guard such as if __name__ == "__main__", but executes code in the global space directly. If that’s the case, move the executable code (which would start the training) into the if-clause protection. Make sure all model parameters as well as the inputs and…
vishak_bharadwaj
I’m building a simple network that takes in two numbers and learns how to add them.import torch add1= torch.randint(0,9,size=[6000]) add2= torch.randint(0,9,size=[6000]) add_sum = add1 + add2This a pretty simple networkfrom torch import nn from torch.nn import functional as F class Net(nn.Module): def __init__(s...
ptrblck
Yes, thedocsmention the expected shape for each layer and I would stick it to it. My general rule is that a batch dimension is expected in nn.Modules. While e.g. linear layers could work with an input having a single dimension, you would have to verify what’s applied internally (which dimension is…
Sumit_Diware
Hello all,Consider a MNIST dataloader with batch size 128:train_loader = data.DataLoader( datasets.MNIST(’./data’, batch_size=128, shuffle=True, train=True, transform=transforms.ToTensor())When a batch of 128 images is processed during training, will this data loader always need to go to the disk for fetching the next ...
ptrblck
It depends on the implementation of the corresponding dataset and you could check it in the source code (as done for MNIST using my link). E.g. the often used ImageFolder dataset uses lazy loading, to save memory, while the CIFAR datasets also load the data and target into the RAM as seenhere. Cu…
zheng_wang
Hello, I encountered a memory leak when writing a convolutional layer using libtorch1.7GPU version. When I execute the code of torch::nn::functional::conv2d in a loop, the memory keeps growing. Excuse me, why is this?torch::Tensor gaussian_filter(torch::Tensor x, int channels) { /* *Parameters: * tensor x [C,H,W] i...
ptrblck
I’m still unsure if you are (accidentally) storing the tensors somehow or if they are attached to a computation graph, which could be stored in the assignment, so could you post an executable code snippet, which would reproduce this issue?
Oussama_Bouldjedri
I am using a capsule networks model, and at a certain point of the training the Relu function located in the conv layer results in nans, usingwith torch.autograd.detect_anomaly(): , I get this errorTraceback (most recent call last):File “C:\Users\obouldjedr\Desktop\lastcode4\cp\test_capsnet.py”, line 532, intrain(c...
ptrblck
The torch.sqrt method would create an Inf gradient for a zero input and a NaN output and gradient for a negative input, so you could add an eps value there as well or make sure the input is a positive number: x = torch.tensor([0.], requires_grad=True) y = torch.sqrt(x) y.backward() print(x.grad) > …
andrea_bragagnolo
Hi, given a Conv2d module I’d like to manually perform the biases addition, i.e. given a moduleMwith weightswand biasesb, I can compute the outputygiven and inputxasy = x * w + b.What I’d like to do is to evaluatex * wusing the module’s forward methodM(x)and then manually add the biasesb. Unfortunately I cannot just o...
ptrblck
Yes, the internal conv implementation (using MKL?) could use another approach than the native addition used in PyTorch, which could thus yield these small numerical mismatches.
sh0416
Hi,Is there any comprehensive guideline for indexing tensor?I’m trying to find the pytorch version of thislink.Or, is the indexing supported by numpy also supported in pytorch?Thanks,
ptrblck
I’m unsure about the relative parity between numpy’s and PyTorch’s indexing, but I’m usually also referring to the numpy docs in necessary and wasn’t running into an unsupported use case so far.
moutan
For my purposes I want to apply Group Normalization to three specific channel groups of a tensor. This groups are contiguous so for a Tensor with dimensions(N,C,H,W). Group 1 would be(N, : C /3,H,W), Group 2(N, C/3: 2C/3, H,W)and Group 3(N; 2C/3 : C, H , W). I tried looking in the code base but did not find what the lo...
ptrblck
Your assumption seems to be correct based on this small experiment: N, H, W = 16, 224, 224 # increasing groups norm = nn.GroupNorm(num_groups=3, num_channels=6) x = torch.cat(( torch.randn(N, 2, H, W) * 2 + 5, torch.randn(N, 2, H, W) * 4 + 10, torch.randn(N, 2, H, W) * 6 + 15, ), dim=1…
4158ndfkvBHJ1
Hello everybody,There is something I’m not understanding well about how autograd works. I am trying to implement a maximum likelihood model in pytorch. This model is maximizing a softmax distribution given some parameters, knowing some batch of data. My model class looks like this:class Model(nn.Module): def __ini...
ptrblck
It seems you are trying to initialize self.params as the trainable parameters in the model, which is not the case at the moment, since you are not registering the tensor and would need to use nn.Parameter(torch.ones(...)) instead. This will make sure this parameter will be properly registered and e.…
Jannis
Hi! I would like to calculate the gradient of torchvision.transforms.functional transformation parameters. For example, I would like to usetorchvision.transforms.functional.rotateand provide a tensor for the angle parameter so I can calculate the gradient of it. Is there any easy way of doing this in PyTorch right now?
ptrblck
I don’t think this is supported in torchvision transformations, as literals are expected and tensor inputs would raise an error. However,Korniais a differentiable computer vision library and might be helpful.CC@edgarribaas the core dev
phantom90
Hi there,Consider the following circumstance:model.eval() y = model(x) loss = criterion(y, label) # backward() and step() the loss, abbreviate.I just want to calculate the gradient and update parameters when things like BN and Dropouts are disabled. Are there any potential issues here?Thanks~
ptrblck
model.eval() does not disable the gradient calculations, but only changes the behavior of some layers (such as batchnorm and dropout), so I wouldn’t expect to see any issues with Autograd.
saeed_i
hi i am working about time series data. i have a problem that confused me. i am tuned a neural network with same implementation in both keras and pytorch but had different result.This is not the only problem. The keras model always gives the same results (Every time I do train model). But the Pytorch model gives the re...
ptrblck
You can use the torch.nn.init methods to initialize the parameters as shown in e.g.this post.
jS5t3r
Hi,I want to train this repository:pytorch-cifar100/train.py at master · weiaicunzai/pytorch-cifar100 · GitHubwhich is some years old.I am getting this message during training:python train.py -net resnet50 -b 64 > runs/performance/a100_128_b64_resnet50.log /home/user/.conda/envs/a100/lib/python3.8/site-packages/torch/j...
ptrblck
Both warnings mention a proper fix, so did you try to apply it and was it not working? E.g. the first one mentions that the .grad attribute of a non-leaf tensor can be accessed after calling .retain_grad() on this tensor.
Dadatata-JZ
Hi there,I have an imbalanced dataset, and I am trying to make each batch contains every class, regardless of the numbers as long as one exists. I found WeightedRandomSampler may be working. However, after I assign weights, the first batch always only draws samples from class0.There are six classes in total.class_sampl...
ptrblck
The weights should be passed as sample weights (a weight is assigned to each sample), not class weights.Hereis an example on how to use the WeightedRandomSampler.
abhibha1807
Hello,I am new to Pytorch and I want to implement an algorithm of the following format,#input1... output1 = model1(input1) output = model1(some_input) #calling output as input2 from now on output2 = model2(input2) loss2 = fn(output2) loss2.backward()If am not wrong, loss2.backward() should compute the gradients wrt t...
ptrblck
You are right in the assumption that passing the output of one model to the other would keep the computation graph intact and model1 should get valid gradients as long as the computation graph is not detached. I don’t know what model1.generate does so could you check, if output has a valid .grad_fn?…
miturian
I am trying to code a test case for multi task learning, using my own loss function. The idea is that the output layer is 3-dimensional, the first output is used for 1D regression, the last two are used for 2-class classification. So, my combined loss function is a weighted sum of L1 loss and CELoss.However, pytorch i...
ptrblck
You are using a target tensor as a LongTensor, which is fine for nn.CrossEntropyLoss, but will fail for nn.SmoothL1Loss, so you would have to transform it into a FloatTensor: loss = self.weights[0]*self.L1(output[:,0],target[:,0].float())+self.weights[1]*self.CE(output[:,1:3],target[:,1])
avalon1511
Hi, I am really new to all this and am working on an assignment with the DCGAN here -DCGAN Tutorial — PyTorch Tutorials 1.8.1+cu102 documentationI have trained this GAN using a dataset A. I need to train the last N (where N=1, 2, 3 etc) layers of the already trained GAN with dataset B - how can I do this?So far I have ...
ptrblck
Thanks for the explanation. I’m still unsure why you are rewrapping the layers in two nn.ModuleLists. I assume you are trying to use one nn.ModuleList for the “frozen” layers and another one for the ones, which should be fine tuned? Rewrapping the model would not be necessary, as it can break the …
weiguowilliam
How would you implement an ensemble of neural networks? I currently use a list like this:list_of_models = [model] * num_modelI wonder if there’s a more ‘Pytorch-like’&efficient way to construct an ensemble? Thank you in advance.
ptrblck
I assume model is an already initialized nn.Module object. If that’s the case, note that you would create num_models references to the same object and won’t create num_models different model objects. To do the latter, you would need to initialize them: [MyModel() for _ in range(num_models)]. With t…
JPKikori
I have this function, help me to convert to amp, tks so much!def step(self, source_x, source_label, target_x, target_imageS=None, target_params=None, target_lp=None, target_lpsoft=None, target_image_full=None, target_weak_params=None): source_out = self.BaseNet_DP(source_x, ssl=True) sourc...
ptrblck
The usage of the amp utilities look alright. Based on the code it seems that you explicitly want to use the float data type in some operations, so you could also use nested autocast statements and disable the casting for these operations.
szymonindy
I have tried to freeze part of my model but it does not work. Gradient computation is still enabled for each layer. Is that some sort of bug or am I doing something wrong?model = models.resnet18(pretrained=True)# To freeze the residual layers for param in model.parameters(): param.require_grad = False for param in ...
ptrblck
You are creating a new .require_grad attribute for each parameter, while you most likely want to set the .requires_grad attribute to False for the parameters (note the missing s).
aroibu1
Hi! In my network, I am trying to carry out upsampling from an encoded latent space. So far I have been using nearest upsampling, but I want to switch to transpose convolutions as this could aid in my training.The way I wish to define my upsampling operation, to keep it consistent with the rest of my code, is as follow...
ptrblck
If the output_size argument is fixed for each layer, you could create a custom module and set this argument during its initialization: class MyConvTranspose3d(nn.Module): def __init__(self, conv, output_size=None): super().__init__() self.conv = conv self.output_size = o…
aroibu1
Hi all! Recently, I started implementing checkpoint saves on my code, as it has become difficult running everything in one go. I save everything as prescribed on the PyTorch tutorials, however when I resume training, the network behaves as if the checkpoint hasn’t been loaded properly. You can see this behaviour in the...
ptrblck
load_state_dict is a method, which should get the state_dict as its input. Currently you are reassigning the state_dict to the function: self.model.load_state_dict = checkpoint['state_dict'] self.optimizer.load_state_dict = checkpoint['optimizer'] Replace these lines of code with: self.model.loa…
tree5680
i edited .view() to .reshape() but same error still occured…def accuracy(output, target, topk=(1,)): maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = corre...
ptrblck
The posted error is raised, if the tensor it not contiguous in memory and thus view will fail. You could either use .reshape instead as suggested in the error message or .contiguous().view(...) alternatively.
GeorgeQ-Q
My question isWhat are the differences between Apex distributed data-parallel with torch ddp since mixed precision training is also inside pytorch now is there any specific reason we use apex ddp in stead of torch ddp?
ptrblck
The apex implementations are deprecated, since they are now supported in PyTorch via their native implementations, so you should not use apex/DDP or apex/AMP anymore.This postexplains it in more detail.
Elton_Lobo
I am trying to create a custom class for my dataset. Can anyone figure out what is wrong in the code given below?class Map_dataset(Dataset): def __init__(self,root_dir,transforms=None): self.transforms=transforms self.root_dir=root_dir self.list_dir=os.listdir(self.root_dir) def __getite...
ptrblck
Based on the error message, the issue is in trying to iterate transforms.Compose, which is not working: for t in self.transforms: input_image=t(input_image) target_iage=t(target_image) transforms.Compose will apply the transformation in the specified order, so you can use it directly: inp…
SaadMunir
Hello everyone !I have a large dataset about a casting machine and its corresponding process parameters . So basically each row is an observation with about 200 parameters and then the corresponding class label of 0 or 1 where 0 means the part is NOT defective and 1 means the part was badly manufactured. We are trying ...
ptrblck
Based on your description I think the proper way to implement this custom sampling strategy would be in a custom sampler. By default the DataLoader would use a SequentialSampler or a RandomSampler, which you could replace with your custom class. This custom sampler could then take the targets and cr…
lm_modeler
I am gettingValueError: optimizer got an empty parameter listwhen I run this code. What am I missing? Tried usingnn.Parametersand still getting error on model parametersaandb. I just want to track and update these two scalars on this toy problem.import torch import torch.nn as nn import torch.nn.functional as F from to...
ptrblck
This error is raised by trying to call the parameter in: self.b(y-x**2)**2 What kind of operation should be performed in this line of code?
julliet
I am new to the NN and PyTorch, so some things are not obvious to me. I would really appreciate help here. I wanted to use nn.CrossEntropyLoss on a tensor of shape [3, 14, 136], where 3 is a batch_size, 14 is sequence_length and 136 is number of tokens. It is one-hotted by number_of_tokens dimension.I put this tensor i...
ptrblck
Based on thedocsthe output of the model should have the shape [batch_size, nb_classes, *], while the target should have the shape [batch_size, *], so you would need to permute the output to the shape [batch_size=3, nb_classes=nb_tokens=136, seq_len=14] (assuming 136 equals the number of classes).…
Oussama_Bouldjedri
I have a set of ID labels from 0…24 that encodes 19 classes and I want basically to have a 1 hot encoding of them: if I use :target = torch.sparse.torch.eye(19).index_select(dim=0, index=target)I get index out of range which I completely understand since some labels are 24 (but the number of total classes is 19), stran...
ptrblck
You could map the current class indices from [0, 24] to the expected range [0, 18] for 19 classes, since your use case would otherwise work with 25 classes where some might never be used.
lkp411
Hey there is there an efficient way to do a strided sum in pytorch? Particularly when the number of elements that fall under each stride is variable but specified? For example:a = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) stride = torch.tensor([3, 3, 4]) result = torch.strided_sum(a, stride) (something like this)Me...
ptrblck
You can use scatter_add_ to accumulate these values to a new tensor. Assuming you have already calculated the stride tensor, you would need to create the index tensor from it as seen here: a = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) stride = torch.tensor([3, 3, 4]) idx = torch.tensor(sum([[i…
tree5680
i made a function code that makes the zero weight fixed to zero while training by making zero weight’s grad to zero.def fix_tensor_data(model.parameters()): for t in model.parameters(): if t.grad is not None: t_copy=t.data.abs().clone() mask = t_copy.gt(0).float().to(t.grad.device) ...
ptrblck
If you are using a momentum in the optimizer and had previous valid updates for these parameters, they’ll still be updated as seen here: # no momentum x = torch.ones(1, 5, requires_grad=True) optimizer = torch.optim.SGD([x], lr=0.1, momentum=0.) # perform a valid update print('no momentum, valid u…
atharvahans1
Hello,I am new to PyTorch and I was trying to use the autograd package. I keep gettingTypeError: 'Tensor' object is not callable. I am not sure what I am doing wrong. I have attached a screenshot of the error and my code below. Can someone please help?Screen Shot 2020-11-27 at 2.13.34 PM2112×1538 506 KBdef lagrangian(q...
ptrblck
Could you check your imports and variable names, as based on the error message it seems you might have overridden the hessian method with a tensor using the same name.
twister9458
Hello all;I’ve an unbalanced dataset for a 3 classes output.I managed to have well stratified train and test sets.My question please: Using WeightedRandomSampler gives me bad results rather than without using it. (74% vs 91% accuracies)Is there any logical explanation for this ?Last question: assuming all my dataset wa...
ptrblck
You might be running into theAccuracy Paradox, which explains that the accuracy might be a misleading metric for imbalanced classification use cases. E.g. in case the majority class occurs in 91% of all cases, your model might only predict this single class to achieve the accuracy of 91%. While t…
danchu
I wanna find some torch function like this:input : a = [[1,2,3,4], [5,6,7,8]], b = [[0,0,0,0],[0,0,0,0]]output : c = [[[1,0],[2,0],[3,0],[4,0]],[[5,0],[6,0],[7,0],[8,0]]]Does this kind of function exist in torch?
ptrblck
Yes, you can use torch.stack: a = torch.tensor([[1,2,3,4], [5,6,7,8]]) b = torch.tensor([[0,0,0,0],[0,0,0,0]]) c = torch.tensor([[[1,0],[2,0],[3,0],[4,0]],[[5,0],[6,0],[7,0],[8,0]]]) print(c) > tensor([[[1, 0], [2, 0], [3, 0], [4, 0]], [[5, 0], …
Alexander_Soare
Say I have a module like:class MyModule(nn.Module): def __init__(self): super().__init__() self.cnn = CNN(params)And then I do:module = MyModule() module.cnn = CNN(some_other_params)Is the replacement registered? Will there be any nasty side effects down the line?
ptrblck
Yes, the assignment of the new module will properly register the new layer with all parameters and is the recommended way to e.g. replace the last linear layer in a fine-tuning use case (assuming the number of classes changed and you would like to retrain this layer). The parameters are also shown i…
Shawn_Zhuang
Hi,I saw this in code:coors = coors.int()and coors is a tensor, whose shape is [1515,4].I have googled the init function but found nothing.Anybody know this function?
ptrblck
Based on your code snippet it seems you are looking for the int() operator, not init(). If that’s the case: the int() operation will return a tensor transformed to the int32 data type: x = torch.randn(10) * 10 print(x) > tensor([ 2.9199, -13.7902, -0.3769, -11.2643, -2.8111, -0.7583, -2.9747,…
tanmay2592
I am trying to measure the time spent in model inference (forward() call on torch::jit::script::Module).torch::NoGradGuard no_grad; model_outputs = torch_model.forward(input_tensors);However, the timing is coming out to be really small. I found the reason is because of the default Asynchronous mode for GPU operations d...
ptrblck
I’m not sure about the TimestampCaptureCallback approach, but in any case you could add manual synchronizations via: auto stream = at::cuda::getCurrentCUDAStream(); // or at::cuda::getDefaultCUDAStream()) AT_CUDA_CHECK(cudaStreamSynchronize(stream)); to make sure your timings are correct. Alternat…
crist77
Hi! Can I have a kernel for a conv2d with some parameters trainable and some parameters not trainable?Let s say if I have 1 kernel with dim 9x9 , can I have the firs 4x9 params trainable and the last 5x9 params not trainable?
ptrblck
Yes, you could create a custom nn.Parameter for the trainable part and use torch.cat or torch.stack to create the weight tensor for the convolution. Once this is done, you could use the functional API via F.conv2d(input, weight, ...) to apply the convolution. You could use a custom nn.Module for th…
twister9458
Hello All;I have a very unbalanced dataset, which I tried to balance using the following code (Class Dataset then my code):class myDataset(Dataset): def __init__(self, csv_file, root_dir, target, length, transform=None): self.annotations = pd.read_csv(csv_file).iloc[:length,:] self.root_dir = root_d...
ptrblck
You could create the weights using the code snippet from my previous post and replace the SubsetRandomSampler with the WeightedRandomSampler using the train_idx. Since you are already using a subset via the train_idx, note that you would also only need to calculate the weights for these indices and…
Dota2Player
did anyone know how to solve this problemi have read the document of torchvision,but i couldn’t find ‘matcifar’,help plsmy pytorch vision is 0.3.1,torchvision is 0.2.0
ptrblck
I assume you’ve used a repository from the authors? If so, did you see, if the authors have forked torchvision and have added this particular dataset?
Jason1995
image1400×829 22.5 KBI get the message as below when I’m training WideResNet with CIFAR-10.RuntimeError: Function 'LogSoftmaxBackward' returned nan values in its 0th output.So I wonder what’s the problem and I found the input is having nan values using the codes below.for epoch in range(epochs): for i, (X, y) in en...
ptrblck
Thanks for the update. Could you execute these runs and see, if the behavior changes, as a sync wouldn’t be strictly necessary, but would help us to isolate is an internal method is broken: add synchronizations in the train_data loop before and after each line of code set non_blocking=False reru…
a_d
Hello all,I know this particular error as In the heading has been encountered and discussed at length in the previous discussions on this forum, but I am simply not able to find the reason as to why I am encountering it, I get the error -Device side assert triggeredwhen I am printing my loss. I am training a segmentat...
ptrblck
Most likely your targets contain invalid values outside of the expected range [0, nb_classes-1]. I’m not sure, if you are using an older PyTorch version, as the stacktrace with blocking launches should show the indexing errors. In case you are already using the latest release, you could use TORCH_…
cbd
In below code i have to use “unsqueeze” 2 times for 3d conversion. Is there anyway to convert 1d to 3d using “unsqueeze” single time.from torchvision import transforms a=torch.ones([5],requires_grad=True) * - 0.5 a=a.unsqueeze_(0) a=a.unsqueeze_(0) print(a.shape)
ptrblck
You could index the tensor with None to add additional dimensions: x = torch.randn(10) y = x[None, :, None, None] print(y.shape) > torch.Size([1, 10, 1, 1])
m3tobom_M
I am trying to implement the below transforms myself but custom outputs and torch outputs are different. A portion of the output is below (some pixel values from different channels). What am I doing wrong?Note: I do not need tensor as output.Custom transforms@njit() def normalize_cv2(image, mean, std): for d in ra...
ptrblck
I don’t know how you are comparing these two outputs, but make sure to create a clone of the input numpy array, since you are manipulating it inplace. Also, note that ToTensor() will normalize numpy arrays, if they are passed in the uint8 dtype, not if they are using the float32 type. Additionally…
Misterion777
Hey everyone. I have installed CUDA 11 + cudnn 8.2 globally on my machine, but I need to use exact Pytorch=1.4.0 for some repo to run, so I created an environment and installed:conda install pytorch==1.4.0 torchvision==0.5.0 cudatoolkit=10.1 -c pytorchWhen running some code in this environment I have some weird cudnn e...
ptrblck
The global cudnn and CUDA installations won’t be used, if you install the binaries. However, since you are using an Ampere GPU, you would need to use CUDA>=11.0 with cudnn>=8, which aren’t used in the PyTorch 1.4.0 binaries.
Arturas_Druteika
Maybe I don’t understand something regarding depthwise seperable convolutions but if you set the argumentgroups=input channelsinnn.Conv2D, as a result you get only one kernel per filter, no matter many input channels there are. To my understanding normal convolutional operation has as many unique kernels per filter as ...
ptrblck
Yes, the first three filters would be used for the first input channel, then the second 3 filters for the second input channel, etc. You can always manually verify it: conv_1 = nn.Conv2d(3, 9, 3, 1, 1, groups=3, bias=False) x = torch.randn(1, 3, 4, 4) out_ref = conv_1(x) x0, x1, x2 = x.split(1, d…
vanduong0504
Hello everyone,How to reset the parameters of layer4 in resnet18, using the Module.apply? Here my code but it doesn’t work.Thank you.def reset_weights(m): for name, layer in m.named_children(): if name=='layer4' and hasattr(layer, 'reset_parameters'): print(f'Reset trainable parameters of l...
ptrblck
layer4 is an nn.Sequential module, which doesn’t have the reset_parameters method, so your conditions won’t be met. You could iterate all modules of layer4 and check for this attribute: def reset_weights(m): for name, layer in m.named_children(): if name=='layer4': print(na…
hankdikeman
Hello,I am new to GPU training, especially training in parallel on multiple GPU’s. I sometimes get lost moving data around devices and figuring out which model is where. Right now I am working with 4 V100 GPUs and training using parallel GPU training.My issue currently is using an autoencoder for inference (i.e. genera...
ptrblck
The to() operation is not an inplace operation on tensors, so you would need to reassign normeddata: normeddata = normeddata.to(DEVICE)
alexlin51
Hi Pytorch Discussion, found a lot of help here on previous projects so wanted to say thanks first!I am currently playing around with a Generative model that should learn to create Album Covers from a dataset I found on Kaggle.Here is my generator:class Generator(nn.Module): def __init__(self): super(Generator, s...
ptrblck
You are detaching the loss tensors by wrapping them into the deprecated Variable in: D_loss = Variable((D_fake_loss + D_real_loss)/2, requires_grad=True) so you should remove the Variable usage. (Note that the same issue would be caused, if you rewrap the loss in a new tensor.) Also, if you are …
jerly-hjzhou
I change the first parameter of resnet-18 mannully and use the changed model to infer. And I got this warning information.UserWarning: The .grad attribute of a Tensor that is not a leaf Tensor is being accessed. Its .grad attribute won't be populated during autograd.backward(). If you indeed want the gradient for a non...
ptrblck
I’m not sure where this warning is raised, since I cannot see any usage of the .grad attribute. However, your current code should fail with: RuntimeError: a view of a leaf Variable that requires grad is being used in an in-place operation. and you would need to manipulate the parameter in a torch…
FaultyBagnose
The Pytorch doc says:“All pre-trained models expect input images normalized in the same way,” … “The images have to be loaded in to a range of[0, 1]and then normalized usingmean = [0.485, 0.456, 0.406]andstd = [0.229, 0.224, 0.225].”Mathematically, the normalization to a given mean and std should give the same result r...
ptrblck
That’s correct and you could skip the [0, 1] normalization and use the mean and std stats for the raw input values in [0, 255]. However, since ToTensor() is often used in the transformations to transform a PIL.Image in [0, 255] to a tensor in [0, 1], I believe this workflow grew organically.
turian
I am currently organizing a NeuroIPS competition, in which participants might be submitting pytorch models to our evaluation server for the leaderboard.Is there a secure way of serializing/loading untrusted pytorch models?Are there alternatively to pickle, which can be insecure? Is there a pytorch model format we can i...
ptrblck
Additionally to what@albanDsaid, I think you could try to secure your environment by e.g. running submissions in a container (singularity or docker) without any permissions, which could affect your bare metal systems. Of course a system is never 100% secure and in the worst case users might try to…
jerly-hjzhou
I’m using resnet-18 to infer test set. When I use one GPU, the time is only 10s. But when I want to use multiple GPUs and only add this codeif torch.cuda.device_count() > 1: print("Let's use", torch.cuda.device_count(), "GPUs!") model = torch.nn.DataParallel(model)The result look like thiswhich cost 24s.My whole co...
ptrblck
nn.DataParallel will scatter and gather the parameters, gradients, etc. between the devices as explained inthis blog postand is thus adding some overhead. However, it should not slow down the execution assuming you’ve scaled up the batch size. We generally recommend to use DistributedDataParallel …
Marcus_Brown
Hello,from the documentation on 3d convolution,How to understand the D ? in (N, C, D, H, W)?let’s say for example I have five video frames and I stack the frames along the channel dimension giving me :a (1, 15, H, W) tensor assuming RGB frames. How do I reshape this tensor to (N, C, D, H, W)
ptrblck
The D dimension should define the “depth” of a volume for 3D inputs or parameters. While 2-dimensional data defines spatial dimensions as height and width, 3-dimensional data uses depth, height, and width.
Parkz
This is the code I’m trying to run:trained_model = model trained_model.load_state_dict(torch.load('net.pth')) dummy_input = Variable(torch.randn(1, 1, 28, 28)) torch.onnx.export(trained_model, dummy_input, "net.onnx")This is the error I am getting:RuntimeError Traceback (most recent call l...
ptrblck
The error points to a type mismatch for the nn.Embedding module, which expects a LongTensor as the input, while you are apparently using a FloatTensor, so you would need to change the dtype of the input. A quick solution would be to transform it via x = x.long(). Also note, that Variables are depr…
Yun_Lee
The problem is thateventhough I specified certain gpus that can be shown with os.environ[“CUDA_VISIBLE_DEVICES”],the program keeps usingonly firstgpu.(But other program works fine and other specified gpus are allocated well.because of that, I think it is not nvidia or system problem.nvidia-smi shows all gpus well and t...
ptrblck
If I understand you correctly, setting CUDA_VISIBLE_DEVICES in the terminal works correctly, but doesn’t work if you try to set it inside the script via os.environ. This is a commonly met issue, if you are not making sure that the env var is set before importing any CUDA related libraries, which i…
Ive_Xu
I am trying to convert a keras model to pytorch for human activity recognition. The keras model could achieve up to 98% accuracy, while Pytorch model could achieve only ~60% accuracy. I couldn’t figure out the problem, first I was thinking of the padding=‘same’ of keras, but I have already adjusted the padding of pytor...
ptrblck
I guess the issue could be created by the nn.LSTM layer in the default setup, which would expect an input in the shape [seq_len, batch_size, nb_features] and could thus process the inputs in a wrong way. If you want to pass inputs with the batch dimension in dim0, you could create the modules with b…
Anonimouz
We are currently implementing a WaveNet like structure to solve the problem of MNIST prediction, ie. given some part of the image, to reconstruct the rest. We’ve trained on the whole MNIST data set for starters, however we run into some problems regarding our model output estimate, namely that it is all gray.From what ...
ptrblck
F.binary_cross_entropy is the functional API version of nn.BCELoss, so your model would need to use torch.sigmoid on its outputs. Also, I assume that you are working on a binary or multi-label classification. If so, I would recommend to remove the sigmoid and use F.binary_cross_entropy_with_logits(…
felixdittrich92
Hi, i switched from TF/Keras to PyTorch/Lightning but got this error can anyone help me with this ?Is there any recommended way to debug some errors in pytorch ?data example:Die Oangegebenen OWerte Osetzen Ovoraus O, Odass Osich OIhre OVersicherung Oseit Odem O1 B-DATE. I-DATE10 I-DATE. I-DATE2019 I-DATEimport pandas ...
ptrblck
Yes, the error is raised in the default collate_fn, as it’s unable to stack the tensors returned by __getitem__ into a batch tensor. I’m unsure which tensor is raising the error, but you could check the shape of each one in the __getitem__ before returning them. In case you are working with variabl…
Joao_de_Oliveira
Hi guys and girls,Newbie to pytorch, more experienced with Keras, GBM, … but curious about performance and power of pytorch, so decided to dive into PyTorch.I picked ashared code for a DAE + MLPfromKaggle competition (Tab-Apr), and reapplied it (somehow successfully) to April’s competition.Went in dept in the code to u...
ptrblck
Since some of the parameters are already containing NaNs, I guess the last update might have created them and you could thus check the gradients for weight_v from the previous iteration(s). It also seems that weight_norm is used, but I don’t know if it’s more sensible to gradient explosions etc.
kranti
I defined a linear layer after the network and this layer is neither part of the network nor the weights are updated during training. It is defined just before the start of the first epoch as mentioned below.mod1_encoder = linear([1024, 256, 256]) mod2_encoder = linear([1024, 512, 256]) mod1_classifier = linear([256, 4...
ptrblck
If you create a new layer, the parameters will be initialized, which will most likely call into a random initialization method and thus the pseudo-random number generator. If you reset the seed after the initialization of tmp, you might get the same values. Note that some methods are not determini…
jungminc88
I am working on an NLP task and I’m trying to train my model to correctly predict the relevance of two documents. Input is a pair of document representations and the model applies linear transformation to both, computes the cosine similarity, applies sigmoid. It turns out, the loss doesn’t change at all during the trai...
ptrblck
Yes, you are detaching the loss tensor from the computation graph by recreating a new tensor, so you would have to create the loss tensor by using torch.cat, torch.stack, torch.where etc. which are all differentiable.
ADONAI_TZEVAOT
I have a matrix A which is 3d and I want to convert so that it is equal to B which is a 2d matrix> A = torch.tensor( [ [[1,1,1,1,1], > [2,2,2,2,2], > [3,3,3,3,3], > [4,4,4,4,4], > [ 5,5,5,5,5]], > > [[6,6,6,6,6] > [7,7,7,7,7], > [8,8,8,8,8], > [9,9...
ptrblck
Directly reshaping A will unfortunately not work, as it would result in: print(A.view(B.size())) > tensor([[ 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3], [ 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6], [ 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9,…
Mohamad_Bairakdar
I expected the following code to haveTruefor all entries ofabut it doesn’t. Why is that? (I’m trying to understand the difference between an input shape N,C,L and N,L for batch norm 1D)self.bn1 = torch.nn.BatchNorm1d(hidden_channels) def bn(self, x): batch_size, num_nodes, num_channels = x.size() y = ...
ptrblck
The last reshape operation will interleave the output values and you would need to permute y before calling reshape: hidden_channels = 4 bn1 = torch.nn.BatchNorm1d(hidden_channels) x = torch.randn(2, 3, 4) batch_size, num_nodes, num_channels = x.size() y = x.clone() x = x.view(-1, num_channels) x…
jerly-hjzhou
I think the more num_works, the time cost for inference should be less. But the result from my code is in opposite. I use trained resnet-18 to inference the test set. When the num_work=0, the time cost is around 12s, but when num_work =6, the time is around 25s.Below is my code.import torch from torchvision import data...
ptrblck
Each worker could create an (initial) overhead by copying the dataset to each process and could thus slow down the first iteration. Also, depending on your setup, you would have to find a sweet spot of for the number of workers, as increasing them won’t necessarily always result in a speedup as desc…
Rajat_Singh1
colab.research.google.comGoogle ColaboratoryCode snippet–SpecifyMAX_LENMAX_LEN = 6Print sentence 0 and its encoded token idstoken_ids = list(preprocessing_for_bert([X[0]])[0].squeeze().numpy())print('Original: ', X[0])print('Token IDs: ', token_ids)Run functionpreprocessing_for_berton the train set and the validation s...
ptrblck
As the error points out, you cannot directly transform a GPU tensor to a numpy array and would need to transfer it to the CPU first via the tensor.cpu() operation before calling .numpy().
jerly-hjzhou
I’m using resnet-18 to infer test set. When I set the batch_size=10, I got average loss =0.96381098 as in this graphimage931×822 77.2 KB.But when I set batch_size=100, I got average loss=0.96381102 as you can see in this graphimage921×618 60.1 KBIt’s very strange. My code is below.import torch from torchvision import d...
ptrblck
The difference is 0.96381102 - 0.96381098 = 3.9999999978945766e-08, which is most likely caused by the limited floating point precision using float32. Internally the order of the operations might not be the same or different algorithms might be used depending on the batch size and thus workload.
newtopytorch
I currently have the following data:f_map, inputs, s_bias = ml_dataset.dataset_for_s_bias()where f_map is a tensor of matrices, inputs is a tensor of floats, and s_bias is a tensor of floats. The first two tensors, f_map and inputs, are the inputs to my ML regression algorithm, and s_bias is the expected output. The re...
ptrblck
The optimizer would need the references to all parameters it should update. In the usual case you would either create two separate optimizers (one for each model) or pass the parameters of both models to a single optimizer. In your current setup you would also train mlp_model and cnn_model would be…
Shahrullohon
I am trying to train multioutput image classification (age and gender labels) but stuck in this problem. Here is my model. I have seen other results so far, unfortunately could not solve it.class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv_layer = nn.Seque...
ptrblck
Thanks for the update. The error is caused, since you are explicitly casting the targets to torch.LongTensor, which is a CPU type. Instead of using .type(torch.LongTensor), call label1.squeeze().long() to keep the tensor on the GPU.
andrea_bragagnolo
HI, I tried looking in the documentation but I couldn’t find what I’m looking for.My question is: how are intermediate gradient collected by the backward hooks affected by amp?I understand that during training we should useGradScaleron the loss asGradScaler.scale(loss).backward(), but what about the gradient collected ...
ptrblck
Yes, the next section of the tutorials shows how tounscale gradients manuallyusing inv_scale = 1./scaler.get_scale(), which you could also use in your hooks.
Vegeballoon
Hello guys, I am trying to build a LeNet5 network to train a classifier for MNIST dataset, but the network seems not to be learning. I have printed the gradients and they are not always zero, but very small. The loss curve as well as the accuracy curve is almost like a flat line when learning rate is small (1e-1) and b...
ptrblck
You might want to play around with some hyperparameters and e.g. lower the learning rate to ~1e-3, as I cannot see any obvious errors in your code.
PannenetsF
As I run some code like these which do the same thing $-\sum ||x-w||$:def via_unsqueeze(W_col, X_col): output = -(W_col.unsqueeze(2) - X_col.unsqueeze(0)).abs().sum(1) return outputanddef via_cdist(W, X): output = -torch.cdist(W, X, 1) return outputSometimes, there will be a difference up to 2e-6 when t...
ptrblck
The difference is most likely caused by the limited floating point precision and a different order of operations. You could use torch.float64 as the data type in case you need to increase the precision, but note that this data type would cause a performance hit on GPUs. A simple example is given he…
blurry_mood
Hi,I want to customize the kernel used in the conv2d layer in a way that shares parameters.In short, I want the kernel to be symmetric with respect to the row in the middle and to the column in the middle.If we take the example of 3 by 3 kernel. I want the third column to have the same parameters as the first one, and ...
ptrblck
You could initialize the nn.Parameters in the model’s __init__ method, create the desired filter in the forward (e.g. via torch.cat and torch.stack) and apply it via the functional API (F.conv2d in your case).
nicozhou
I see a lot of examples using model.featurestorchvision.models.vgg16(pretrained=pretrained).featuresso, can we usemodel.encoderormodel.decodertoo? or it depends on the architecture of the model? where can we found the documentation of them?
ptrblck
It depends on the architecture of the model and you can check the internal modules in the model definition. E.g. torchvision.models are implementedhere.
AerysS
I have atorch.Tensorof shape(2, 2, 2)(can be bigger), where the values are normalized within range[0, 1].Now I am given a positive integerK, which tells me that I need to create a mask where for each 2D tensor inside the batch, values are 1 if it is larger than1/kof all the values, and 0 elsewhere. The return mask also...
ptrblck
You could use broadcasting to get the desired result: x = torch.tensor([[[1., 3.], [2., 4.]], [[5., 7.], [9., 8.]]]) quantile = torch.tensor([torch.quantile(a, 1/2) for a in x]) res = torch.where(x > quantile[:, None, None], 1, 0) print(res)…
Parkz
I’m new to data science and need help troubleshooting this error. This is the code:alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789-._' def sentence_to_id(data): #creates a dict that maps to every char of alphabet an unique int based on position char_to_int = dict((c,i) for i,c in enumerate(alphabet)) encod...
ptrblck
temp_label seems to have the index value 58, while you are initializing label with 57 zeros. This would allow you to index label with values in [0, 56] and 58 will raise the out of bounds error.
isaacg
I have been using pytorch for the last year after using tensorflow for several years and theano before that. I very much enjoy the functional interface of tensorflow a lot. However, the interface had several bugs which gave me troubles so I switched to pytorch. For example, adding extra loss terms to the optimization...
ptrblck
I think a lot of boilerplate code could be reduced by using a higher-level API on top of PyTorch such as Ignite, Catalyst, or PyTorch Lightning. These libraries provide a different level of abstraction and might still fit your use case. If I’m not mistaken, you have still the full control with you…
Parkz
I’m not sure how to resolve this error. I am trying to build a classifier for 36 different labels that are numbered from 0 to 35. Here is some of the code:#one-hot encode vocabulary alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789-._' def sentence_to_id(data): #creates a dict that maps to every char of alphabet an ...
ptrblck
nn.BCEWithLogitsLoss expects the model output and target to have the same shape. Based on the new error message it seems that your model output has a shape of [35], while you are using a single target value only, which won’t work. The expected shapes for a mulit-label classification would be [batc…
jS5t3r
I trained a model like this:net = resnet50(num_classes=settings.NUM_CLASSES) net = nn.parallel.DataParallel(net, device_ids=list(range(torch.cuda.device_count()))) net = net.cuda() ... torch.save(net.state_dict(), weights_path)I would like to load the model:model = get_network(args) model.load_state_dict(torch.load(set...
ptrblck
You are saving the nn.DataParallel state_dict, which will include the .module keys as describedhere. You could either wrap the model first into nn.DataParallel and load the state_dict afterwards or store the net.module.state_dict() instead.