user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
srod
I have ak x 2tensor namedpointsand I have anotherk x 1tensor namedmask.maskcontains 1 or 0 for each index. I want to filterpointsand remove the entire row ifmaskdoes not contain a 1 for that specifick. How can I do this?
ptrblck
You could use torch.masked_select: k = 10 x = torch.randn(k, 2) mask = torch.empty(k, 1, dtype=torch.uint8).random_(2) x.masked_select(mask).view(-1, 2)
bb417759235
class DenseNet(nn.Module):“”“Densenet-BC model classArgs:growth_rate (int) - how many filters to add each layer (k in paper)block_config (list of 4 ints) - how many layers in each pooling blocknum_init_features (int) - the number of filters to learn in the first convolution layerbn_size (int) - multiplicative factor fo...
ptrblck
I’m not sure how _Denseblock is defined, but assuming you are using nn.Conv3d layers, this line might be the issue: self.features.add_module('norm5', nn.BatchNorm2d(num_features)) Should this be BatchNorm2d or rather BatchNorm3d? Or is the transition layer flattening your output already?
Tudor67
Hi, I am trying to initialize the weights of a conv net (with nn.Sequential) using a custom method.When I do this initialization my network achieves an accuracy equal to ~10% (for CIFAR-10 this is equivalent to a random response => the network doesn’t learn anything). Without this initialization I get ~58% accuracy (th...
ptrblck
I’ve tested your code for some random input and the model could fit it. Using CIFAR10, I just set the channels to 6 and 12 in the conv layers. The model indeed struggles to learn and the default random init seems to be better. Changing fan_in = shape[1] for linear layers makes it a bit better. …
Wei_Chen
I am not sure if I understand it correctly, but when I read the code here:https://github.com/jcjohnson/pytorch-examples/blob/master/nn/two_layer_net_module.py.In training part:for t in range(500): # Forward pass: Compute predicted y by passing x to the model y_pred = model(x) # Compute and print loss loss = lo...
ptrblck
The computation graph is constructed in each forward pass, which allows you to create your model dynamically and use plain python control-flow operators like for loops etc.
TheShadow29
So when I ran my code around 2 days ago it was taking 1 min per epoch, and when I ran exactly the same code today it was taking around 10 mins per epoch. In fact, it started very fast and after about 30-50% of the epoch is done, it suddenly slows down.I noticed that my disk space (4tb hdd) had only about 70 gb left. So...
ptrblck
Based onthese claimsit’s apparently a valid assumption that your HDD/SSD slows down once it’s almost filled.
Naman-ntc
What is the standard way to get the gradient value at a particular node in pytorch 0.4.1When I try to access the gradient of a particular tensor in graph using the .grad attribute I getNone.Istorch.autograd.gradthe approach I should follow.Also is the None coming to free up memory. (I also tried using retain_graph=True...
ptrblck
Have a look atthis thread. register_hook is probably, what you want.
vinaykumar2491
Hi,I’m using Convolutional Autoencoder Network. While training my CPU RAM (30GB) is getting fully used in just 20 epochs but my GPU memory (8GB) is used only 5%.How should I approach to use my GPU better and reduce CPU memory usage.Thanks
ptrblck
You are storing the computation graph using this line of code: running_loss += loss Change it to running_loss += loss.item() and try it again.
cod3licious
I’m trying to use the ReduceLROnPlateau scheduler but it doesn’t do anything, i.e. not decrease the learning rate after my loss stops decreasing (and actually starts to increase over multiple epochs quite a bit).Here is the code:criterion = nn.MSELoss() optimizer = optim.Adam(self.model.parameters(), lr=lr, wei...
ptrblck
The patience is applied to the last minimal loss value and the subsequent values. Let’s analyze the behavior for patience=0: Until epoch10 the loss is decreasing (starting with epoch0). The loss in epoch11 increases; since patience=0, we are decreasing the lr. The current min value is 10980 from …
AlexV
The convolutional layers (e.g.nn.Conv2d) requiregroupsto divide bothin_channelsandout_channels. The functional convolutions (e.g.nn.functional.conv2d) only requiregroupsto dividein_channels.This leads to confusing behavior:import numpy as np import torch from torch import nn from torch.nn import functional as F # test...
ptrblck
It seems to be fixed in the current master, although the error message is a bit unclear: RuntimeError: std::exception EDIT: I’ve created an issuehere. Thanks for reporting it!
sanayam
I am trying to save the bicubic and HR_np images. I can plot it right but I am having a hard time in saving it. Below is my code. I tried using torchvision.utils.save_image(imgs[‘bicubic_np’], ‘ccc.png’.format(), nrow=8, padding=2, normalize=False, range=None, scale_each=False, pad_value=0) but it did not work. Tell me...
ptrblck
Sure, no worries. Here is a small example using random values for your imgs: imgs = {} imgs['bicubic_np'] = np.random.randn(1, 576, 576) tensors_to_plot = torch.from_numpy(imgs['bicubic_np']) torchvision.utils.save_image(tensors_to_plot, 'test.png') You have just to use the last two lines of code…
sanayam
I have attached the screenshots of my code and the error. Can anyone tell me where I am going wrong?Screenshot-2018-8-30%20super-resolution2144×1014 140 KBScreenshot-2018-8-30%20super-resolution(1)2144×1014 285 KBScreenshot-2018-8-30%20super-resolution(2)2144×1014 124 KBScreenshot-2018-8-30%20super-resolution(3)2144×10...
ptrblck
You haven’t posted the code of your model, but I assume the last layer is a convolution with out_channels=3. You can add code using three backticks `. It’ll make debugging easier and the search of this forum can find your code, if someone else has this problem. Are you dealing with gray-scale imag…
pritisolanki
Hi,I am using vgg16 pre-train model . I have replaced the classifier with followingclassifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(input_size, hidden_sizes[0])), ('relu_fc1', nn.ReLU()), ('drop_fc1',nn.Dropout(drop_p)), ('fc2', nn.Linear(hidden_sizes[0], hidden_sizes[1])), ('relu_fc2', nn...
ptrblck
Could you print the shape of toImg? The standard size for vgg16 is [batch_size, 3, 224, 224]. Also, you shouldn’t use model.forward as this might yield strange behavior, if you want to use hooks. Just call the model directly: output = model(toImg).
ankitvad
I’m a little confused how to detach certain model from the loss computation graph.If I have 3 models that generate an output:A,BandC, given an input.And, 3 optimizers for those 3 models:Oa,ObandOc, for A, B and C resp.Let’s assume I have an initial inputx.I also have 3 lossesL1,L2andL3.Let’s assume a scenario where th...
ptrblck
.detach() will return a detached version of your tensor. You can reuse the “attached” tensor for further computations as long as you don’t reassign it somehow: modelA = nn.Linear(10, 10) modelB = nn.Linear(10, 10) modelC = nn.Linear(10, 10) x = torch.randn(1, 10) a = modelA(x) b = modelB(a.detach(…
vinaykumar2491
nn.Upsample()is depecated inpytorch version > 0.4.0in favor ofnn.functional.interpolate()I’m not able to useinterpolate()insidenn.Sequential():Below is my network:class MeeDecoder(torch.nn.Module): def __init__(self): super(MeeDecoder, self).__init__() self.de_layer1 = torch.nn.Conv2d(in_channels=4...
ptrblck
You could create a nn.Module with your interpolate function as a workaround: class Interpolate(nn.Module): def __init__(self, size, mode): super(Interpolate, self).__init__() self.interp = nn.functional.interpolate self.size = size self.mode = mode d…
dizcza
I’m trying to implement efficient k-winner-take-all activation function in PyTorch.class KWinnersTakeAll(torch.autograd.Function): @staticmethod def forward(ctx, tensor, sparsity: float): batch_size, embedding_size = tensor.shape _, argsort = tensor.sort(dim=1, descending=True) k_active...
ptrblck
I think you could use advanced indexing for your use case. Here is a small example with smaller sizes for better understanding: batch_size = 5 features = 4 idx = torch.empty(batch_size, 2, dtype=torch.long).random_(features) mask_active = torch.zeros(x.shape, dtype=torch.uint8) mask_active_fast =…
Htut_Lynn_Aung
Is there any way to do real time image classification with webcam using Pytorch trained model?
ptrblck
I’ve checked another possibility and this is most likely the issue. In your normalization, you have an additional zero for the third channel, which results in the inf values: transforms.Normalize([0.485,0.456,0.406],[0.229,0.224,0,0.225]) Remove the zero and try it again.
carioka_88
Hello,I am kind of new with Pytorch.I would like to run my CNN with some ordered datasets that I have.I have n-dimensional arrays, and I would like to pass them like the input dataset.Is there any way to pass it with torch.utils.data.DataLoader?Or how can I transform the n-dimensional array into a DataLoader object?For...
ptrblck
You could create a Dataset, and load and transform your arrays there. Here is a small example: import torch from torch.utils.data import Dataset, DataLoader import numpy as np class MyDataset(Dataset): def __init__(self, data, target, transform=None): self.data = torch.from_numpy(da…
YuxiaoXu
We have several offline machines and want to deploy pytorch on them. To do this, We need to build a wheel package containing all dependencies (just like the official wheel package) in one machine and install the built .whl file in others. The result is:(1) A .whl file is built in one machine and successfully installed...
ptrblck
What GPUs are you using? Is only the first CUDA call taking a long time? In the past this was due to a mismatch of your CUDA version which resulted in PyTorch being recompiled for your GPU. Could you try it with CUDA8 and see, if it still takes that long?
Daniel_Joseph
Hello everyonecould you please help me getting through this issue, i want to read ‘.mat’ file contains 145x145x200 pixels and i need to feed it into a network, is there any way to do this?I would be very grateful for any help
ptrblck
You could load the .mat using scipy.io.loadmat (docs) and then wrap the numpy array into a tensor.
ivan-bilan
I need to translate the following numpy code to PyTorch, in particular the np.tile part (ideally, PyTorch 0.4.0 compatible):# k.size() = q.size() batch_size, sent_len, vec_size = q.size() # i.e. [150, 96, 120], also k is same q_ = np.repeat(q, sent_len, axis=1) k_ = np.tile(k, (sent_len, 1)) concat_vecs = np.stack([q_...
ptrblck
This should yield the same result: q = np.random.randn(150, 96, 120) k = np.random.randn(150, 96, 120) batch_size, sent_len, vec_size = q.shape # i.e. [150, 96, 120], also k is same q_ = np.repeat(q, sent_len, axis=1) k_ = np.tile(k, (sent_len, 1)) concat_vecs = np.stack([q_, k_], axis=2).reshape(…
dhecloud
Just wondering if this interaction with indexing with tensors as opposed to with lists is intended.Listsa = [1,1,1] b = a[1] b -= 1a will still be [1,1,1] and b will be 0On the other hand, for tensors,a = torch.ones(3) b = a[1] b -= 1a will be tensor([ 1., 0., 1.]) and b will be tensor(0.).Is this the intended behavi...
ptrblck
It’s intended behavior. If you want to get a copy, you could use .clone(): a = torch.ones(3) b = a[1].clone() b -= 1
michaelklachko
I’m seeing consistent change in results when I make a trivial change to my code.Original version:class LeNet(nn.Module): def __init__(self, nfilters=32, nclasses=10, linear=128): super(LeNet, self).__init__() self.linear1 = nn.Linear(nfilters*5*5, linear) self.linear2 = nn.Linear(linear, ncl...
ptrblck
I think you have a typo in your first model, as you are not using the Dropout layer in forward: x - self.dropout(x) This should probably be an assignment instead of a subtraction. You will get exactly the same output, if you fix this typo and seed all operations accordingly: torch.manual_seed(28…
oasjd7
Hi all, I`m confused that three types of optimizer expressions.1. optimizer = torch.optim.Adam(list(model1.parameters()) + list(model2.parameters()), ...)vs2. optimizer = torch.optim.SGD([{'params': model1.parameters()}, {'params': model2.parameters()}], ...)vs3. optimizer = torch.optim.Adam(...
ptrblck
The first and third approach are basically the same with the difference that you are passing the parameters of two different models together in 1. The second one can be used forper-parameter options.
oasjd7
I want to test nn.CrossEntropyLoss() is same as tf.nn.softmax_cross_entropy_with_logits in tensorflow.so I have tested on tensorflow and pytorch. I got value with tensorflow, but I don`t know how to get value of pytorch.Tensorflow test :sess = tf.Session() y_true = tf.convert_to_tensor(np.array([[0.0, 1.0, 0.0], [0...
ptrblck
I’ve fixed your PyTorch code as there were some minor issues: loss = nn.CrossEntropyLoss(reduction='none') input = torch.tensor([[0.5, 1.5, 0.1], [2.2, 1.3, 1.7]], requires_grad=True) target = torch.tensor([1, 2], dtype=torch.long) print(type(input), type(target)) output = loss(input, target) outpu…
brianC
I usedtorchvision.model.resnet18to classify images, but it seems output same result with different input.Here is my test coderes_model = torchvision.models.resnet18(pretrained=True) normalize = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize( mean=[0.4...
ptrblck
Try to set your model to evaluation using model.eval() before testing your images.
shn
for the Consumer-to-shop Clothes Retrieval dataset, it need to read a pair image at the same time, it will be okay as followed code?img1 = read('...') img2 = read('...') img = [img1, img2]thanks for replying me
ptrblck
I assume you would like to create a Dataset returning both images? The easiest way would be to create an own Dataset class and use your code snippet to load the data: class MyDataset(Dataset): def __init__(self, image1_paths, image2_paths, transform=None): self.image1_paths = image1_pa…
Wanger-SJTU
I have a pretrained model, and want to apply it to a new dataset. From the AdaBN paper, I want to recaculate the the mean and var for each neuros and update the value for each BN layer. How could I reset the parameter?
ptrblck
You can call .reset_parameters() directly: bn = nn.BatchNorm2d(3) bn(torch.randn(10, 3, 24, 24)) print(bn.running_mean) print(bn.running_var) bn.reset_parameters() print(bn.running_mean) print(bn.running_var)
_chen
Hi, I want to finetuning the pretrained inception v3 model, but get type mismatch error. the following is my code.#!/usr/bin/env python3 import torch import torch.nn as nn import torch.optim as optim from torchvision import models import torchvision.transforms as transforms from bcdataset import BloodCellDataset impor...
ptrblck
You have to assign the images and labels when you push them onto the GPU: images = images.to(device) labels = labels.to(device) Could you change it and try it again?
vinaykumar2491
Hi,I’m getting the following error.RuntimeError: Calculated padded input size per channel: (1017 x 1). Kernel size: (3 x 3). Kernel size can't greater than actual input size at /opt/conda/conda-bld/pytorch_1524584710464/work/aten/src/THNN/generic/SpatialConvolutionMM.c:48My input tensor has size [1,1,1025,15]Followin...
ptrblck
Your last conv layer in your encoder throws this error, since it receives an input of [1, 30, 1017, 1] and tries to use kernel_size=3. You have to lower the kernel size to 1 or modify your model somewhere before this layer.
Ranahanocka
https://pytorch.org/tutorials/intermediate/reinforcement_q_learning.htmlwhile the comments in the tutorial specify that autograd is used, it is never explicitly declared (that I can see). In supervised learning, the inputs are usually set as input_data = Variable(input_data) and then out = net.forward(data). However, h...
ptrblck
I haven’t explored the tutorial in detail, but from what I know state_action_values are the output of the model, and should already require gradients. Could you check it with state_action_values.requires_grad? Also, if you re-wrap a Tensor, it will lose it’s associated computation graph and you ar…
John1231983
Hello all, I have read some related question about imbalance classification; however, I did not find the answer. My dataset is imbalance class that shows the distribution in belowScreenshot%20from%202018-08-20%2010-25-03969×556 21.5 KBI am usingWeightedRandomSamplerto handle the above problem. First, thetrain_labelsis ...
ptrblck
I think your issue might be related tothis one. Try to pass the weights for each sample to WeightedRandomSampler and see if it’s working.
bb417759235
I want to fine tune a classification network.so,I need to make a one-hot label.label = torch.zeros(1,74,dtype=torch.long) //1 batch size 74 categories label = label.scatter_(dim=1,index=torch.LongTensor([[ (0~73) ]]),value=1)print(label) **torch.Size([1, 74])**RuntimeError: multi-target not supported at ClassNLLCr...
ptrblck
CrossEntropyLoss does not work with one-hot encoded targets. The target dimensions are specified as [batch_size]. Internally the indices are stored. In the example input has a batch size of 3 and provides 5 logits. The target has the same batch size of 3 with random indices.
jpainam
Hi. I have a tensoryof shapetorch.Size([32, 1, 4, 2])andxof shapetorch.Size([32, 2048, 4, 2])I want to multiplyx*yacross allxchannel. I have tried# case 1 xy = x*y # shape torch.Size([32, 2048, 4, 2]) # case 2 b, c, h, w = x.size() # shape torch.Size([32, 2048, 4, 2]) b_att, c_att, h_att, w_att = y.size() # shap...
ptrblck
As both methods return the same result, I would prefer the first one.
JustnLiu
Hi,I was trying to train GoogLeNet on a server with multiple GPUs using python3 + pytorch 0.3.1.post2. However, I keep getting this error: ‘RuntimeError: CUDNN_STATUS_INTERNAL_ERROR’. It seems like this error happens when conv3d() is called. The complete error message is below. Could anyone help me out with it?ThanksFi...
ptrblck
Is your code running on CPU? Also, could you update to the latest release and check it again or do you need this PyTorch version for some reason?
eslam
fc = nn.Linear(128, 128)lin = fc1(torch.tensor([16,128]))Can anyone please tell me why this error appears?.. it works when editing the last line to belin = fc1(torch.Tensor(16,128)) … what is the difference between torch.tensor() and torch.Tensor()Thanks a lot
ptrblck
The types of output and target should be the same. Try to cast your target to float32 using target = target.float().
vlco
Following the tutorial:https://pytorch.org/tutorials/intermediate/spatial_transformer_tutorial.htmlWhat would I need to do to adapt the STN network to work with specific B=batch size, H=image height, W=image width, C= channels? I assume B is handled by .view(-1, …) but what about the remaining H, W, C values?Thank you ...
ptrblck
You mean the view() op in in stn() and forward()? If you change the number of input channels, height and width for your input, you would need to adapt the in_features for the linear layers as well or alternatively use adaptive pooling layers to get your desired output size. As you can see self.loc…
ojh3636
I faced to something weird error when I try to move Tensor to GPU.First my machine spec isUbuntu 16.04nvidia driver: 390.77GPU: TitanX (Pascal)Torch 0.4.1 (with cuda9.0)I didn’t install any cuda Toolkit in my local, just download pytorch via anaconda to my virtualenv. (because I saw some posts that downloading pytorch ...
ptrblck
Did you restart the machine after reinstalling the drivers? If so, could you try to install PyTorch via conda with CUDA9.1 or 9.2?
hansole
When getting a state dict using<module>.state_dict()the dictionary references the internal parameters of the model. Meaning, once the model changes, the dict will also change. Usually this doesn’t really impact things as most people will serialize the state to disk straight away.If you however keep copies of the state ...
ptrblck
You are right. Sorry for being not clear enough. Here is another small code example: old_state_dict = {} for key in model.state_dict(): old_state_dict[key] = model.state_dict()[key].clone()
campellcl
In the event that a classification model is being trained on a large amount of data (~3,000,000 input images per epoch), what is the recommended approach for implementingcheckpoint-like functionality at the mini-batch level, instead of the epoch level (as shown here)? Can anyone recommend a way to save the weights and ...
ptrblck
Neither the model nor the optimizer use the epoch or batch count. It’s up to you to store and load the model checkpoints. The model and optimizer just use .load_state_dict() to restore their parameters. If you can work with epoch + minibatch, it’s fine. Alternatively you could somehow store the e…
youkaichao
according to the documentationhttps://pytorch.org/docs/stable/torchvision/models.html, pretrained models are pretrained on ImageNet. But I’d like to knowexactly the yearof the ImageNet dataset used.Does it matter? Or imagenets are roughly the same?
ptrblck
They are trained on ImageNet-12:
ptab
Hi,For a given input of size (batch, channels, width, height) I would like to apply a 2-strided convolution with a single fixed 2D-filter to each channel of each batch, resulting in an output of size (batch, channels, width/2, height/2).Using the group parameter of nn.functional.conv2d I came up with this solution:I wo...
ptrblck
I think it would be faster to reshape your input, so that your channels are stacked in the batch dimension. [batch_size, channels, h, w] would become [batch_size * channels, 1, h, w]. Then you could use a conv layer with in_channels=1 and out_channels=1 and reshape the output again. batch_size = …
inkplay
I am trying to build a progressive autoencoder, for the encoder part I would like to prepend more layer on top of a ModuleList, how can I achieve that? I want to avoid copying and remaking my model every time I grow a layer.eg: # BEFORE GROWTH self.layers = nn.ModuleList( [ conv2d( 256, 512 ), nn.ReLu() ] ) forward...
ptrblck
Would that work: mlist = nn.ModuleList([nn.Conv2d(3, 6, 3, 1, 1)]) mlist = nn.ModuleList([nn.Conv2d(1, 3, 3, 1, 1), *mlist]) Or are you trying to avoid exactly this?
isalirezag
Can any one help me with this question?Lets say i have a 4x4 tensor and i want to do subsampling in the following way, so for each 2x2 block i put the smallest elements together,then the second smallest elements, and so on, so the out put will be 4 tensors with size half of the input. Stride will be = 2.Here is an exam...
ptrblck
You are right! Thanks for pointing this out. Here is a (hopefully) fixed version: kh, kw = 2, 2 dh, dw = 2, 2 input = torch.randint(10, (1,2,6,6)) input_windows = input.unfold(2, kh, dh).unfold(3, kw, dw) input_windows = input_windows.contiguous().view(*input_windows.size()[:-2], -1) input_windows…
isalirezag
I am wondering if maxpool2d in pytorch as any learnable parameter? and if so what is that?I saw people useself.pool1 = nn.MaxPool2d(2, 2) , self.pool2 = nn.MaxPool2d(2, 2),etc in their models. So i assume there should be some learnable parameters.The reason that im asking is that im trying to build my own maxpool and w...
ptrblck
Max pooling does not have any learnable parameters. You can check if with: pool = nn.MaxPool2d(2) print(list(pool.parameters())) > [] The initialization of these layers is probably just for convenience, e.g. if you want easily change the pooling operation without changing your forward method.
jpainam
Hi!I’m usingsave_imageafter some conv layer to output the image. But since the output shape of the tensor istorch.Size([32, 1, 3, 3]). I end up having very tiny images. How can I resize before calling save_image.By the way, usingscipyworksimg = x.detach().cpu().numpy() img = img[0] # Taking one image to test with img =...
ptrblck
You could use: x = torch.randn(32, 1, 3, 3) transform = transforms.Compose([ transforms.ToPILImage(), transforms.Resize(size=24), transforms.ToTensor() ]) x = [transform(x_) for x_ in x] torchvision.utils.save_image(x, 'test.png')
Skinish
I am trying to find a way to deal with imbalanced data in pytorch. I was used to Keras’class_weight, although I am not sure what it really did (I think it was a matter of penalizing more or less certain classes).The only solution that I find in pytorch is by usingWeightedRandomSamplerwithDataLoader, that is simply a wa...
ptrblck
You can also apply class weighting using the weight argument for a lot of loss functions. nn.NLLLoss or nn.CrossEntropyLoss both include this argument. You can find all loss functionshere.
jpainam
Hi!I can monitor my GPU and I can see no hit on my GPU. But I get an out of memory error.I even set the batch size to 1. I’m feeding two images of size (224,224); (448,448).Runing of a GPU Quatro K1200RuntimeError: cuda runtime error (2) : out of memory at c:\users\administrator\download s\new-builder\win-wheel\pytorch...
ptrblck
You could use nn.DataParallel to split your batch onto your GPUs.Hereis a good tutorial to get you started.
Adherer
The code is below:import torch import matplotlib.pyplot as plt from torch.autograd import Variable # torch.manual_seed(1) # reproducible N_SAMPLES = 20 N_HIDDEN = 300 # training data x = torch.unsqueeze(torch.linspace(-1, 1, N_SAMPLES), 1) y = x + 0.3*torch.normal(torch.zeros(N_SAMPLES, 1), torch.ones(N_SAMPLES, ...
ptrblck
eval() changes the Module to evaluation, i.e. some layers like Dropout and BatchNorm change their behavior. In the case of Dropout, the connections won’t be dropped but scaled. The curves show the predictions on the test data. As you can see, the “overfitted” model predicts the samples closer t…
DeepCem
hi this is my first post, so if not suitable sorry.basically I am developing a NN that uses images. However, I receive this error:RuntimeError: Given groups=1, weight[5, 3, 436, 436], so expected input[5, 436, 436, 3] to have 3 channels, but got 436 channels insteadI got that legent of weight[batch,channel,h,w], but in...
ptrblck
You can just permute the dimensions: inputs = inputs.permute(0, 3, 2, 1) or change your Dataset to return the input in the right shape.
JuanFMontesinos
Hi there,I was training a model with SGD and decided to move to Adam.I was using batch size 20 for SGD, however max BS i can use with Adam is 2.optimizer = torch.optim.SGD([{'params': model.unet_model.parameters()},{'params': model.audio_s.parameters()}, {'params': model.drn_model.parameters(), 'lr': args.DRNlr}, ...
ptrblck
An increased memory usage for optimizers using running estimates is normal. As the memory usage depends on the number of your parameters, I’m not sure someone already compared it.
inkplay
The code from documentation will give back an error if you addmodel = MyModule()class MyModule(nn.Module): def __init__(self): super(MyModule, self).__init__() self.choices = nn.ModuleDict({ 'conv': nn.Conv2d(10, 10, 3), 'pool': nn.MaxPool2d(3) }) self...
ptrblck
Which PyTorch version are you using? If < 0.4.1, could you try to update and run it again?
Feixiang_Xu
Usually we use DTW(Dynamic Time warpping) to measure the similarity between two variabel voice sequences. However DTW is time-cunsuming and not easy to run in the GPU since too much control in it. I wish to find a deep learning algorithm to measure the similarty. Anybody has ideas? Thanks:)
ptrblck
What kind of input are you using for DTW? Some kind of mel frequency cepstral coefficient? If the DTW works sufficiently well and you have the data, you could try to train a model to predict the DTW score for two voice sequences. If your DTW results aren’t really good, you would have to get someh…
stoneyang
Hi, there:I’ve encountered this problem and got stucked for a while. I have a labeled image dataset in a considerable large scale and I chose to train a vgg16 on it just starting frompytorch’s imagenet example.I firstly organize data into three splits, namely train, val, test; under each of them are bunches of subdirec...
ptrblck
It seems you’ve used nn.DataParallel to save the model. You could wrap your current model again in nn.DataParallel or just remove the .module keys.Hereis a similar thread with some suggestions.
HEIMDAL13
Hello,I have seen that is possible to set diferent learnign rates for diferent layers using Per-parameter options. But in my case, I have a lot of diferent modules, and I only want to set a diferent learnign rate for just a layer.If tried something like this:self._optimizer = optim.SGD([{'params': model.parameters()},{...
ptrblck
You could try to filter out your special layer: optim.SGD([{'params': [param for name, param in model.named_parameters() if 'fc2' not in name]}, {'params': model.fc2.parameters(), 'lr': 5e-3}], lr=1e-2)
Count-Badgerston
I have created a model, trained it, evaluated and saved withtorch.save(model.state_dict(), 'pathToSavedModel')If I create the same model in a different .py file, how can I load the pretrained parameters from an old model to new one so I can evaluate it directly ?Documentation ontorch.loaddoes not give me any insight an...
ptrblck
You can load the state_dict using: model = YourModel() model.load_state_dict(torch.load('pathToSavedModel')) Have a look at theSerialization semanticsfor more information.
string111
Hey there super people!I am having issues understanding theBCELossweightparameter. I am having a binary classification issue, I have an RNN which for each time step over a sequence produces a binary classification. Precisely, it produces an output of size(batch, sequence_len)where each element is in range0 - 1(confiden...
ptrblck
Good to hear. Maybe the new pos_weight argument fornn.BCEwithLogitsLossmight work better, since there is a difference in my weighting approach and the implemented one. Seethis discussion.
skiddles
I am working on a LSTM model and trying to use a DataLoader to provide the data. I am using stock price data and my dataset consists of:Date (string)Closing Price (float)Price Change (float)Right now I am just looking for a good example of LSTM using similar data so I can configure my DataSet and DataLoader correctly....
ptrblck
The SequantialSampler samples your data sequentially in the same order. To use a sliding window, I would create an own Dataset and use the __getitem__ method to get the sliding window. Here is a small example (untested): class MyDataset(Dataset): def __init__(self, data, window): self…
string111
Hey, I wanted to ask if there is a difference of feeding a batch to the model and then update the weights or feeding data solely to the model and sum up the loss and update after the batch size. I am aware that this depends also on the used criterion, but can I do the following example in praxis? (My GPU-mem is too sma...
ptrblck
If you use reduction='sum' in your criterion, the gradients should be the same: model = nn.Linear(10, 2) criterion = nn.NLLLoss(reduction='sum') x = torch.randn(2, 10) y = torch.empty(2, dtype=torch.long).random_(2) # use whole batch loss = criterion(model(x), y) loss.backward() model_grad_batch …
isalirezag
If i have tensorA = torch.rand(30,500,50,50)what is the smartest and fastest way to normalize each layer (the layers in A.size(1)) to have values between a and b.The naive way is:B = torch.zeros(A.size())for b in range(A.size(0)): for c in range(A.size(1)): B[b,c,:,:] = ((b-a)*(A[b,c,:,:]-to...
ptrblck
I haven’t timed the code yet, but it should be faster than for loops: x1 = torch.randn(30, 500, 50, 50) x1_min = torch.min(x, dim=3, keepdim=True)[0].min(2, keepdim=True)[0] x1_max = torch.max(x, dim=3, keepdim=True)[0].max(2, keepdim=True)[0] x2 = (g-f)*(x1 - x1_min) / (x1_max - x1_min) + f
Gaurav_Nayak
While doing hyperparameter optimization using Ray Tune in pytorch, getting the below error:Traceback (most recent call last): File "/home/vsl3/anaconda2/lib/python2.7/site-packages/ray/worker.py", line 891, in _process_task *arguments) File "/home/vsl3/anaconda2/lib/python2.7/site-packages/ray/actor.py", line 2...
ptrblck
I"m not familiar with Ray Tune, but the error seems to come from a call to a bool value: mask = True mask() > TypeError: 'bool' object is not callable
Young-Hoon_Byun
Hi. I’m beginner of pytorch, and I’m trying to version up pytorch from 0.2.0_3 to 0.4.0.Using conda environment, I tried to follow the instruction they gave(https://pytorch.org/)I followed codes they gave, (like conda install pytorch torchvision -c pytorch)the version never changed somehow.(installation worked, but not...
ptrblck
Are you building PyTorch from source? If you don’t need the current master bug fixes and features, it’s simpler to install it using the pre-built binaries. However, if you want to build from source, try to run python setup.py clean before pyhon setup.py install.
ntoan
Is there a simple way to calculate the output size of multiple convolution and pooling layers? I mean the automatical way. Suppose I have 10 such layers, then when I decide to change the first layer, I would need to recalculate the output size of input images fed through the whole 10 layers which is too troublesome.I s...
ptrblck
You can implement such a method in your model class using random input. It should be something like this: def calculate_size(self, input_size): x = torch.randn(input_size).unsqueeze(0) output = self.layers(x) return output.size()[1:] This will use one forward pass to calculate the outp…
brijraj
Hi everyone,I am seeking for optimal steps in order to train my network on Imagenet. As the dataset is very big, I see a single mistake of mine may lead to several more days/hours.Please suggest me a reading on Imagenet-loading and plugging in the model.
ptrblck
In that case you could use loss.data[0] instead. Let me know, if the memory issue disappears.
Losspost
Hi. I am trying to load a model with:import torch import pyautogui as mouse import cv2 from ScreenRecorder import Record,IniRecord,Frame def start(model): sc_ini = Frame() monitor = sc_ini.get() sc = IniRecord(monitor,1.6) while True: frame = sc.getFrame() cv2.imshow('frame',frame)...
ptrblck
You have to call it on your model: model.load_state_dict(torch.load(...))
krishnavishalv
I have a dataset with 100 images which occupy around 120 MB and their masks occupy around 4.2 MB. I have written a dataloader. When I try to plot some examples using the following code, the process is killed because of running out of memory.import torchvision import matplotlib.pyplot as plt from augmentations import * ...
ptrblck
Thanks for the info. I’ll try to debug your code. In the meanwhile could you remove the recursion in __getitem__: return self.__getitem__(np.random.randint(0, self.__len__())) and just return random data instead: return torch.randn(YOUR_SIZE), torch.randn(YOUR_SIZE)
Losspost
Ok it works so far right now. But i get problems with my labels.Apperently the labels have the wrong form?The Error is :torch.Size([10, 3]) Traceback (most recent call last): File "<ipython-input-76-4f1765267e06>", line 1, in <module> runfile('D:/Nextcloud/Python/Gamebot/model.py', wdir='D:/Nextcloud/Python/Game...
ptrblck
You could split the outputs into the regression problem (mouse coordinates) and the classification problem (click/no-click). Both outputs should be passed to the appropriate loss function. Here is a very simple example code you could use as a starter: class MyModel(nn.Module): def __init__(se…
benedikth
Hey guys,I’m implementing some RL and got stuck at a, in my opinion, weird behaviour.I’ll useDataParalleland thedevice-tag to move my Nets/ Data to the available device(s).Using CPU and one CUDA device everything works fine, but if I use more than one device, I’ll get the following error:File “_test_script.py”, line 22...
ptrblck
Could you try to add a batch dimension to your data? For a batch size of 1, your input shape should be [1, in_features]. I assume 72 is your feature dimension. If so, nn.DataParallel might split on the wrong dimension.
lysuhin
Hi, I’m trying to just export base recurrent model to ONNX, but seems like I’m missing something about the dimensions ordering of inputs or so. I have no problems with simple forward pass but do have one attorch.onnx.export.This is my code:import torch import torch.onnx model = torch.nn.GRU(input_size=3, ...
ptrblck
Your code works for my builds 0.5.0a0+4028ff6 and 0.4.0. Which PyTorch version are you using?
TonyMaster
Hello, I’m doing a project about semantic segmentation with 2 class using U-net , but my data was unbalanced, so I think maybe use focalloss is a good idea for my project, and I was use BCEloss, so changed the final layer from 1 channel to 2 channels, and use this codefocalloss2d,but the loss was unchanged during train...
ptrblck
Where did you modify the code? In your first post or the github repo? I’m not sure about this line: label = label[:, :, np.newaxis] Are you trying to add a batch dimension to your target? If so, the batch dimension should be at dim0, i.e. the first dimension. Make sure your label is of type lon…
12_DHH
I tried to extract the feature by adding the VGG16 network to the predicted image and ground truth, and use L1 loss to establish the extracted relationship,ie, L1_LOSS(VGG16(predicted)-VGG16(ground truth)),Screenshot%20from%202018-07-23%2017-56-271155×460 63.5 KBAnd the following error occurredTraceback (most recent ca...
ptrblck
You have to assign the detached tensor: target = target.detach() or alternatively just detach it in the criterion: loss = criterion(output, target.detach())
stanis-morozov
Hello,I am experimenting with resnet34 network in pytorch and I have noticed that sometimes the output of some layers depends on the batch size. Here is my codex1 = torch.rand(100, 3, 224, 224) x2 = x1[0].unsqueeze_(0) x1, x2 = x1.to(device), x2.to(device) resnet = getattr(torchvision.models, 'resnet34')(pretrained=Fa...
ptrblck
Could you try setting torch.backends.cudnn.deterministic = True and run it again? cuDNN might use non-deterministic methods for a larger batch size, bun I’m unsure if that’s the case.
eugene
In a multi-class classification, I sometimes see the following two implementations:nn.Linear+nn.CrossEntropyLossnn.LogSoftmax+nn.NLLLossAre they both the same in terms of the following?Both are softmax classifiersMathematicallyModel training efficiencyAny other differences?What are the trade-offs to consider?If the int...
ptrblck
Both approaches are the same. In fact nn.CrossEntropyLoss just uses nn.LogSoftmax() + nn.NLLLoss() internally.Hereis the line of code. For a binary classification you could use nn.CrossEntropyLoss() with a logit output of shape [batch_size, 2] or nn.BCELoss() with a nn.Sigmoid() in the last lay…
miladmozafari
Hi,I’m using PyTorch tensor library for tensor based computations. I’m implementing a particular type of spiking neural network and I do not use PyTorch’s Network or Module. I just use tensor and its methods plus some functions in nn.functionals.Currently, in order to have a single code capable of running on GPU and CP...
ptrblck
It should be sufficient to move your tensors to the GPU. You can check the current device by printing tensor.device. If your GPU is not fully utilized your code might have some bottleneck or the operations are just too small so that the overhead of moving between host and device is bigger than the…
Paritosh
I am using different Dataloaders for train set and test set, so in all, I have 2 Dataloaders.I do training and testing in every epoch.Is there a way I can free up the Dataloader not being used (for eg. free-up the train dataloader while testing; and free-up test dataloader while training) so as to be able to increase t...
ptrblck
Have you used with torch.no_grad() during your test phase? This will avoid storing the intermediate variables needed for the backward pass, which is not necessary for testing.
mattrobin
I’m often in a situation where on my local machine (without a GPU) my code runs fine, but I’d like to test that all the tensors are added to the correct device if there’s a GPU present. I want to test this before I commit my code, but do so would require deploying it to a remote machine, which are usually running somet...
ptrblck
I’m not aware of a way to simulate a GPU, but you could run an AWS instance to try it out or use a Colab notebook, although I’m not sure about the licensing.
John1231983
I am using batch norm in my network. For each epoch in training, I will perform evaluate loss in validation set. Will the batch norm statistic in train() mode maintain in next epoch because I want to train these statistic? Thanksfor epoch in range of (100): net.train() loss=... loss.backward() optim...
ptrblck
The running statistics will be updated once your model is set to .train() again. Your code snippet looks fine. You could move the net.eval() before the loop through your validation set, but it’s not a problem if you call .eval() repeatedly.
shreyas_kamath
I am trying to use the example given below to construct a custom convolution module which will be used in the network instead of the torch.nn.conv2d.inp = torch.randn(1, 3, 10, 12) w = torch.randn(2, 3, 4, 5, requires_grad = True) inp_unf = torch.nn.functional.unfold(inp, (4, 5)) out_unf = inp_unf.transpose(1, 2).matmu...
ptrblck
You could just derive nn.Module like when creating a model. In the __init__ function you should create your parameters and the forward will perform your computation. Since you used just pure PyTorch methods, autograd will be able to create the backward call.
sebastianwjc
I adopted a 2-layer neural network in the tutorial:model = nn.Sequential( nn.Linear(D_in, H), nn.Tanh(), nn.Linear(H, D_out), )Then I trained the model, save and load the model in the way as they mentionedhere(second answer, case#1). But when the output yields a SyntaxError:File "eval01.py", line 63 mod...
ptrblck
Could you post the code for loading the state dict? Your error is most likely due to a typo, e.g. a missing parenthesis.
inkplay
The below piece of code gives me back really weird data augmented image. There are no other transformations besides the Resize. I am using pytorch 0.40transformed_dataset = data_sets(csv_path=csv_path, image_path = image_path, transform = transforms.Compos...
ptrblck
Could you try to use img = img.permute(1, 2, 0) instead of the view call?
Tank
Is it possible to build a CNN like the following easily in Pytorch?X_train[0:99] -> Con1 -> Conv2 - MaxPool / + X[99:105] -> linear1 -> linear2 ->OuputAs in we are adding more information to the fully connected layers than simply what the conv layers tell us. For example imagine doing NLP on movie reviews but you know...
ptrblck
How would you like to split your input data? Since it seems you would like to use a one-dimensional conv layer, your input should be of shape [batch_size, channels, length]. Are you splitting X_train based on the length? Also, do you want to concatenate the split input? If so, this could be a sta…
Joseph_Santarcangelo
Hello, I have created a data-loader object, I set the parameter batch size equal to five and I run the following code. I would like some clarification, is the following code performing mini-batch gradient descent or stochastic gradient descent on a mini-batch.from torch import nn import torch import numpy as np import ...
ptrblck
In your current code snippet you are assigning x to your complete dataset, i.e. you are performing batch gradient descent. In the former code your DataLoader provided batches of size 5, so you used mini-batch gradient descent. If you use a dataloader with batch_size=1 or slice each sample one by o…
borisbranson
I know this is a very basic question, but it’s my first day with pytorch and I can’t seem to figure it out? What is the difference between no_grad() and requires_grad, and when to use each of them, and when/how to mix them?Thanks guys.Best,Boris
ptrblck
with torch.no_grad() is a context manager and is used to prevent calculating gradients in the following code block. Usually it is used when you evaluate your model and don’t need to call backward() to calculate the gradients and update the corresponding parameters. Also, you can use it to initiali…
Tank
Does anyone know a convenient and easy way to understand whether your NN is suffering from dead RELU’s in Pytorch?
ptrblck
By dead ReLUs you mean a negative input and thus a zero result? If so, you could count the zeros in the output activation. Here is a toy example for a simple model: model = nn.Sequential( nn.Linear(10, 10), nn.ReLU() ) x = torch.randn(10, 10) output = model(x) (output == 0).sum(1).float(…
Tank
I have read the other similar posts but have not been able to solve the issue and get Conv1d to work.Initially I was getting this error: Runtime error: Expected object of type torch.DoubleTensor but found type torch.FloatTensor for argument#2‘weight’.I tried adding a .double() at the end of my nn.Conv1d line but that ...
ptrblck
Your target seems to be still a torch.DoubleTensor. Could you cast it to .float() and try it again?
isalirezag
Let s say I have a list consist of K tensorsL = [ torch.rand(B,C,D,D) for _ in range(K)]for simplicity lets sayB=1I want to find the max value and the corresponding index to the max value of each element.How I can do that in an efficient way?Example:Lets say I have:B = 1 C = 1 D = 3 K = 2 L = [ torch.rand(B,C,D,D) for...
ptrblck
You could use torch.stack instead of torch.cat: L = [ torch.rand(B,C,D,D) for _ in range(K)] print(L) L = torch.stack(L) L.max(0)
lxy
I am a little confused about the padding setting of the torch.nn.ConvTranspose2d.As I see the document, it seems that the padding of the deconvolution is calculated by some settings of convolution.padding(deconv) = K(conv) - 1 - padding(conv)An Example:If I want to upsample x3 using the deconvolution, the setting of t...
ptrblck
You are right. There are several setting for your ConvTranpose layer to achieve the same result. The same goes for the opposite direction: you can get the same output shape using different settings for a Conv layer.This tutorialand alsothese visualizationsmight make things clearer.
Pfaeff
Make a list for each class, take 25% at random from each list, combine the lists and shuffle.
ptrblck
This would split the dataset before using any of the PyTorch classes. You would get different splits and create different Dataset classes: X = np.random.randn(1000, 2) y = np.random.randint(0, 10, size=1000) X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.1, stratify=y) np.un…
Carl
Hello!To work with a remote GPU server running on CentOS 6.9, I had to install pytorch from source (the packaged version as an incompatibility with glibc). I ran 20 batches of my training process with the autograd profiler, and I looked at the trace withchrome://tracing. My local computer, that has a GeForce 1080 Ti, p...
ptrblck
If cuDNN isn’t detected, you could try to specify CUDNN_LIB_DIR (libcudnn.so or something similar should be in the dir) and CUDNN_INCLUDE_DIR (cudnn.h should be in the dir).
isalirezag
I have a baseline (eg VGG) and i want to connect several small models to different place of the baseline.For example for simplicity I am going to do it at the end of my baseline here. Then I want to train and share the losses.I did the following but i am not sure why i got this error.Can you please help/guide meThanksS...
ptrblck
Try to assign the result back to x so that the result from m(x) will be fed to the next module.
JaeGer
Hello ,I’m doing classification using recurrent network and I remember using a metric in SKlearn with random forest that gives the classifier probability of each class , example I have 3 classes this metric gives me the probability of what the classifier thinks this object belongs to which class , Is there a built in f...
ptrblck
If your model returns logits, you could call F.softmax on them, which will yield the class probabilities. Example: import torch.nn.functional as F model = nn.Linear(10, 5) x = torch.randn(1, 10) output = model(x) prob = F.softmax(output, dim=1)
peach_is
jupyter: My output format is just like picture here.1797×138 13.4 KBi wonder how to set to the following format.0.2355 0.8276 0.6279 -2.38260.3533 1.3359 0.1627 1.7314[torch.FloatTensor of size 2x4]thank you!
ptrblck
There was a discussion inthis threadabout this topic. Currently you could just use print(a, a.type(), a.size()).
mnazaal
Hi,I’m working on a problem regarding image segmentation.My input is RGB, and the labels are 4 channels, one for each of the classes. Technically, the first 3 channels form an RGB image and the last channel is added to differentiate between the other 3 classes and the background.A typical input and label combo looks li...
ptrblck
It looks like you tried to permute your label tensor and somehow the dimensions got mixed up. Could you search for code using view, permute or another transformation on your labels, and post these here?
Dr_John
I am using a VGG16 pretrained network, and the GPU memory usage (seen via nvidia-smi) increases every mini-batch (even when I delete all variables, or use torch.cuda.empty_cache() in the end of every iteration). It seems like some variables are stored in the GPU memory and cause the “out of memory” error. I couldn’t so...
ptrblck
You could try to see the memory usage with the script posted inthis thread. Do you still run out of memory for batch_size=1 or are you currently testing batch_size=4? Could you temporarily switch to an optimizer without tracking stats, e.g. optim.SGD?
gt_tugsuu
If i do this, does the “Model” and the “Encoder” have same weights?Or will they become two separate networks?class Encoder(nn.Module): def __init__(self): super(Encoder, self).__init__() self.fc1 = nn.Linear(784, 32) def forward(self, x): return F.sigmoid(self.fc1(x)) class Decoder(nn....
ptrblck
Both will be initialized with their own weights: print(Model.fc1.fc1.weight) print(Encoder.fc1.weight)
cijerezg
I have seen two types of for loops that go through the dataloader.for batch_idx, (data,target) in enumerate(train_loader): train...for data,target in train_loader: train...Is there a difference between those two? If so, what is it?Thanks
ptrblck
In the first one you’ll get the current index of the iteration saved in batch_idx. That’s what the enumerate op is for. It’s often used e.g. if you would like to print some training stats every N batches. Besides that, there is no difference.
hanshu2018
I am new to pytorch. I read the code about how to define a network and call the forward function to generate output.27%20PM512×595 39.1 KBI am confused why “out=net(input)” , instead of “out=net.forward(input)” just like the standard form of calling a function defined in a class?Thanks
ptrblck
When you call the model directly, the internal __call__ function is used. Have a look atthe code. This function manages all registered hooks and calls forward afterwards. That’s also the reason you should call the model directly, because otherwise your hooks might not work etc.
Dr_John
I am using a pretrained VGG16 network (the code is given below). Why does each forward pass of the same image produces different outputs? (see below) I thought it is the result of the “transforms”, but the variable “img” remains unchanged between the forward passes. In addition, the weights and biases of the network r...
ptrblck
Try to set your model to model.eval(). Since you have Dropout layers in your model, the output will change.
Tank
Similar questions have been asked but I have not been able to solve the problem. I am trying to create a CNN over an image with one channel. I keep getting variations of a dimension error. Input Image is of size (99 * 99). Batch size 4.Shape of input is (4 *99 * 99). When I tried to pass this into a CNN I obviously g...
ptrblck
The unsqueeze was necessary, as your channel dimension was missing. Since you are using an image, you should also use nn.MaxPool2d instead of nn.MaxPool1d. Here is a small example: model = nn.Sequential( nn.Conv2d(in_channels=1, out_channels=3, kernel_size=3, stride=1, padding=1), nn.MaxP…
tor
Why did I get None gradients from net.state.dict() as below?Should not the gradient values from net.state.dict() be the same with those from net.named_parameters()?Note: using thisstate_dict()and thisnamed_parameters()net.zero_grad() ypred = net(x) loss = loss_fn(ypred, y) loss.backward() print('### net.named_paramete...
ptrblck
Try to pass keep_vars=True to net.state_dict(keep_vars=True) and it should work. Since the default is set to False, the underlying data of the tensors will be returned and thus detached from the variable.
somnath
3mHow can we use machine learning classifiers like SVM, Decision Tree, Random Forest, etc in PyTorch? Is there any library available?
ptrblck
You could apply these techniques usingscikit-learn. They work an numpy arrays, so if you would like to train an SVM on top of a CNN, you could just get the numpy array from the tensor: output = pytorch_model(x) output = output.numpy()