user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
thyr
I have a step in my model which is very expensive as it does operation over the entire vocabulary. Let’s say the step is as followsoutput =self.vocab_process(input)input is of dimension bsz x seq_len x doutput is of dimension bsz x seq_len x kI found that batch size of 128 works well for this step but anything more tha...
ptrblck
If intermediate tensors in vocab_process need the device memory and will thus raise the OOM issue, your loop approach could work (assuming that vocab_process returns the right output for sub-tensors). Since Python uses function scoping you wouldn’t have to delete the intermediate tensors, as they w…
soulslicer
I have a tensor of size [B, 64, 256, 384]. I want to stretch it softly along the channel axis so it becomes [B, 256, 256, 384]. I tried doing this but i get an errordpv_refined_predicted = F.interpolate(dpv_refined_predicted, size=[256,256,384], mode='linear')dpv_refined_predicted = F.upsample(dpv_refined_predicted, s...
ptrblck
F.intepolate would need to use mode='bilinear' for 4D inputs and could only interpolate the spatial dimensions. To interpolate in the channel dimension, you could permute the input and output as shown here: B = 2 x = torch.randn([B, 64, 256, 384]) x = x.permute(0, 2, 1, 3) out = F.interpolate(x, …
Jordan_Howell
Hi. It seems to me that my data loader is pulling the same image. It’s transforming it differently but it’s still the same image.image805×350 86.8 KBI would expect it to pull 10 different images with each batch of 10.Below is the data loader:class Inspection_Dataset(Dataset): """ df: Dataframe contain...
ptrblck
The Dataset.__getitem__ will get an index as the argument from the DataLoader to create a batch. These indices will be in the range [0, len(dataset)-1], so you would only have to make sure to load each corresponding sample using the passed index. I would still recommend to check the path and make…
Rahul_pillai
Every time i train ,my training loss just spikes during the 2nd epoch and drops hard,i want to know why is that, is it a bad thing?
ptrblck
Could have various reasons, such as a high learning rate, which could cause some divergence at the beginning of the epoch, and later on let your model converge again (as your validation loss is low). You could check the predictions during training and check the loss for each batch to isolate it fur…
pooya_khandel
I know that settingnum_workers > 0inDataloadermay speed training and data access. According todocumentationnum_workersis abouthow many subprocesses to use for data loading.0means that the data will be loaded in the main process.Does the loading refer to loading data into the RAM? For instance, suppose that there is eno...
ptrblck
If your data is already loaded, you might get an advantage of using multiple workers for the preprocessing of each sample. If you don’t need to process the samples, but would simply slice the data, you won’t see a huge performance benefit. Just in case, you could nevertheless profile the code and ve…
CS.Enthu
Hello everyone.I have a 3D volume of medical data storred as numpy array of size [284,143,143]. Now I want to slice the images axially and save them in tiff format. How can I acheive that. Can someone please give an example.Thanks
ptrblck
You could iterate the tensor, index each sample, transform it to PIL.Image and store it. Here is a small code snippet: import torchvision.transforms.functional as TF x = torch.randn(5, 24, 24) for idx in range(x.size(0)): tmp = x[idx] img = TF.to_pil_image(tmp) img.save('img{}.tiff'.…
xolotl18
Hi everyone,I seem to have problems making this loss function work.I feed it the output of the network and the labels from the dataset and after the first epoch it says that the loss is 0, but the accuracy is still low.Do you know where the problem should be?
ptrblck
I think nn.MultiMarginLoss would be the suitable criterion: Creates a criterion that optimizes a multi-class classification hinge loss (margin-based loss) between input x (a 2D mini-batch Tensor) and output y Based on the shape information it should also work for your current output and target s…
Andreas_Georgiou
I am trying to compute pairwise equality of all elements of 2 1D tensors. Then I want to know how many times each element of y occurs in x. Right now I am using the following:x = x.view(-1,1) y = y.view(1,-1) (x==y).sum(dim=0)Now this works fine but the intermediate x==y is quite large and it will not fit into the GPU ...
ptrblck
You could trade memory for compute by using loops and perform the comparison without the broadcasting for the sub-elements (including the sum). I don’t know, of there would be another better way “between” these approaches.
Haider_Ali_Shuvo
I have a batch of output mask of semantic segmentation <N,H,W> and my predicted mask of <N,H,W> , There are 22 categories. . How can i calculate mean IOU metric / Dice Coeff effeciently ?
ptrblck
For IOU take a look atthis postfor dice atthis one.
Barak_Beilin
Is this the correct way to specify custom manipulation of the weights of a convolution layer?class MaskedConv3d(nn.Module): def __init__(self, channels, filter_mask): super().__init__() self.kernel_size = tuple(filter_mask.shape) self.filter_mask = nn.Parameter(filter_mask) # tensor ...
ptrblck
No, you shouldn’t use the .data attribute, as it might yield silent errors and could break your code in various ways. The error message points to a mismatch between a tensor and the expected nn.Parameter. Try to wrap the new weight into a parameter via: with torch.no_grad(): self.conv.weight …
Jeremy_Rutman
I’d like to randomly initialize word embeddings - can I do the following:TEXT.build_vocab(train_data) vocab_size = len(TEXT.vocab) embedding_vectors = torch.FloatTensor(np.random.rand(vocab_size,embedding_length)) word_embeddings = nn.Embedding(vocab_size, embedding_length) word_embeddings.weight = nn...
ptrblck
This code snippet would assign embedding vectors to the nn.Embedding layer. Note that nn.Embedding will already randomly initialize the weight parameter, but you can of course reassign it. You could use torch.from_numpy(np.random.rand(...)).float() to avoid a copy, but your code should also work.
madeye_moody
Creating a basic CNN model for binary image classification. Tried evaluating my model before training but receive the runtime error for dtypes mismatch as the BCE loss function uses it’s weights in float form and it seems as though my inputs are Tensors containing Long data. I don’t believe I ever converted my data int...
ptrblck
The to() operation is not an inplace operation for tensors, so you would need to reassign the result: targets = targets.to(torch.float32) ...
Haider_Ali_Shuvo
I set up a really small toy Full Connected Network for image segmentation on Pascal VOC . The architecture looks like following ==> Conv - Conv- Conv- Transpose conv-Transpose conv-Transpose conv .I set up a per pixel cross Entropy Loss and trained it with Adam . But i am not able to lower down loss . Can anyone tell w...
ptrblck
The model itself seems to be correct, as I can perfectly overfit a random input and target batch of 10 samples: class Model(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3,64,3,2,1) self.conv2 = nn.Conv2d(64,128,3,2,1) self.conv3 = nn.…
_joker
I would like to have views on; what if I am training a ResNet model on the reduced dimension from an autoencoder (i.e., the output from the encoder’s bottleneck layer directly to the ResNet classifier)?Thank you everyone in advance.
ptrblck
Your input might currently be too small for a resnet and you might get an error from a conv layer, explaining that the kernel size cannot be bigger than the input shape. You could try to reshape it, such that the input channels are set to 1 and the spatial sizes are increased by a factor of 16 via: …
skerlet_flandorle
I’m doing reinforcement learningBatch size cannot be greater than 1I’m trying a batch size of 32I can’t find anything strange when I look at RossI’m in troubletensor([[1.3092e-03, 2.1749e-03, 2.6177e-06, 2.2517e-03, 2.1730e-03, 4.7358e-05,1.3836e-03, 8.5324e-04, 1.0955e-03, 1.9888e-03, 1.3575e-03, 1.6514e-05,2.5816e-04...
ptrblck
Based on the error message it seems that loss is not a scalar value but a tensor with multiple values. You could either reduce it to a scalar (e.g. with torch.mean, if that would fir your use case) or you could pass the gradients to backward e.g. via loss.backward(torch.ones_like(loss)).
bfeeny
I have seen code that has like this:data_predict.extend(train_predict.cpu().data.numpy().tolist())where data_predict is a List, and train_predict is a Tensor. My understanding is that .data is used to extract the Tensor from a Variable, and that if the object is already a Tensor, there is no purpose for it in this man...
ptrblck
Variables are deprecated since PyTorch 0.4 and you can use tensors now. Also, you should not access the .data attribute directly, as it might yield unwanted side effects. So you are correct and should remove the .data usage.
bfeeny
I have ran a few models using DataParallel, just by simply passing the model to nn.DataParallel() and I have had a range of strange things that happen sometimes. What I see commonly ,is my graphs (matplotlib, etc) will look different, like WAY different, which makes me think there is something being computed different...
ptrblck
The training might differ generally, as the gradients will be reduced from all devices to the default device, which would be equivalent to training with a bigger batch size. Also, if you are using batchnorm layers, their running estimates won’t be synchronized in nn.DataParallel, which might also m…
dfalbel
It’s totally a dum question, sorry!,But I couldn’t find where the indexing code is defined for the Torch tensor.Could someone point me to that?
ptrblck
The CPU indexing should be foundhere, which would call intoget_item.
chinmay5
I am not sure if this has been answered before, but the libraries of FasterRCNN performs the non max suppression using CUDA kernel. I was hoping if there is a way to code it using pure PyTorch and no CUDA kernels. I can not use the ones from torchvision since I am going to work on 3d boxes while the ones from vision li...
ptrblck
While a custom CUDA kernel could potentially yield a speedup for the operations, you could start with a pure PyTorch implementation and could thus also use the GPU. The numpy methods should also be available in PyTorch and you could just rewrite the code. If you see a bottleneck in this translatio…
budfox3
I’m implementing the following architecture:grafik1120×539 43.9 KBwith loss:Both the State and Moment RNN get the same input at time t and feed their hidden states to some Feed Forward Networks along with additional inputs (same for both FFN). Their output then is combined in a custom Loss function.The whole network is...
ptrblck
Yes, that is correct. You would get an error, if a method is not differentiable. As a quick test, you could call the backward() method and check all parameters for valid gradients via: for name, param in model.named_parameters(): print(name, param.grad) If any parameter returns a None gradien…
Aiman_Mutasem-bellh
Dear friendsI have a tensor with the dimensions of x = torch.Size([128, 99, 8, 31]).I need to multiply the second position ‘channels’ with itself to get x = torch.Size([128, (99 * 99 ), 8, 31]) = torch.Size([128, 9801, 8, 31]).Is this logically accepted, and how to do it?AlsoI have a tensor with the dimnsions of y ...
ptrblck
As@tomexplained, there is not a single correct answer and it depends on what you are trying to achieve. E.g. the second example would need a reduction (reduce the shape of 99 to 1), which can be accomplished using torch.mean, torch.sum, etc. or simply by indexing. So the more interesting questio…
gamebo5000
I am completely new to Pytorch and I created my first model. I made a similar model in keras and use this code to test it on data it never seen before:> from keras.models import load_model > import numpy as np > from keras.preprocessing import image > import time > import sys > import PIL > > start_time =time.time(...
ptrblck
It seems torch.load(‘C:/Users/deonh/Pictures/Summer Work/xrays/PythonApplication1/scans’) returns the state_dict of the model, not the model instance itself. You would have to create the model instance before and load the state_dict afterwards. Here is a small code snippet: model = MyModel() # …
JonathanHampton
I am currently implementing this paper (https://arxiv.org/abs/1710.02410) in PyTorch and I have ran into an issue training the model.The input data consists of an image, a measurement scalar, and a control scalar. The image gets passed to a convolutional module and the measurement scalar gets passed through a linear mo...
ptrblck
You could try to add CUDA streams as describedhere, but would have to take care of the synchronizations to avoid race conditions. I would recommend to try it out with a “similar” but simple model and check, if you would get any performance gains at all.
Antonio_Ossa
Hi eveyone,I’m working with a customDatasetandBatchSampler. Due to the nature of my data, I have to fetch batches of different sizes, that’s why I’m using aCustomBatchSampler. Because of this,DataLoaders try to fetch items from myCustomDatasetone item at each time.As you can seehere, if I provide abatch_samplerto aData...
ptrblck
I think the BatchSampler will make sure to pass all batch indices to your Dataset's __getitem__ method as seen in this example: class MyDataset(Dataset): def __init__(self): self.data = torch.arange(100).view(100, 1).float() def __getitem__(self, index): print(index…
navid_mahmoudian
Hello,I have two large tensors A and B, both have type LongTensor and dimension 1. Both tensors are the results of torch.unique, so they have unique elements, and B is a subset of A (all elements of B are available in A). Is there any efficient way to find indices of tensor B elements in tensor A?
ptrblck
If the tensors are not large or if you have enough memory, you could probably use this broadcasting approach: a = torch.arange(10) b = torch.arange(2, 7)[torch.randperm(5)] print((a.unsqueeze(1) == b).nonzero()) > tensor([[2, 1], [3, 3], [4, 4], [5, 0], [6, 2]]) Alt…
cijerezg
I am doing regression on an image, I have a fully CNN (no fully connected layers) and Adam optimizer. For some reason unknown to me when I use batch size 1, my result is much better (In testing is almost 10 times better, in training more than 10 times) in training and testing as oposed to using higher batch sizes (64,1...
ptrblck
The batch size is independent from the data loading and is usually chosen as what works well for your model and training procedure (too small or too large might degrade the final accuracy) which GPUs you are using and what fits into your device memory. Generally you can increase the device utiliza…
JIALI_MA
I know that AdaptiveAvgPool2d is able to give the outputs of any defined size, but I don’t know what is the size of filter and stride it indeed use during calculation.For example: if the input size is (14, 14), and the output size is (3, 3). What is the corresponding filter parameter? Suppose padding is 0, it seems the...
ptrblck
Based onthis implementation, the input of 14x14 and output of 3x3 would create the first start and end index as: # First iteration istartH = floor((0*14)/3) = 0 iendH = ceil((1*14)/3) = 5 # Second iteration istartH = floor((1*14)/3) = 4 iendH = ceil((2*14)/3) = 10 So it seems that the window siz…
Rahul_pillai
Whenever i tried to save the entire model the warning shows, it saves without any errors.checkpoint = {'model': ResNet9(), 'state_dict': model.state_dict()} torch.save(checkpoint, 'model.pth')But when i try loading it , it gives me this error.--------------------------------------------------------------------------- A...
ptrblck
You could either import the model from another script via: from other_file import ResNet9 model = ResNet9() or define the model in the same script: def ResNet9(nn.Module): def __init__(self): ... model = ResNet9()
oasjd7
Hi, all.As far as I know, 1st parameter innn.KLDivLoss()need to beF.log_softmax().What about the 2nd parameter?(In my case, there is no softmax in classifier.)class Classifier(nn.Module): def __init__(self, channel, classes=10): super(Classifier, self).__init__() self.fc = nn.Linear(channel, classes...
ptrblck
Based on thedocs, the second argument should be passed as probabilities: As withNLLLoss, the input given is expected to contain log-probabilities and is not restricted to a 2D Tensor. The targets are given as probabilities (i.e. without taking the logarithm).
alexobrads
Hi Team,I am new to Pytorch so this might be a silly question but hopefully someone can help, I have tried my best over the past few days to debug/educate myself more to try and resolve my problem but have been unable to.Set up:I am building a variational auto encoderData is just y values of some graph that has multipl...
ptrblck
I would try to normalize the complete dataset to values in the range [0, 1] for the input and target. You might standardize the input e.g. in your forward method, but I’m not sure, if this would help or if it could even be harmful. If you pass a target outside of [0, 1], your loss might get negati…
Tank
Creating a part of speech LSTM. Not sure how to shape the data if I am batching sentences of similar length.X.shape = (100, 60, 4), [batch, length of sentence, features per word]output.shape = (100, 60, 10) [batch, length of sentences, type of word (10 potential types)]y.shape = (100, 60)The error I get: Expected targe...
ptrblck
What is your number of classes and what do the dimensions of the output represent? Are you working on a multi-class classification, where each temp. step would correspond to a single class? If so, nn.CrossEntropyLoss expects the model output to have the shape [batch_size, nb_classes, seq_len] and …
fgauthier
Hi, I am new to Pytorch and I was wondering if there is a way to convert a .json file in a numpy array. I want to do this because I want to convert my .json in a mask.Right now I have this
ptrblck
Depending how the data is stored in the json object, you might be able to directly create a numpy array. Your current code doesn’t seem to show the json file. This question doesn’t seem to be PyTorch-specific, so you might get a better answer on e.g. StackOverflow.
PavelCz
Hello all,I have noticed some to me unexpected behaviour when usingConcatDataset. I managed to reproduce it with the minimal example provided below.Whenshuffle=Trueis removed the script runs fine without any problems. Furthermore, the prints show that the sizes of all the elements in the concatenated dataset are the sa...
ptrblck
It seems thatthis line of codeis causing the error, as the target will be transformed to an int. As a workaround you could pass a target_transform and transform the target back to a tensor via: mnist = torchvision.datasets.MNIST( root=DATASET_DIR, train=True, download=True, transform=transfo…
Jordan_Howell
Hello,General question:What do I look for if a model that is predicting a test set stops at the same row every time?Nothing looks wrong to me. No data is missing. The image is there that’s supposed to be pulling. I tried removing that row, the same number index (new observation since the old was removed) is still get...
ptrblck
What is the difference between the run in the terminal and your custom dataset? Apparently self.image_frame.loc[idx, 'location'] returns a str for the current idx. I would recommend to check the image_frame in an IDE and make sure the location column contains the expected values, which can be prop…
mflova
Hi!I have been studying Machine Learning for such a long time and I decided to start with Deep Learning models. I am trying to implement a regression problem (2 targets) from an BW processed image dataset that I have created.Since I am using the ResNet architecture, I have tried to make some changes to the model, but I...
ptrblck
I assume multi-target refers to a multi-class classification, i.e. each sample corresponds to one target only. If that’s the case, you could create the last linear layer with out_features=nb_classes, such that each sample will yield the logits for all classes. For the criterion you could use nn.Cr…
springtostring
I am trying to build Logistic matrix factorization.When I train my model, I found that my model is empty.I am unfamiliar to PyTorch and I don’t know what causes the error.It really confuse me.Can you give me some suggestions?Thank you!this is my codeclass LMF(nn.Module): def __init__(self, C, R_test , n_factor): ...
ptrblck
print(model) will print the registered modules, which are not present in your current implementation. You could create the extra_repr method, which would print additional information about your custom module, similar tothis one. To print the parameters, you could use: for name, param in model.na…
milad66
%reload_ext autoreload%autoreload 2%matplotlib inlineimport mathimport timeimport osimport globimport numpy as npimport matplotlib.pyplot as pltfrom tqdm import tqdmfrom PIL import Imagefrom sklearn.metrics import confusion_matriximport torchimport torch.nn as nnimport torch.optim as optimfrom torch.autograd import Var...
ptrblck
Your code isn’t formatted correctly (you can post code snippets by wrapping them into three backticks ```), but based on the error message and the current posted code, I guess that the forward method might be defined inside the __init__ method. Could you check it and if that’s the case correct the …
Dhorka
Hi,I was checking the documentation of theVOC datasetprovided by pytorch. I saw that there are three parameters very similar: transform, target_transform and transforms. As far as I understood transforms apply the same transformation to the rgb and the label. However, I didn’t see that “transforms” functionality in the...
ptrblck
You could either define a custom transformation, which accepts the image and target or use e.g. thesegmentation transformations, which also accept these two arguments.
bluesky314
After I load my optimiser state dict when a previously run session with a different lr, the new optimizer’s lr also changes.eg)lr=0.01 opt = torch.optim.Adam(model.parameters(), lr=lr, betas=(0.9, 0.999), eps=1e-08, weight_decay=weight_decay) for groups in opt.param_groups: print(groups['lr']); break opt.load_state_di...
ptrblck
I assume the learning rate was stored in the state_dict and thus loaded in: opt.load_state_dict(torch.load(load_saved)['optimizer'] which I would consider the correct behavior to restore the previous session. If you want to change it after loading the state_dict, you could change it directly in t…
alex_gilabert
HelloI have the next code and im wondering how i could implement somehow the last loop. Here comes an explanation of the codefeatures_list = torch.empty( (0, 1000), dtype=torch.float ).cuda()Firstly we create an empty tensor of 1000 colummns (output of VGG16 conv_layer5_3).Batch size of the dataloader = 8counter = 0 ...
ptrblck
Double post fromhere.
NHH
Consider the following sequential model:Net A -> Net B --> Net CAlso consider Loss B, computed with the output of Net B, and Loss C, with the output of Net C.I would like Loss C to impact the weights of Net A, B and C, and Loss B to only impact Net B.If I add the two losses and run loss.backward(), Loss B will impact N...
ptrblck
You could create two different forward passes through NetB with the output of NetA and with the detached output of NetA: outA = NetA(input) outB = NetB(outA) outB_det = NetB(outA.detach()) outC = NetC(outB) loss = criterion(outC, target) loss.backward() # will calculate the grads for A, B, C loss…
coincheung
Hi,Suppose these is one 2d tensor:ten = torch.randn(4, 5)Now I need to remove one element from each row of that tensor according to another tensor:ids = torch.tensor([2, 1, 4, 1])which means that remove theten[0, 2],ten[1, 1], ten[2, 4],ten[3, 1]from the tensor, and results in a4 x 4` tensor. How could I do this please...
ptrblck
This should work: ten = torch.randn(4, 5) ids = torch.tensor([2, 1, 4, 1]) mask = torch.ones_like(ten).scatter_(1, ids.unsqueeze(1), 0.) res = ten[mask.bool()].view(4, 4)
Spen
Is it possible to mark part of the forward pass to only backpropagate the gradient but not to adjust weights?In the following example code I have aModulethat uses only one layer (one set of parameters) but it is used twice in the forward step. During the optimization I would expect the weights to be adjusted twice as w...
ptrblck
torch.no_grad() is more aggressive, as it Autograd won’t track any operations in the block, so that out2 won’t have a valid .grad_fn and you thus won’t be able to call backward on the calculated loss. .requires_grad will disable the grad calculation for this particular parameter, while the output o…
codeknight11
I am going through someone’s project and noticed that they are downloading resnet models using torch.utils.model_zoo module.I have only used torchvision.models so farWhat is the difference between loading pretrained models via model_zoo vs torchvision.models?
ptrblck
The model_zoo was moved to the torch.hub, if I’m not mistaken. torch.hub is an easy way to load pretrained models from public GitHub repositories and you can find the currently supported modelshere. For a resnet you could either use the torchvision implementation or load these models from the hub…
sad_robot
Hello, so I don’t really get why it is that we need to give a grad tensor to tensor.backwards(). They say the grad should be the gradient of the tensor w.r.t itself but wouldn’t that just be a tensor of all ones?If not could you please give an example where the gradient wouldn’t be all ones?I feel like I’m missing some...
ptrblck
If you are trying to calculate the dLoss/dLoss, then it would be torch.ones, that’s correct. For other use cases it might be different. Recently such a use case was describedhere.
Jaideep_Valani
Is there any pytorch function that can help select every time equal no of times from Tensor listsay tensor([0, 1])If i make sample(tensor[0,1],1) 20 times i should nearly 50 pct of times 0 ,50 pct of time 1
ptrblck
You could use torch.multinomial to sample using weights: x = torch.tensor([0, 1]) weights = torch.tensor([0.5, 0.5]) idx = torch.multinomial(weights, num_samples=100, replacement=True) out = x[idx] Note that the indexing is not really necessary here, since the indices are already the target output…
Peter1
Hello,I am trying to export a torchvision.model.the model is r3d-18 (resnet3D)import torch import torch.onnx import torchvision dummy_input = torch.randn(1, 3, 4, 112, 112) model = torchvision.models.video.r3d_18(pretrained=True) torch.onnx.export(model, x, "ResNet3D-18.onnx")I tried to load the onnx file on matlab.bu...
ptrblck
You are passing x to torch.onnx.export, while it seems dummy_input should have been passed. Could you check it or is it a copy-paste error?
collinbrake
I am attempting to extract the pixel location of an object (a row of plants in my application) from an image. From thisrelated topicI have gathered that CNN’s are not designed to provide locality information about objects in an image, but rather to detect an object anywhere in an image by constructing a translation-inv...
ptrblck
This sounds rather like a segmentation use case, where each pixel will get a class prediction. torchvision provides a few segmentation models, which you could try out for your use case. Let me know, if I misunderstood your question.
Frank_Ofoedu
Hello. I deployed a trained model via flask on heroku. I noticed my predict method keeps failing at the point of applying a transform to an input image.This is the error messageRuntimeError: The size of tensor a (4) must match the size of tensor b (3) at non-singleton dimension 0This is the predict methoddef transform_...
ptrblck
This error might be raised, if your input tensor has 4 channels, while the Normalize transformation expects a 3 channel image. This might happen, if some of your input channels contain an alpha channel. After loading the PIL.Image, you could convert it to RGB via image = image.convert('RGB').
sozerella
I have the weirdest Problem, my neural network makes Cuda run out of memory but can manage x epochs depending on the size of the dataset.Example: data set size: 80, epochs before error: 5, data set size: 40, epochs before error: 10, data set size: 20, epochs before error: 19 (all with a batch_size of 4)I create a data ...
ptrblck
These lines of code will append to losses, which are still attached to the computation graph, and will thus increase the memory usage in each iteration: training_losses.append(total_train_loss) validation_losses.append(total_val_loss) To store the loss value for printing or debugging purposes, yo…
dhananjayraut
I want to do something likea = torch.tensor([0.0, 0.0, 0.0, 0.0, 0.0]) b = torch.tensor([1, 2, 2, 4, 0, 1, 3]) c = torch.tensor([0.3, 0.2, 0.4, 0.1, 1.0, 2.0, 0.4]) a[b] += cexpected result : tensor([1.0000, 2.0000, 0.6000, 0.4000, 0.1000])actual result: tensor([1.0000, 2.0000, 0.4000, 0.4000, 0.1000])at index 2...
ptrblck
a.put_(b, c, accumulate=True) should work. I assume a[1] should have the value 2.3 after the addition.
jahan123
So my dataset is very unbalanced:class-1samples: 76class-2samples: 259now before applying weighted loss function for each class, I want to know does it make any sense to use classweightwhen dataset is this much unbalanced ? Specially when mybatch_size=1.(I can’t increase batch_size because of my system resources).are t...
ptrblck
If you are using a batch size of 1, the loss weighting won’t have any effect in the default setup using reduction='mean', since the weighted mean will be calculated. Here is a small example showing this behavior: # Setup weight = torch.tensor([1., 10.]) criterion = nn.CrossEntropyLoss() criterion_…
Mayank_Jha
Dear all, I am trying to identify a mathematical function (quadratic) using feed forward NNsThe training loss, validation loss go down as desired.however, the NN does not seem to learn at all!Problem is , when I plot “test_x” against predicton from trained NN (y_pred),I get somehting very strange.I am grateful to all t...
ptrblck
Thanks for the code. In your test phase you are recreating a new model and thus lose all training progress: #see the trained outputs net = Network(train_x.shape[1], train_y.shape[1]) net.eval() Reusing your trained model instance yields a prediction which approximates the target curve.
jcgarciaca
I don’t understand how to calculate therunning_lossvalue when training a model.InTraining a classifier tutorialwhen training, therunning_lossis added withloss.item()and set to 0.0 every 2000 mini-batches as follow:running_loss += loss.item() if i % 2000 == 1999: # print every 2000 mini-batches print('[%d, %5d] loss...
ptrblck
It depends how you would like to print the running loss value. In the first example the current loss average of the batch will be added to running_loss, printed after 2000 iterations and reset. The second example prints the loss for the complete epoch and is a bit more accurate. Depending on the …
asha97
Following is the error trace:File “main.py”, line 267, in main_ = train(iteration,optimizer)File “main.py”, line 134, in trainfor j, (img,fix,img_seq,target) in enumerate(trainloader):File “/DATA/rani.1/.local/lib/python3.6/site-packages/torch/utils/data/dataloader.py”, line 345, innextdata = self._next_data()File “/DA...
ptrblck
Based on the stack trace it seems you are using a custom Dataset, which seems to be defined in ./util/data_processing.py. Inside the __getitem__ method you are apparently using np.random.choice, which get’s an invalid argument combination. It seems that len(pt_img) might be smaller than self.pt_len …
nowyouseeme
I have a large tensor of size[80000, 300]. I want to select a set of n rows from this 2D tensor. So the resultant tensor should have a shape[n, 300]. I looked atthissimilar topic, and it proposed a very simple solution of usingtorch.ByteTensor. However my problem is I can not initialise that large ByteTensor.I tried cr...
ptrblck
You could transform the tensor via ind = ind.byte(). However, if your number of indices is small, it should be beneficial to directly index the tensor via: x = torch.randn(80, 3) idx = torch.tensor([0, 4, 6]) ret = x[idx]
shwe87
Hi,Below is my code:class BiGRU(nn.Module): def __init__(self, input_size, hidden_dim, dropout): super(BiGRU, self).__init__() self.BiGRU = nn.GRU( input_size=input_size, hidden_size=hidden_dim, num_layers=1, batch_first=True, bidirectional=True) self.layer_norm = nn....
ptrblck
nn.Sequential takes one additional input, while you are trying to pass two to it. The error message mentions 2 and 3 input arguments, as the self argument will also be counted into the number of input arguments. You could change BiGRU.forward to accept a list of inputs, unwrap it inside the method…
nobodykid
Hello,I have a multi-output model which returns 3 outputs when doing forward passfor data in train_loader: input = Variable(data.type(torch.cuda.FloatTensor)) out_a, out_b, out_c = multi_output_model(input)I’d like to do some post-processing of the output, but because of limited-memory GPU I tried to design so ...
ptrblck
You would have to call the cpu() or to('cpu') operation on each tensor separately either inside the model in its forward method or outside of the model, as you cannot use it on a tuple.
Lucid
Hello. Any solution?When I write pil instead of pytorch (line19), it does not give an error, but the pil is slower. I want to use pytorch.My Code2020.06.12_007_1146×829 133 KBErrorsException in thread Thread-1: Traceback (most recent call last): File "C:\Users\1700x\AppData\Local\Programs\Python\Python38\lib\threadin...
ptrblck
PyTorch doesn’t provide any image decoding methods and torchvision uses PIL by default. You could try to use OpenCV instead of PIL or alternatively PIL-SIMD, which might speedup your code.
mahsa
Hi,I want to define my layer matrix. In my defined layer, I have a diagonal matrix which its parameters are on its diameter. I tried the following way, but it didn’t work. Is there any way I can define something like this?self.weight = Parameter(torch.diag(torch.FloatTensor(1, nparam)))Thanks
ptrblck
torch.diag would return a 1D tensor with the diagonal elements of your input, since you are passing a 2D input tensor to this method. If you would like to create a 2D diagonal matrix, your input tensor should be a 1D tensor. That being said, note that torch.FloatTensor will use uninitialized memor…
aatiibutt
Hy! I have loaded Resnet-152 pre-trained model, and modified the out features of the fc layer through following model.image1024×127 3.75 KBimage1117×372 22.7 KBNow i want to apply relu on the modified fc layer, and then add a new fc layer which take out_features of previous fc layer, and out_feature = 10, like this:Any...
ptrblck
You could assign an nn.Sequential container to model.fc instead of a single linear layer via: model.fc = nn.Sequential( nn.Linear(num_ftrs, 1024), nn.ReLU(), nn.Linear(1024, 10) )
NIkolaStaykov
I am trying to use a temporal conv net with different kernel sizes simultaneously for regression. Net.modules() does not include the 1d convolutions, but rather only the fc layers at the end.class TemporalConvNet(nn.Module): def __init__(self, in_channels, out_channels, kernel_sizes=[2,3], dilation_size=1): ...
ptrblck
Plain Python lists won’t register nn.Modules properly inside the parent model and you should use nn.ModuleList instead.
xcamchoo
Hi,I need to freeze everything except the last layer.I do this:for param in model.parameters(): param.requires_grad = False # Replace the last fully-connected layer # Parameters of newly constructed modules have requires_grad=True by default model.fc = nn.Linear(64, 10)But i have this error:RuntimeE...
ptrblck
I didn’t realize you are using your custom resnet implementation, which uses model.linear as the last linear layer, not fc. Try to change the code to model.module.linear = ... and it should work.
rahulbhalley
It looks liketorch.lerpfunction is available buttorch.slerpdoes not exist in PyTorch 1.0.I’m inspired to try its implementation fromSampling Generative Networkspaper for interpolation in latent space. Also recently introducedGAN 2.0by NVIDIA also doesSlerpinterpolation.Has anyone implementedSlerpin PyTorch? Here is aNu...
ptrblck
There are some minor error regarding the shapes. Here is a working solution for batched inputs: def slerp(val, low, high): low_norm = low/torch.norm(low, dim=1, keepdim=True) high_norm = high/torch.norm(high, dim=1, keepdim=True) omega = torch.acos((low_norm*high_norm).sum(1)) so =…
swim_airport
This is a code example:dataset = datasets.MNIST(root=root, train=istrain, transform=None) #preserve raw img print(type(dataset[0][0])) # <class 'PIL.Image.Image'> dataset = torch.utils.data.Subset(dataset, indices=SAMPLED_INDEX) # for resample for ind in range(len(dataset)): img, label = dataset[ind] # <class '...
ptrblck
Subset will wrap the passed Dataset in the .dataset attribute, so you would have to add the transformation via: dataset.dataset.transform = transforms.Compose([ transforms.RandomResizedCrop(28), transforms.ToTensor(), transforms.Normalize((0.1307,), (…
seewoo5
I have a tensor of shape(batch_size, seq_len). From this, I want to make a tensor of shape(bs, seq_len+1, seq_len+1)where each tensor corresponds to a single batch is an off-diagonal matrix with entries from given tensor.More precisely, from a given tensorx = [[1, 2, 3], [4, 5, 6]],I want to make a function that return...
ptrblck
This code should work: x = torch.tensor([[1, 2, 3], [4, 5, 6]]).float() idx = torch.arange(3).view(1, 1, 3).repeat(2, 1, 1) res = torch.zeros(2, 3, 3).scatter_(1, idx , x.unsqueeze(1))
seedship
Let me start off this post by saying I am a newbie with deep learning and pytorch.I am trying to train a DenseNet instance on a dataset of around 2500 images. Currently, I am parsing them from my disk and loading them into main memory. I have 64GB of main memory and 8GB of GPU memory. I figure since main memory is chea...
ptrblck
Depends on the use case and how the data is stored. Usually I load the data lazily as it also allows for faster debugging (startup time is lower). The entire tensor should not be copied to the device. That might be the case. I’m not sure which GPUs are provided in Google Colab, but you migh…
s.sni
Let’s considera = torch.arange(8).view(2,2,2)which should look like[[[0, 1], [2, 3]], [[4, 5], [6, 7]]]and alsoindex = torch.tensor([1, 0])“index” shows column indexes which should be extracted from “a”.so the output should be look like this:[[1, 4], [3, 6]]although it seems not difficult, using torch.gather and othe...
ptrblck
You could directly index the tensor and permute the output: res = a[torch.arange(2), :, index] print(res) > tensor([[1, 3], [4, 6]]) print(res.t()) > tensor([[1, 4], [3, 6]])
sornpraram
Hi,I am new to CNN, RNN and deep learning.I am trying to make architecture that will combine CNN and RNN.input image size = [20,3,48,48]a CNN output size = [20,64,48,48]and now i want cnn ouput to be RNN inputbut as I know the input of RNN must be 3-dimension only which is [seq_len, batch, input_size]How can I make 4-d...
ptrblck
You would have to decide which dimension(s) should be the temporal dimension (seq_len) and which the features (input_size). E.g. you could treat the output channels as the features and the spatial dimensions (height and width) as the temporal dimension. To do so, you could first flatten the spatia…
Erhan
I implemented a image classificaton algorithm and there are 10 classes.I have small dataset with 216 rgb images.When I train my network, loss value doesn’t decrease.Here is my code:class signLanguageDataset(Dataset): def __init__(self, h5_root_dir, train): self.h5_root_dir = h5_root_dir self.h_data...
ptrblck
A batch size of 2 might be too small for batch norm layers, so you should either increase the batch size or maybe even remove the batch norm layers. I cannot find anything obviously wrong in the code, so I would recommend to play around with the hyper-parameters more (such as removing the scheduler…
barradas
Hi!I’m failing to install pytorch with cuda support on a clean Manjaro install. (Lysia, 20.0.3: kernel is 5.6.15-1-MANJARO)The GPU is a GTX1080ti, CUDA is 10.2.89, and I have tried two ways of installing torch. The first was, as the documentation specifies:pip install --user torch torchvision. I got this through select...
ptrblck
For CUDA10.2.89, you would need a driver >=440.33 as given inthis table. Could you try to update the driver and reinstall PyTorch?
Ahmedib
this the first time I use pytorch and I usepython version==3.7.6 , pandas==1.0.3 , numpy==1.18.4 ,sklearn==0.22.2.post1 torch==1.5.0+cpu , matplotlib==3.2.1I try this code for time series with LSTMtime series with LSTM Pytorchthe problem in this code exactly ( local variable ‘batch’ referenced before assignment ) a...
ptrblck
It would be possible, if len(x) contains at least batch_size+1 samples, which doesn’t seem to be the case. This loop won’t yield anything for lengths in [0, batch_size]: batch_size = 32 for i in range(0, 32 - batch_size, batch_size): print(i)
frwidi
Dear all,I am new to Pytorch. For my work, I am using IterableDataset for generating training data that consist of random numbers in a normal distribution. I read in the documentation that ChainDataset can be used for combining datasets generated from IterableDataset. I tried to code it, but it doesn’t work as I expect...
ptrblck
IterableDatasets don’t end automatically, as they don’t use the __len__ method to determine the length of the data and in your particular code snippet you are using a while True loop, which won’t exit. Instead you should break, if your stream doesn’t yield new data anymore or use any other conditio…
songyuc
Hi guys,I meet a problem that, how to get the index of a element in a Tensor whose value is True?Such as, a Tensor like:False False FasleFlase True FalseFalse False FalseThen I can get the index of (1,1).So how can I implement this operation?Your answer and idea will be appreciated!
ptrblck
nonzero() would return you the indices of all non-zero entries (in that case True): x = torch.bernoulli(torch.ones(3, 3) * 0.5).bool() print(x) > tensor([[ True, True, False], [False, False, True], [ True, False, False]]) print(x.nonzero()) > tensor([[0, 0], [0, 1], …
ooodragon
Hello!I’m using nn.Dataparallel and tried to get its name by model.class.basebut it does not work with nn.Dataparallel which only gives string (DataParallel)is there any solution without changing the model’s status?
ptrblck
nn.DataParallel will create model replica on all specified devices. During the forward pass, the data will be split in dim0 and each chunk will be sent to the corresponding device.This tutorialgives you more information regarding the shapes andthis blog postexplains the overall work flow as wel…
albanD
Hi,You can try to enabletorch.autograd.set_detect_anomaly(True)to see which forward function corresponds to the failing one in the backward.Also You can try to run the same code on CPU to see if you get a better error message.Also, I would double check all the indices in the multiple indexing you do.Finally. You should...
ptrblck
Sorry for the delayed reply, but yes it should be fixed by now. Let us know, if you run into this issue again, please.
NearIt
i am usingFashionMNIST_train_dataset = torchvision.datasets.FashionMNIST( root = './data/FashionMNIST', train = True, download = True, transform = transforms.Compose([ transforms.ToTensor() ]) )and I want SPLIT this data to N balanced labeled data, and the re...
ptrblck
You could use e.g.sklearn.model_selection.StratifiedShuffleSplit(or any other suitable splitting function) to create the split indices. Once you have the indices, you could pass your dataset together with the split indices to a Subset and pass it then to a DataLoader.
tyterry
Hi all,I am trying to implement mixed precision training in pytorch, which would involve scaling the loss (computed in half precision) with a scaling factor and compute the gradient, then update the master model (in one precision) with the computed gradient divided by the same scale factor.I know that I can extract the...
ptrblck
Additionally to@albanD’s suggestion, you could scale the loss before the backward call, which would automatically scale all gradients and unscale the gradients before the update. Note that automatic mixed-precision is currently available in themaster and nightly binaries, in case you don’t want t…
Zador
Hi!I followed the pytorch tutorial on the topic transfer learning but I am getting results that are clearly wrong. As the application I am trying to apply is different a had to make some tweaks and it would be great if someone can give me some insight.You can see below that I am here removing the final layer of the pre...
ptrblck
torch.no_grad() will avoid storing the intermediate tensors during validation and testing and will thus save memory. model.eval() will change the behavior of some layers. E.g. it will disable dropout layers and use the running stats in batchnorm layers instead of the batch statistics. If you didn’…
AlvinZheng
Hi~I encountered a strange phenomenon: after pruning an empty filter in a conv layer, the output features of the conv is inconsistent with the previous one, (The shape change is as expected, what I said is the value inconsistency)To reproduce:c1=torch.nn.Conv2d(3,10,7,bias=False) c2=torch.nn.Conv2d(3,9,7,bias=False) fo...
ptrblck
The difference is most likely created due to the limited floating point precision and a different order of operations as shown in this example: x = torch.empty(100, 100, 100).uniform_(0, 100) print(x.sum()) > tensor(49965816.) print(x.sum(0).sum(0).sum(0)) > tensor(49965808.) Also, you shouldn’t u…
carlogarro
I have a very big dataset, and I would like to use a different random subset for each epoch of 1000 samples. Is there any way I can do it using Dataset and Dataloader?I would like something liketorch.utils.data.RandomSamplerbut without replacement.train_loader = DataLoader( train_dataset, batch_size=32, shu...
ptrblck
Your approach looks correct. To verify it, I would suggest to print the index in Dataset..__getitem__ for a couple of epochs and make sure that you are seeing a variety of indices.
glenguo06
Hi, recently I need to implement functional.conv_transpose2d() with pure C++ code from scratch, and use cudnn if needed. Where can I follow in detail how this function in PyTorch or ATen is actually implemented?
ptrblck
The general dispatching is done inATen/native/Convolution.cpp, in particular the cudnn implementation is called inthese lines of code. This will then call intocudnn_convolution_transpose_forward, which is the backward operation of a vanilla convolution.
Vishu_Gupta
How do I perform an average of 2 or more layers i.e.z = keras.layers.average([x, y, w])as done in Keras. Should I first add them viatorch.addand then divide by the number of layers or is there any direct way to perform it?
ptrblck
If you want to calculate the average of the activations of different layers, you could simply add them and divide by the number of activations (3 in your case). I’m not sure, what “average of layers” means, but if you want to average the parameters of different layers, you could usethis approach.
jueqi_wang
I am usingBCEWithLogitsLossas loss function, and the output size and targets size is the same as ·torch.Size([4, 1, 128, 128, 128])· but I run into that error.
ptrblck
nn.BCEWithLogitsLoss should work, if the model output and target have the same shape. Could you print the shape of both inputs again and check, where the size of 2 is coming from?
postBG
F.conv2d only supports applying the same kernel to all examples in a batch.However, I want to apply different kernels to each example. How can I do this?The most naive approach seems the code below:def parallel_conv2d(inputs, filters, stride=1, padding=1): batch_size = inputs.size(0) output_slices = [F.conv2d(inpu...
ptrblck
Thanks for the update and I clearly misunderstood the use case. I think if the kernel shapes are different, you would need to use a loop and concatenate the output afterwards, as the filters cannot be stored directly in a single tensor. However, if the kernels have all the same shape, the grouped …
DumnBird
I am trying to convert a parameter of resnet34 to numpy , but I found that the values would change after converting, as shown in the figure.Why would this happen? What can I do to get precise values in numpy format?( I am trying to get parameter in torch pretrained models and put them in tensorflow 1.x model , since ...
ptrblck
This is most likely a printing issue and you could use torch.set_printoptions(precision=15) to increase the decimals.
arjun_pukale
My task is to create a single object detection model, It is doing 2 task: 1. Classification between 2 classes [cat, no object]2: Regression x and y co_ordinates.So I want to design a loss function such that it gives me 2 losses for classification and regression each.for classification I am using CrossEntropy Loss, but ...
ptrblck
The code looks generally alright. The output should contain raw logits, not probabilities for the nn.CrossEntropyLoss, but I assume you just used these values for easier debugging. If you are concerned about the indexing, you could just use separate target tensors (and potentially different output …
weidler
I have a tensor of order 5 and want to reduce it to order 4 by selectively picking along the third domain based on the position in the second domain.Let’s say my original tensor’s shape is(1, 16, 16, 8, 8)and I want to get(1, 16, 8, 8). So far, I am doing this as follows iteratively:import torch original_tensor = torc...
ptrblck
I don’t quite understand this use case, but based on your loop approach, you could use arange to index the tensor via: original_tensor[:, torch.arange(original_tensor.size(1)), torch.arange(original_tensor.size(2))] which would result in the same output as output_tensor.
Truong_Khang
Hello,I run my model on a single GPU, the result of the test set is normal. But when I change to run on multiple GPU, the metrics evaluated on the test set (loss, RMSE,…) are not stable, they increase dramatically over time. I wonder why this problem happens, I thought the result must be the same in both cases.Pytorch ...
ptrblck
Thanks for the code. It seems your approach is similar to weight_norm, which uses the setattr and getattr to modify the weight parameter so you could try to adaptWeightNormto your use case. Alternatively, it might be easier to use the functional API, which would define a self.weight parameter, m…
Sorench
Hi,I have been reading through the posts that mention slow back prop and my undertanding is that backprop should take about 2x the forward pass. Mine takes 20x.I am running a 3D U-Net on a (1,1,32,512,512) test image volume and I am consistently gettig these numbers (Titan RTX and pytroch 1.5.0 from pip):Transferring i...
ptrblck
Assuming you are using cudnn, you could add torch.backends.cudnn.benchmark = True at the beginning of your script to use the cudnn heuristics to pick the fastest algorithms for your workload. Note that the first iteration for each new input shape will be slow, as cudnn is benchmarking the kernels, …
shwe87
Hello,I have created the following model:def __init__(self, input_size, output_size, hidden_dim, n_layers, n_feats, drop_prob=0.5): super(MySpeechRecognition, self).__init__() #output_dim = will be the alphabet + '' and space = 28 chars self.input_size = input_size self.hidden_dim = hidd...
ptrblck
You could try to profile the code and determine where the bottleneck is at the moment. E.g. if the data loading is the bottleneck, you could potentially increase the number of workers, if that’s not already done. I don’t know what kind of systems are used on Kaggle, so I cannot comment on the data …
dedeco
I intend during the train compute the loss using MSELoss but using max error as reference for stoping to train and to compute the error.Note that I set reduce=False, so the loss_func will returns a loss per input/target element. How I can use an optimizer that I can use max error to compute?Error:/Envs/climaenv/lib/pyt...
ptrblck
If you want to use the max error to stop your training, you could use loss = orig_loss.max().detach().numpy() Currently orig_loss is not a scalar, as you use reduce=False in your loss function. Therefore float cannot cast it to a scalar float.
Bick95
I am working on implementing a GAN.For computing the loss of the generator, I compute both the negative probabilities that the discriminator mis-classifies an all-real minibatch and an all-generated-fake minibatch. Then, I back-propagate both parts sequentially and finally apply the step function.Calculating and back-p...
ptrblck
If I understand the code correctly, get_dis_xy will return two tensors, which were not created by the generator (or if they were, then they are detached inthese lines of code, since they are re-wrapped in the deprecated Variable class). You could check for gradients in the generator after the bac…
Jordan_Howell
This is what I put:os.environ['CUDA_LAUNCH_BLOCKING']="1" python inspection_model.py
ptrblck
The nn.Embedding layer would get an input tensor, and you should check its min and max value, e.g. as: print(x.min(), x.max()) out = self.embedding(x) # raises the index error This might give you the indices, which are out of bounds. However, the error description is a bit confusing, as you mentio…
Solitude
Hi, I would like to have the identical transformation on the input and label but I can’t figure it out. Here’s my code:# Pytorch import torch import torchvision import torch.nn as nn import torch.nn.functional as F import torchvision.transforms.functional as TF from torchvision import datasets, models, transforms from ...
ptrblck
Alternatively to the seeding approach, you could also use the functional API as explainedhere.
theairbend3r
I’m trying to insert residual connection in my small 3 conv-layer.Here’s what it looks like -class ResClassifier(nn.Module): def __init__(self, num_classes): super(ResClassifier( self).__init__() self.block1 = self.conv_block(c_in=1, c_out=16, dropout=0.1, kernel_size=5, stride=1, ...
ptrblck
You could use a downsample layer as seen in the originalResNet implementation, which could just use a 1x1 conv with the desired number of output channels to match the activation.
shwe87
Hi everyone,I have created a few models using Deep Learning but mostly have worked with images. Unlike with audio, images can be cropped, resized, etc.So, I was in the process of creating a Speech Recogniton model (for Spanish) as my thesis and I got to do these steps:This is my dataset, the dataset are of different le...
ptrblck
In the default setup nn.RNN (as well as e.g. nn.LSTM) expect an input in the shape [seq_len, batch_size, features]. I assume you are working with 128 frequencies and a variable sequence length in the last dimension. If that’s the case, you could remove dim1, which seems to be an unnecessary channe…
John_J_Watson
I have a use case, where I think using two optimisers would help the model learn better. Let me explain: so, I have one model like so:my_model=Net()which is trained overNsamples belonging to training_set1. Now, I use results of this trained model (embeddings to be precise) to generate another training_set2, which is a ...
ptrblck
Your approach should be valid code-wise. The optimizers would only apply their step() method to all parameters, which have a valid gradient, so there shouldn’t be a problem.
Harsimar_Singh
Hi experts and community folks, here I am trying to do some hack using list.children()import fastaifrom torchsummary import summaryfrom fastai.vision.models.unet import *from fastai.callbacks import *from fastai.utils.mem import *arch = torchvision.models.resnet34(pretrained=False)li = list(model.children())#listof the...
ptrblck
If you want to change the first layer, you can directly replace it via: model = torchvision.models.resnet34(pretrained=False) model.conv1 = nn.Conv2d(1, 64, (7, 7), (2, 2), (3, 3), bias=False) x = torch.randn(1, 1, 224, 224) out = model(x) I’m not sure what might go wrong in your code, as it’s a …
aroibu1
I have been trying for a while to use CosineEmbeddingLoss() as the loss function for a network that I am working on. However, when I tried a simple example to check some of it’s features, I am running into some strange behaviour, as below.If, for example, I do the following, then the behaviour is as expected…>>> loss =...
ptrblck
The problem arises, as the cosine similarity between zero vectors is undefined. In PyTorch nn.CosineEmbeddingLoss returns apparently a loss of 1 for zero tensors: loss = torch.nn.CosineEmbeddingLoss(reduction='none') b = torch.tensor([[0.,0.,0.],[0.,1.,0.],[0.,0.,0.]]) print(loss(b, b, torch.ones_…