user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
ToxaDev | UserWarning:Found GPU0 Tesla V100-SXM2-16GB which requires CUDA_VERSION >= 9000 foroptimal performance and fast startup time, but your PyTorch was compiledwith CUDA_VERSION 8000. Please install the correct PyTorch binaryusing instructions fromhttp://pytorch.org……RuntimeError: CUDNN_STATUS_MAPPING_ERRORBut i did install... | ptrblck | How did you install PyTorch?
Did you compile from source or install the pre-built binaries?
You can find the install command on thewebsite.
This should be the command you are looking for:
conda install pytorch torchvision cuda90 -c pytorch |
Dr_John | VGG16 and Resnet require input images to be of size 224X224X3. I know my question may be stupid, but is there any chance to use these pretrained networks on a datasets with different input sizes (for example, black and white images of size 224X224X1? or images of different size, which I don’t want to resize?)Thanks! | ptrblck | In your first use case (different number of input channels) you could add a conv layer before the pre-trained model and return 3 out_channels.
For different input sizes you could have a look at thesource code of vgg16. There you could perform some model surgery and add an adaptive pooling layer in… |
XiaXuehai | I built a model of multi-labels classification. The model like this:class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3)
self.conv2 = nn.Conv2d(32, 32, 3)
self.pool24 = nn.MaxPool2d(2, 2)
self.conv3 = nn.Conv2d(32, 64, 3)
self.conv4 = nn.Conv2d(64, 64, 3)
... | ptrblck | Thanks for the clarification.
So we basically have multiple predictions (7 numbers) using a multi-class classification (not multi-label).
In a multi-label classification, each sample might have more than one target class.
Using license plates this approach seems to be invalid, since neither a sin… |
XiaXuehai | I am new about pytorch.the example like thisinputs = torch.rand(1,1,10,10)
mod = nn.Conv2d(1,32,3,2,1)
out = mod(inputs)
print(out.shape)the output istorch.Size([1, 32, 5, 5])I think new_width = (old_width+2*padding-kernal_size)/stride +1.but it cann’t divisible.So how to calculate it in pytorch? | ptrblck | The complete formula for the output size is given in thedocs. If it’s not divisible, the output size seems to be rounded down.
EDIT:new link to the Conv2d docs. |
XiaXuehai | Code like this:trainset = COCODataset('data.txt', (416,416), True, is_debug=True)
trainloader = DataLoader(trainset, batch_size=8,shuffle=False, num_workers=4)
net = Mynet(file)
if gpu:
net.cuda()
optimizer = optim.SGD(net.parameters(), lr=0.01)
for epoch in range(Epochs):
for i, sample in enumerate(trainload... | ptrblck | The error message seems to point to your RAM, not the GPU memory.
Could you check it with free -h and see how much memory is left?
This particular error message can be triggered, if new processes would like to spawn / fork and there is not enough memory left. |
Naman-ntc | What is the best way to resume a training in pytorch.Saving an optimizer would be necessary since some optimizers store the momentum of gradients along with the current gradients.What is an elegant way to do this? | ptrblck | There is a good example in theImageNet demo. |
dawn | here is my model:class vgg16Net(nn.Module):definit(self):super(vgg16Net, self).init()vgg = models.vgg16_bn(pretrained=True)self.block1 = nn.Sequential(*list(vgg.features.children())[:7])self.block2 = nn.Sequential(*list(vgg.features.children())[7:14])self.block3 = nn.Sequential(*list(vgg.features.children())[14:24])sel... | ptrblck | It looks like you forgot to return x. |
Naruto-Sasuke | My code is based on Pytorch 0.3.I want to take the features of net1(such as, the last layer but one), then feed them to net2.Net1 and net2 should be trained simultaneously. And of course, the gradients from net2 willhave an influence on net1. (I modified the architecture of net2).Here is the toy example:import torch
... | ptrblck | If you need to have more flexibility, you could have a look at forward hooks inthis post.
Since you need the gradients, make sure not to detach the tensor. |
rawwar | I was trying to do the followingimport torch
print(torch.Tensor(2,3))I don’t know why but, some times it works and gives an output, and sometimes it throw’s out the following error.RuntimeError Traceback (most recent call last)D:\softwares\anaconda\lib\site-packages\IPython\core\formatters.... | ptrblck | It seems this bug is fixed in the master branch, although I couldn’t reproduce the issue using 0.4.0.
Maybe I was just lucky with the uninitialized values.
However, you can just use the tensor as you wish. Just avoid printing an uninitialized tensor. |
linyu | Given a M×N×C matrix, I want to calculate the l2-norm of all sub-matrix with size m×n×C, m<M and n<N, then get a (M-m+1)×(N-n+1)×1 matrix. How to effectively implement it in pytorch? Thank you for your attention and answer. | ptrblck | This code should work for your matrix given the kernel size and stride:
kh, kw = 3, 3 # kernel size
dh, dw = 1, 1 # stride
C, M, N = 4, 7, 7
x = torch.randn(M, N, C)
patches = x.unfold(0, kh, dh).unfold(1, kw, dw)
print(patches.shape)
> torch.Size([5, 5, 4, 3, 3])
patches = patches.contiguous().v… |
Dr_John | I want to use VGG16 network for transfer learning. Following thetransfer learning tutorial, which is based on the Resnet network, I want to replace the lines:model_ft = models.resnet18(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 2)
optimizer_ft = optim.SGD(model_ft.parameters()... | ptrblck | For VGG16 you would have to use model_ft.classifier. You can find the corresponding codehere.
Here is a small example how to reset the last layer. Of course you could also replace the whole classifier, if that’s what you wish.
model = models.vgg16(pretrained=False)
model.classifier[-1] = nn.Linea… |
sank | How can i implement a gaussian filter on a image tensor after the last convolutional layer as a post processing step? | ptrblck | You can create a nn.Conv2d(..., bias=False) layer and set the weights to the gaussian weights with:
conv = nn.Conv2d(..., bias=False)
with torch.no_grad():
conv.weight = gaussian_weights
Then just apply it on your tensor. |
JaeGer | Hello ,I’m having a stagnate accuracy on my modelScreenshot%20from%202018-07-02%2016-59-17734×429 80.6 KBmodel_in = MLPModel(input_dim, args.MLP_in_width[0], args.MLP_in_width[1], args.MLP_in_width[2],args.MLP_in_width[2])
if torch.cuda.is_available():
model_in.cuda()
# RNN----------------------------... | ptrblck | Your loss is not decreasing either.
Try to simplify your approach by trying to overfit a single sample.
If the loss approaches zero and you succesfully overfitted your model, we could have a look at other possible errors. If that’s not possible, your model or training procedure has most likely a b… |
JaeGer | Hello ,I have created a neural network like this : F1 = feedforward netwrok --> RNN --> F2 = feedforward netwrok and I want to train them but I’m having issues with my optimizer# MLP_in-----------------------------------------------------------------------
model_in = MLPModel(input_dim, args.hidden_dim_1_in, args.hidd... | ptrblck | You could pass the parameters together with:
params = list(model_in.parameters()) + list(model_RNN.parameters()) + list(model_out.parameters())
optimizer = optim.SGD(params, lr=learning_rate) |
overclock | Greetings I have some errors in the evaluation set in the sense that I sometimes achieve validation accuracies of 127%.I may be an error on cuda, or something?Thanks in advance!def evaluation(model, loader, epoch, mini_batch_size, sequence_size):
model.eval()
test_loss = 0
correct = 0
size_input = mini_... | ptrblck | I think that might be the reason your Dataset length is smaller than the calculated predictions, since your Dataset returns the length of the data using its batch dimension.
Assuming you have 240 samples, the DataLoader will return 10 batches a 24 samples.
len(loader.dataset) will also return 240. … |
danyaljj | Hi there,Apologies if this is a basic question. I did go a bit of search but didn’t find quite what I have in mind.Given a model (the forward function) and a given loss, is it possible to find the gradient in the input layer?For example, takeAllenNLP’s BiDAF model. it has aforwardfunction which defines the network stru... | ptrblck | Do you just want the gradient for the first layer (input layer) or the input tensor?
For the former you can just print the layer’s parameter’s grad, while you would need to set requires_grad=True for the latter:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init_… |
Shani_Gamrian | Using PyTorch 0.1.12 and trying to multiply two matrices in the following sizes: [1,49,1] and [1,49,256], but when I do I get the error:RuntimeError: inconsistent tensor sizeI tried using.expand_asfor both matrices but it didn’t work.(I know that it works on newer versions) | ptrblck | I’ve tested it in my 0.1.12 environment and it should work like you tried it:
a = torch.randn(1, 49, 1)
b = torch.randn(1, 49, 256)
c = a.expand_as(b) * b |
linyu | I know how to define conv parameter or fc parameter. Now, I want to define a parameter matrix W×H, and it can be learned like conv parameter. How can I do this?Thank you for your attention and answer! | ptrblck | You can register parameters in your model with nn.Parameter.
Alternatively, if you would like to train your parameter outside of a model, you could just use torch.randn(..., requires_grad=True). You can find an examplehere. |
Raul_Gombru | I want to build a CNN model that takes additional input data besides the image at a certain layer.To do that, I plan to use a standard CNN model, take one of its last FC layers, concatenate it with the additional input data and add FC layers processing both inputs.The code I need would be something like:additional_data... | ptrblck | Here is a small example for your use case:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.cnn = models.inception_v3(pretrained=False, aux_logits=False)
self.cnn.fc = nn.Linear(
self.cnn.fc.in_features, 20)
… |
dagcilibili | In the DCGAN example that can be foundhere, while training the generator network after training the discriminator network, we do not performnetG.zero_grad()again. However, doesn’t this accumulate the gradients with respect torealdata in thenetD(line 208), or the gradients with respect to the previous feeding offakedat... | ptrblck | In the update step of the discriminator (line 208), the generator does not get the data, so the backward step does not calculate any gradients for it.
In line 217 the input to the discriminator is detached as you already observed. Thus the backward call of errD_fake also does not calculate the grad… |
Shani_Gamrian | How to convert the following batch normalization layer from Tensorflow to Pytorch?tf.contrib.layers.batch_norm(inputs=x,
decay=0.95,
center=True,
scale=True,
is_training=(mode=='train'),
... | ptrblck | Based on thedoc, let’s try to compare the arguments.
decay seems to be 1-momentum in PyTorch.
center and scale seem to be the affine transformations, (affine in PyTorch).
is_training can be achieved by calling .train() on the Module.
I’m not sure, what updates_collection, resuse and scope mean … |
coltonoppa | I’m a total newbie and I’ve got this message below right before finishing PyTorch installation. Can anyone please tell me what is wrong with this?(base) C:\Users\Ju Hong Min>conda install pytorch cuda91 -c pytorchSolving environment: donePackage Planenvironment location: C:\ProgramData\Anaconda3added / updated specs:- ... | ptrblck | Did you install conda as admin? The “permission denied” error seems to be pointing to it.
Could you run the terminal as an admin and try it again? |
lpinto | I am trying to train on around 200G of .npy files. I have a custom image class:class CustomImageFolder(ImageFolder):
def __init__(self, root, transform=None):
super(CustomImageFolder, self).__init__(str(root),transform)
def __getitem__(self, index):
path = self.imgs[index][0]
img = np.load(path)
img /=... | ptrblck | Sure! You don’t need to inherit from ImageFolder.
Just create your own Dataset and load your numpy arrays as you want:
class MyDataset(Dataset):
def __init__(self, root, transform=None):
self.image_paths = os.glob.(... # get your numpy array paths here
def __getitem__(self, index)… |
Saeed_Izadi | Hi All,In the data preparation phase for my network, I read an image one at a time, and then, I want to extract several patches from this image as my mini-batch. In other words, the data preparation consists of two steps: 1) read an image and 2) extract random patches to form the mini-match.What’s the proper way to use... | ptrblck | You could just sample in __getitem__ and stack the patches into the batch dimension:
Here is a small example sampling 5x5 patches. These patches are returned as a 4-dimensional tensor from __getitem__. During the training you could push these patches into the batch dimension with view.
class MyDat… |
M_Researcher | Hello,I was wondering how to handle 2D input data while doing a 1D convolution in PyTorch. This nice answer handles three situations:https://stats.stackexchange.com/questions/292751/is-a-1d-convolution-of-size-m-with-k-channels-the-same-as-a-2d-convolution-o/292791I am interested in the second example: I have multiple ... | ptrblck | The second example is using basically a 2D convolution where the kernel height is equal to the input height.
This code should yield the desired results:
batch_size = 1
channels = 1
height = 3
length = 10
kernel_size = (height, 5)
x = torch.randn(batch_size, channels, height, length)
conv = nn.Co… |
lpinto | I’m trying to deconvolute a 3d image. I want the z-axis to remain the same while increasing the x,y image dimensions by a multiple of 2, so effectively just doubling the size.When I am normally convolving and compressing an 8x96x96 (batch of 64 images) like so:nn.Conv3d(nc, 32, 3, (1,2,2), 1)
nn.Conv3d(32, 32, 3, (1,2,... | ptrblck | This code might help:
x = torch.randn(1, 256, 1, 3, 3)
conv = nn.ConvTranspose3d(in_channels=256,
out_channels=64,
kernel_size=(1, 4, 4),
stride=(1, 2, 2),
padding=(0, 1, 1),
… |
isalirezag | I am changing the vgg code from:‘’‘VGG11/13/16/19 in Pytorch.’‘’import torchimport torch.nn as nnfrom torch.autograd import Variableimport syscfg = {‘VGG19’: [64, 64, ‘M’, 128, 128, ‘M’, 256, 256, 256, 256, ‘M’, 512, 512, 512, 512, ‘M’, 512, 512, 512, 512, ‘M’],}device = torch.device(“cuda:0” if torch.cuda.is_available... | ptrblck | You are reusing the BatchnNorm2d layers in your second approach, while you create new ones in the first approach:
Out = self.ReLUU(self.BatchNorm_64(self.conv1_1(x)))
Out = self.MaxPool(self.ReLUU(self.BatchNorm_64(self.conv1_2(Out)))) |
Jindong | Hi, every one,I am using the sampler for loading the data with train_sampler and test_sampler, but with this method, I have to set the shuffle as False, is there some other way that i can use the train_sampler or test_sampler for data loading in the mean time I can keep the shuffle as True?Thanks | ptrblck | You would have to implement shuffling into your sampler.
Have a look at the implementation ofRandomSampler. |
Shisho_Sama | How can I save the scheduler state ?I tried :temp = scheduler.state_dict()
temp['last_epoch']=36but got the errorAttributeError: ‘MultiStepLR’ object has no attribute ‘state_dict’The reason I’m trying this is , I forgot to save the scheduler setting along with other needed info when saving the checkpoint! so now th... | ptrblck | This code works for PyTorch 0.4.0:
optimizer = optim.SGD([torch.randn(10, requires_grad=True)], lr=1e-1)
scheduler = optim.MultiStepLR(optimizer, [5, 10], 0.1)
print(scheduler.state_dict())
Which version are you using? |
Ryobot | How should EncoderDecoder with mixin of Encoder and Decoder be implemented?In the following snippetself.encis not registered as a module.class Encoder(nn.Module):
def __init__(self):
super().__init__()
self.enc = nn.Linear(2,2)
class Decoder(nn.Module):
def __init__(self):
super().__ini... | ptrblck | You could remove the super(Encoder, self).__init__().
Generally you could inherit from multiple classes, but I think it would be easier to just register the Modules in EncoderDecoder:
class Encoder(nn.Module):
def __init__(self):
super(Encoder, self).__init__()
self.enc = nn.Li… |
ptrblck | The hooks should be already registered withhybrid_cnn's augmented modules.Could you post the complete error message? | ptrblck | Thanks for the code.
Your return statement is at the wrong place.
get_activation should return hook, not hook itself:
Right way:
def get_activation(name):
def hook(model, input, output):
activation[name] = output.detach()
return hook
Your current implementation:
def get_activat… |
somnath | Using PyTorch, I am able to create an autoencoder like the one given below. How do I save the output matrix to a .csv file after every layer?class Autoencoder(nn.Module):
def __init__(self, ):
super(Autoencoder, self).__init__()
self.fc1 = nn.Linear(10000, 5000)
self.fc2 = nn.Linear(5000, 20... | ptrblck | You can use@Supreet’s code to return the outputs (just add commas between the returned tensors).
Once you grab the outputs, you could save them to a .csv.
Here is a small example:
class Autoencoder(nn.Module):
def __init__(self, ):
super(Autoencoder, self).__init__()
self.fc1… |
Alex_Sugar | Hey All, I’m learning how to use pytorch and am wondering what the best way to do the following is:in a custom module, I have an intermediate tensor that has a shape like [2,8,16], I’d like to apply a linear layer transform, say from 8 -> 4, in the middle dimension and get out a tensor of shape [2,4,16]. The obvious wa... | ptrblck | You could permute the dimensions and just apply a linear layer:
x = torch.randn(2, 8, 16)
x = x.permute(0, 2, 1).contiguous()
lin = nn.Linear(8, 4)
output = lin(x)
Thedocsexplain the behavior of the input and output shapes. |
inkplay | I would get the errorRuntimeError: Expected tensor for argument #1 'input' to have the same dimension as tensor for 'result'; but 4 does not equal 2 (while checking arguments for cudnn_convolution)If I run the code below. Quick googling returns various issues that cause this. I assume Pytorch doesn’t like the 9 in chan... | ptrblck | Your input to the last conv layer is [batch_size, 512, 2, 2] which is too small for a kernel size of 4.
Change the last layer to nn.Conv2d(opt.ndf*8, 1, 2, 1, 0, bias=False) and your model should run. |
ks7g2h3 | I’m building a model that does the following: (i) breaks an image up into small square windows, (ii) applies a network to each window, transforming each into an output window of the same size, and (iii) reassembles the output windows into an output image of the same size as the input image. I’m wondering if there’s an ... | ptrblck | Do the small windows overlap? If so, you would have to think about a method to unite them (summing, mean, etc.).
If not, you could try the following:
channels = 1
h, w = 12, 12
image = torch.randn(1, channels, h, w)
kh, kw = 3, 3 # kernel size
dh, dw = 3, 3 # stride
patches = image.unfold(2, kh,… |
Naman-ntc | I was thinking that would it be better to store and load images present as tensors?In general I load images with opencv or PIL and converting them to tensors, if I converted my data into tensor and dump them would it be faster while loading?? | ptrblck | If you don’t want to transform your images, you could load them as tensors.
However, if you do need a transformation, you would have to transform the tensors back to PIL.Images, apply the augmentation/transformation, and transform them back to tensors.
This shouldn’t be too bad regarding the perfo… |
Jindong | Hi, every one,I have a question about the “.cuda()”. In an example of Pytorch, I saw that there were the code like this:criterion = nn.CrossEntropyLoss().cuda()In my code, I don’t do this. So I am wondering if it necessary to move the loss function to the GPU.Thanks | ptrblck | Additionally to what@royboysaid, you need to push your criterion to the GPU, if it’s stateful, i.e. if it has some parameters or internal states.
Usually loss functions are just functional so that it is not necessary. |
Naruto-Sasuke | 4D1E6621519DC40F0FD85FE766B719C61308×504 93.2 KBI download pytorch from this link and get it installed in my server. It works fine in a test file. However,LD_LIBRARY_PATHcontains nocudnn. I wondering pytorch installed in this way get no utilizationof cudnn lib, leading to the slow training in DNNs.If I add tocudnnpath... | ptrblck | You can print the version with:
print(torch.backends.cudnn.version())
The wheels come with some pre-built libraties (CUDA, cuDNN, etc.). |
Dr_John | In thePytorch transfer learning tutorial, the following line of code appears:scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)and during the model training:scheduler.step()I can’t find the documentation of lr_scheduler (only the method itself). Will someone please help me understand what exactly doe... | ptrblck | The learning rate scheduler adjusts the learning rates stored in the optimizer.
In your example a step function is used to lower the learning rate after 7 steps with a multiplicative factor of gamma=0.1.
Assuming that your initial learning rate is 1e-1:
optimizer = optim.SGD(model.parameters(), l… |
Oktai15 | I want to stack list of something and convert it to gpu:torch.stack(fatoms, 0).to(device=device)As far as I know, tensor was created on cpu firstly and then would be transferred to specified device. How to put it on gpu straight? | ptrblck | If your fatoms list contains CPU tensors, then your example is the way to go.
You could push the content onto the GPU before calling torch.stack, which is what my example shows. |
Pramodith | I’m using the snippet given below to measure the amount of time each batch takes to load.st_batch= time.time()
torch.cuda.synchronize()
for cnt, batch in enumerate(train_data_loader):
torch.cuda.synchronize()
end_batch= time.time()
print(end_batch-st_batch)
... | ptrblck | Are you using multiple workers in your DataLoader?
If so, could you try to increase the number?
It looks like your training procedure has to wait sometimes for the DataLoader to provide new batches. Also, is your data locally on an SSD? |
rbunn80110 | I have been working on what I think should be a ridiculously simple problem. Let’s say I have a 2D matrix 5x5. I would like to take each 3x3 patch, flatten the patch (to 9 elements), then put the flattened patch through a network that spits out a single number. So the 5x5 matrix should become a 3x3 matrix. Each ind... | ptrblck | You are not missing anything and your explanation seems fine.
As@bdhsaid, it’s comparable to a conv or pooling layer.
Here is a small example for your use case:
image = torch.randn(1, 1, 5, 5)
kh, kw = 3, 3 # kernel size
dh, dw = 1, 1 # stride
patches = image.unfold(2, kh, dh).unfold(3, kw, dw… |
Stefan_Modl | Hello together,At first: This is my first question at the forum and I am not a native speaker so please forgive me if I make some mistakes.so here is my code:import…data = np.random.rand(3,3,1)*255print(data)[[[244.41737097][107.10737004][ 58.35949555]][[113.9660475 ][219.29274698][196.0943086 ]][[226.91415229][152.049... | ptrblck | Currently the division by 255. is done, when the transformation assumes an image.
Using a np.array this is done by checking against the dtype.
If you pass a np.uint8 array into the transformation, it will be scaled.
You can find the line of codehere.
data = np.array(np.random.rand(3, 3, 1) * 25… |
JaeGer | Hello ,New to PyTorch and deep learning I have Four questions :1- Is it better to scale all your data then split to training and testing sets or do it otherwise.2- How to use effectively use data augmentation3- I have missing values in my datasets NaN I just removed the lines where they appeared (8 out of 9230) so im m... | ptrblck | I assume scaling is done for normalization. If so, you should split your data first and then scale it. Otherwise you will leak the test information into your training procedure.
Have a look at theData loading tutorial. Basically you create a Dataset and add your data augmentation in the __geti… |
iAvicenna | I noticed that there is a weird slow down of the training phase when I accumulate the losses using .item() instead of .data[0] (note I am testing this code on google colab GPU). The network is a relatively simple CNN:import torch
import time
from torch.autograd import Variable
import torchvision
from torchvision import... | ptrblck | I think your timing might give weird results, because your synchronization points are different in both implementations.
Calling .item() on a tensor gives you a standard Python number, which is pushed to the CPU.
This line of code would add a synchronization to wait for the GPU to finish calculati… |
iAvicenna | Assume you have a tensor y of size M x 10 and another tensor x of size M. The values of both x and y are integers between 0 and 9.I want to get a new tensor z of size M which is of the following form:z[k]= y[k][x[k]]Is it possible to do this without using a for loop? | ptrblck | You could use torch.gather for this:
M = 10
y = torch.empty(M, 10, dtype=torch.long).random_(10)
x = torch.empty(M, dtype=torch.long).random_(10)
w = torch.gather(y, 1, x.unsqueeze(1))
w = w.view(-1)
z = torch.zeros(M, dtype=torch.long)
for k in range(M):
z[k] = y[k, x[k]]
print((z == w)) |
Bixbeat | Hi all,Couldn’t find a better title for this, so I’ll explain it here:I have a tensor with model outputs, e.g. in the shape [5, 3].I’m trying to retain only a few of these, e.g. indices 2 and 4.I’ve tried using torch.masked_select() to retain these entries, but it requires a 1D vector to operate over.What alternatives ... | ptrblck | I’m not really understand, what kind of indices you would like to slice.
Are the indices in dim0?
If so, you could just use:
outputs = torch.randn(5, 3)
outputs[[2, 4], :] |
ElleryL | Consider I have a input dataX = torch.Tensor(sample_size,dim1,dim2)For each data point, its a matrix form with dim1xdim2Now when I feed into neural network withnn.Linear(input_Dim,hidden_dim)I haveoutput = input.matmul(weight.t())
RuntimeError: size mismatch,This makes sense because forward only does operation of matri... | ptrblck | You can add additional dimensions like this:
batch_size = 10
add_features = 5
in_features = 7
out_features = 12
x = torch.randn(batch_size, add_features, in_features)
lin = nn.Linear(in_features, out_features)
output = lin(x)
Is this what you are looking for? |
yoelshoshan | The first thing that happens in my model forward method is calling checkpoint few times using several feature extractors.However, I get the following warning:UserWarning: None of the inputs have requires_grad=True. Gradients will be None
warnings.warn("None of the inputs have requires_grad=True. Gradients will be Non... | ptrblck | A small update. I’m reading atutorial on checkpointing modelsfrom the original author@Priya_Goyaland this part seems to be interesting for your use case:
NOTE: In case of checkpointing, if all the inputs don’t require grad but the outputs do, then if the inputs are passed as is, the output of… |
Rajarshi_Banerjee | Suppose you have a Tensor a = [n, 3, h, w] and another tensor b = [n, h, w]And you want to do this:torch.stack((torch.bmm(a[:,0,:,:],b), torch.bmm(a[:,1,:,:],b), torch.bmm(a[:,2,:,:],b)), dim=1)is there any better way of doing that that is applying torch.bmm() on tensors where the batches have channels but each channel... | ptrblck | You could add an additional dimension at dim1 in b and let broadcasting do the rest:
a = torch.randn(10, 3, 24, 24)
b = torch.randn(10, 24, 24)
c = torch.stack((torch.bmm(a[:,0,:,:],b), torch.bmm(a[:,1,:,:],b), torch.bmm(a[:,2,:,:],b)), dim=1)
d = torch.matmul(a, b.unsqueeze(1))
(c == d).all… |
AreTor | I’ve seen that in many models there are layer parameters named like'features.0.weight'/'features.0.bias'and'features.3.weight'/'features.3.bias', skipping numbers 1 and 2. Why are they skipped? | ptrblck | Maybe because the layers 1 and 2 are nn.ReLU() and nn.MaxPool2d.
Not easy to tell without a model definition, but this might be the case. |
bb417759235 | I built a C3D network.self.conv1 = nn.Conv3d(3, 64, kernel_size=(3, 3, 3), padding=(1, 1, 1))self.pool1 = nn.MaxPool3d(kernel_size=(1, 2, 2), stride=(1, 2, 2))self.conv2 = nn.Conv3d(64, 128, kernel_size=(3, 3, 3), padding=(1, 1, 1))self.pool2 = nn.MaxPool3d(kernel_size=(2, 2, 2), stride=(2, 2, 2))…When I enter the colo... | ptrblck | Your last error message might be a misleading error due to a missing batch dimension in your input.
It has been fixed inmaster.
Could you unsqueeze at dim0 and try it again? |
John1231983 | I have a target with size ofNxHxW, where N is batch size. I want to make one hot encoding with the output size ofNxCxHxWfor image segmentation.def one_hot(targets):
targets_extend=targets.clone()
targets_extend.unsqueeze_(1) # convert to Nx1xHxW
one_hot = torch.cuda.FloatTensor(targets_extend.size(0), C... | ptrblck | I would stick with .clone, since .detach still uses the same underlying data.
Your inplace unsqueeze_ will therefore also unsqueeze targets:
x = torch.ones(10)
y = x.detach()
y.unsqueeze_(0)
print(x.shape)
> torch.Size([1, 10])
print(y.shape)
> torch.Size([1, 10])
May I ask, why you need the BCEL… |
uhotspot4 | I was wondering if there was any sort of issue with torch.optim.lr_scheduler.ReduceLROnPlateau in version 0.3.1b0+2b47480!!!Since as soon as I switch to using scheduler my loss stays almost constant!Here is the code I am using:optimizer = torch.optim.Adam(model.parameters(), lr=0.00003)
scheduler = torch.optim.lr_sched... | ptrblck | You still have to call optimizer.step().
The scheduler will just adjust the learning rate. It won’t perform the weight updates. |
stefdoerr | Hi, what I am trying to do is the following:I have a data array A (n, m) and an index array I of same size (n, m) and a result array R (x, n).I am trying to scatter elements of A into R while also summing up all values which scatter to the same index.This can be done in numpy for example in 1D arrays using np.histogram... | ptrblck | You could achieve this with tensor.scatter_add_:
A = torch.tensor([[0.7, 1.3],
[56.1, 7. ]])
I = torch.tensor([[1, 2],
[0, 0]])
torch.zeros(2, 3).scatter_add_(1, I, A) |
ptrblck | For 3d convolutions your input should have the dimensions[batch_size, channels, depth, height, width].The convolution will be applied on the channels like in the two dimensional case.I think it depends on your use case, whatzexactly means. Are you working with medical images? | ptrblck | Ah sorry, my bad! I just added my batch size of 1 to the View() layer.
You should change it to:
encoder:
View((batch_size, -1))
decoder:
View((batch_size, -1, 3, 3))
Unfortunately, you cannot use x.size(0), since the layer is defined in a Sequential, so you have to know your batch size beforehan… |
AreTor | Suppose I have a 3d Tensorx, and I runitorch.topk(x, k=2, dim=0)[1]to retrieve the indices of the first two max values over the 0th dimension.Then I want to use those indices to index the tensor to assign a value, however I am not able to define the code to perform the correct advanced indexing, The only thing I was ab... | ptrblck | Would this work:
x = torch.randn(3, 10, 10)
idx = torch.topk(x, k=2, dim=0)[1]
x.scatter_(0, idx, 100)
print(x) |
Dr_John | I am new with Pytorch, and will be glad if someone will be able to help me understand the following (and correct me if I am wrong), regarding the meaning of the command x.view in Pytorch first tutorial:https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html( def forward(self, x):x = self.pool(F.relu(self.... | ptrblck | Your explanation is right in general.
Just some minor issues:
In PyTorch, images are represented as [channels, height, width], so a color image would be [3, 256, 256].
During the training you will get batches of images, so your shape in the forward method will get an additional batch dimension at… |
tejus-gupta | import torch
from skimage import io
img = io.imread('input.png')
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
img =torch.tensor(img, device=device).float()
print(img.device)Outputcuda:0
cpuI am not able to convert a numpy array into a torch tensor on GPU. What is the right wa... | ptrblck | You should transform numpy arrays to PyTorch tensors with torch.from_numpy.
Otherwise some weird issues might occur.
img = torch.from_numpy(img).float().to(device) |
mario98 | I trained a model with among others had the following layer:final_layer.append(nn.Conv2d(64, 1, kernel_size=1))and then saved it to a file with state_dict and torch.save.Then, when I wanted to load that model using load_state_dict, but by accident the same layer was setup as follows:final_layer.append(nn.Conv2d(64, 32,... | ptrblck | Can reproduce this issue with:
path = './test_model.pth'
model = nn.Conv2d(64, 1, 3, 1, 1)
torch.save(model.state_dict(), path)
model = nn.Conv2d(64, 32, 3, 1, 1)
model.load_state_dict(torch.load(path))
for w in model.weight[:, :, 0, 0]:
print(w)
Seems like an unwanted behavior to me. |
ravitejajnv | I’ve a custom model which I’ve saved as model_dict (which I saved as a .pth file) after training. Now I want to use it as feature extractor. How can I do this?network architecturePlease see the model architecture from the above link.Specifically I want to extract the features of the colored layer. can someone point out... | ptrblck | Based on your image, it looks like your model has two different feature extractors, which are concatenated and passed into another module.
Depending on your model definition, you could just change the forward pass and return the features from the first feature extractor.
I’ve created a simple exam… |
tremblerz | I know it might be duplicate of many of the existing issues already here on this forum but I wasn’t able to figure out problem with my code. I’ve reduced my intricate codebase to the following simple snippet.class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.l1 = torch.ze... | ptrblck | You should register the model parameters as nn.Parameter. Otherwise the tensors won’t be properly registered.
Alternatively, you could call register_parameter on the tensors.
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.l1 = nn.Parameter(torch.… |
BradMcDanel | I am trying to apply a different threshold to each input channel (e.g., similar to PReLU with \alpha set to nChannels), but the thresholds do not need to be learned. So far I have the following, but it is too slow due to the for loop.class ChannelwiseThreshold(nn.Module):
def __init__(self):
super(Channelwi... | ptrblck | I’m not sure what your shapes are, but could this work?
a = torch.randn(3, 2)
th = torch.randn(3, 1)
print(a)
> tensor([[ 1.1200, -0.1365],
[-0.1328, 0.0842],
[-0.5945, 0.6210]])
print(th)
> tensor([[-0.7215],
[ 1.1406],
[-0.4683]])
idx = (a > th).float()
print(a… |
bewagner | I ran into a rather curious problem while trying to implement thissemi-supervised representation learning algorithm(tl;dr Pretrain a CNN by letting it solve jigsaw puzzles. Each image gets cut into nine tiles. These tiles are permutated with a precalculated permutation and the net has to predict the index in the permut... | ptrblck | I think it’s related to the multiprocessing behavior in Windows.
You should wrap your whole code in another function and guard it:
def run():
for epoch in ...
train(...)
if __name__=='__main__':
run()
I’m wondering why you won’t get a Broken Pipe error, which is usually thrown i… |
tkit1994 | DataLoader behaves the same at every epoch with np.randomIn my code, I need to usenp.random.randint()to random crop my data.Howevery, the random number generated at every epoch is the same.I think it shoud be different. Does DataLoader setnp.random.seed()at the beginning of each epoch? I will post my simplified code be... | ptrblck | This is a knwon issue and is explained in the notes of theDataLoader doc.
You should use worker_init_fn to seed other libraries like numpy. |
nmxnql | I am a pytorch learner ang i want to finetune xception network .When i run the following :import pretrainedmodels
model_name = 'xception'
model_ft=pretrainedmodels.__dict__[model_name]\
(num_classes=1000, pretrained='imagenet')i get the follwing error:RuntimeError: Error(s) in loading state_dict for Xception:
... | ptrblck | Thanks for the link. It’s aknown issuein the repo with a posted workaround. The author,@Cadene, is apparently working on it. |
unnir | I would like to know, if there is a way to reset weights for a PyTorch model.Here is my code:class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 16, kernel_size=5)
self.conv2 = nn.Conv2d(16, 32, kernel_size=5)
self.conv3 = nn.Conv2d(32, 64,... | ptrblck | Sure! You just have to define your init function:
def weights_init(m):
if isinstance(m, nn.Conv2d):
torch.nn.init.xavier_uniform(m.weight.data)
And call it on the model with:
model.apply(weight_init)
If you want to have the same random weights for each initialization, you would need … |
Soumyadeep | I am trying to use my custom dataset and hence downloaded the the code data_loading_tutorial available in the Pytorch tutorials.The code works fine till the line:transformed_dataset = FaceLandmarksDataset(csv_file=‘faces/face_landmarks.csv’,_ root_dir=‘faces/’,_transform=transf... | ptrblck | You could add this line at the bottom of your code, if you wrap the other code into the run() function.
Alternatively, you could wrap your whole code into the if-statement.
The important point is, that your main code should be executed inside this if-statement.
Otherwise Windows will execute the … |
lizhidan | I just written a simple model to classify cifar10 like below method:https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#sphx-glr-beginner-transfer-learning-tutorial-pyAnd I ran it twice,with the same seed:torch.manual_seed(60)
torch.cuda.manual_seed(60)and I set dataset loadershuffle=Falsewithout any... | ptrblck | Looks good to me. To search for the problematic part, could you repeat this procedure with random tensors as input, i.e. don’t use your Dataset and DataLoader?
Since you are seeding, the random tensor should be the same in each run. |
ptrblck | Are your predictions negative?You could check if with(output_batch < 0.0).any()If so,torch.logwill returntensor(nan.). | ptrblck | Ah ok, thanks for the info.
It looks like a standard segmentation task.
I would suggest to use nn.CrossEntropyLoss for your use case.
Have a look at the following code snippet:
n_class = 10
preds = torch.randn(4, n_class, 24, 24)
labels = torch.empty(4, 24, 24, dtype=torch.long).random_(n_class)… |
nullgeppetto | Hi all,I am new to PyTorch (have some good experience in Theano/Lasagne), and I am trying to build an SSD-like architecture.I define the following class (apologies for its length):class SSD(nn.Module):
def __init__(self, init_weights=True):
super(SSD, self).__init__()
# ===========================... | ptrblck | You could create a method to load your weights.
I created a small example for you.
You could definitely write the code in a more compact way, so this should be a starter only.class SSD(nn.Module):
def __init__(self, init_weights=True):
super(SSD, self).__init__()
# ========… |
aleurs | I have two datasets each of 142.000 images, one for training and one for validation. What I have implemented is that it goes through the train data set (batchsize 11) and trains.But what I now want to do is the following:train on the first images 11 images of the train setvalidate the model on the first 11 images from ... | ptrblck | If your Datasets have the same sizes, which seems to be the case, you could just iterate both DataLoaders in the for loop.
Note that the indices for each loader might be different if you use shuffling.
train_dataset = TensorDataset(torch.randn(100, 3, 24, 24))
val_dataset = TensorDataset(torch.ran… |
tpostadj | I am training a custom patch-based network (4 layers) and I realized that, unless I set the lr to 0.0000001 to start converging somehow.I feel like something is wrong with such a tuning.However, if I run the training with lr = 0.01, loss will get huge, like several billions and eventually NaN.Can this be related to ini... | ptrblck | From skimming your code, it looks like you are not zeroing out the gradients after the weight update.
In this case the gradients get accumulated and the weight updates will be quite useless.
Add this line into your for loop and run it again:
self.optimizer.zero_grad()
It is also recommended to c… |
tpostadj | I am trying to train a fully convolutional net from scratch for a semantic segmentation task, but the training set I have is sparse, meaning that I have to ignore pixels that do not contain information (label=0) while training.Otherwise, I have 5 classes I am interested to retrieve.To achieve that, I just added the arg... | ptrblck | The ignore_index argument just masks the loss for the current class.
From the docs:
ignore_index (int, optional) – Specifies a target value that is ignored and does not contribute to the input gradient. When size_average is True, the loss is averaged over non-ignored targets.
If you would like … |
Oktai15 | batch_in = torch.zeros((3, 3, 1))
batch_in[0] = torch.Tensor([1, 2, 3])
batch_in[1] = torch.Tensor([1, 2, 0])
batch_in[2] = torch.Tensor([1, 0, 0])I got error:RuntimeError: The expanded size of the tensor (1) must match the existing size (3) at non-singleton dimension 1Why? | ptrblck | The dimension of batch_in[0] is [3, 1], so you have to make sure to assign a tensor with the same dims:
batch_in[0] = torch.Tensor([[1], [2], [3]]) |
dragen | For a self-defined nn.Module, we can easily convert between cpu and cuda by means of.to(device)if our variable is defined as :class MyModule(nn.Module):
def __init__():
var1 = nn.Parameters()
var2 = nn.register_buffer()However, sometimes, it’s can NOT work if in run-time code, such as :class MyModule(nn... | ptrblck | You could try to use the device property of another parameter:
class MyModule(nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.fc1 = nn.Linear(1, 1)
def forward(self, x):
return x
def get(self):
device = self.fc1.weight.devi… |
Michael_Petrochuk | Hi There!Can something like this list of Conv1d layers be achieved using a single Conv2d or Conv2dTransposed? I tried thinking really hard but was unable to think of something clever!assert in_channels < out_channels
assert features.shape == (batch_size, in_channels, signal_length)
convs = nn.ModuleList(
[nn.Conv1... | ptrblck | Thanks for the updated code!
I think this should even be possible with a Conv1d using out_channels=out_channels*num_layers and a view on the result tensor.
I created a small example which demonstrates this approach.
For an easy comparison of both methods I set bias=False and initialized the weigt… |
Alberto167 | Hello,Does anyone know how to split batches of tensors in different positions each?I am trying to separate my tensors in two parts according to thesplit_position, which is different for each samplebatch.shape = torch.Size([128, 68, 1]) # (batch_size, max_len, 1)
split_positions.shape = ([128]) # split ... | ptrblck | Ok, thanks for the info.
I don’t know an elegant way to achieve your results.
If your results would look like this:
l = tensor([10, 3, 1, 0, 0, 0, 0, 0, 0, 0]),
m_l = tensor([0, 0, 0, 20, 4, 0, 0, 0, 0, 0,])
, i.e. there the zeros in front of the right part, you could use .scatter_().
In case … |
liangbright | I am using PyTorch 0.4import torchX=torch.randn((100,3))Y=torch.randn((100))w1=torch.tensor(0.1, requires_grad=True)w2=torch.tensor(0.1, requires_grad=True)w3=torch.tensor(0.1, requires_grad=True)W=torch.tensor([0.1, 0.1, 0.1], requires_grad=True)W[0]=w1 * w2; W[1]=w2 * w3; W[2]=w3 * w1#W=torch.cat([w1.view(1),w2.vie... | ptrblck | You can read a nice explanation of leaf variables inthis post.
Usually you have to avoid modifying a leaf variable with an in-place operation.
I haven’t seen your error message yet, but it seems it related to an in-place modification, because you are re-assigning the values of W in this line:
W[… |
Hunbo | This is my new dataset class:class MyDataset(Dataset):
def __init__(self, root_dir_img, root_dir_gt, transform=None):
self.root_dir_img = root_dir_img
self.root_dir_gt = root_dir_gt
self.transform = transform
self.img_names = [os.path.join(root_dir_img, name) for name in os.listdi... | ptrblck | Add the following line:
elif mask.mode == '1':
img2 = torch.from_numpy(np.array(mask, np.uint8, copy=False)) |
wfpytorch | Hi there,The problem is the gradient is None on my custom loss (Dice loss).to verify the setup is correct, I used thecriterion = nn.BCEWithLogitsLoss(size_average=False, reduce=True).The setup is indeed correct as I can retrieve gradients for my parameters usinggrad_of_params = {}for name, parameter in model.named_para... | ptrblck | I think the threshold will also kill your gradients.
You could trythisimplementation.
Would this work for you? |
Naman-ntc | I have 2 batchnorm layers, both have sameweight, samebias, samerunning_meanand samerunning_var. The first is a BatchNorm2D layer and second is a BatchNorm3D layerI give an inputx2d(1x128x64x64) to first BatchNorm2d layer and inputx3d(1x128x5x64x64) to both layers. I ensure thatx3d[:,:,0,:,:] = x3d[:,:,1,:,:] = x3d[:,:,... | ptrblck | Thanks for the code! I created a small example script to show the difference between the 2D and 3D case.
I think it’s due to the different variance, since you have to divide by a larger number of elements in the 3D case.
The code is a bit ugly, but I think it will explain the effects:
# Init Batc… |
JaeGer | Hello ,I’m new to PyTorch, I want to construct a simple Neural Network with one hidden layer (Relu), the input will be a 1930 * 240 tensor, output 1930 * 10. Is there any template code with commentary to learn and thank you. | ptrblck | Would this work as a starter code:
nb_samples = 1930
in_features = 240
hidden = 50
out_dim = 10
model = nn.Sequential(
nn.Linear(in_features, hidden),
nn.ReLU(),
nn.Linear(hidden, hidden),
nn.ReLU(),
nn.Linear(hidden, out_dim)
)
x = torch.randn(nb_samples, in_features)
output … |
Naman-ntc | I tried to load an old pytorch version built model in pytorch 0.4 but I recieved this error on accessing the layers of model :python3.6/site-packages/torch/nn/modules/batchnorm.py", line 53, in extra_repr
'track_running_stats={track_running_stats}'.format(**self.__dict__)
KeyError: 'track_running_stats'Iwas ableto ... | ptrblck | How did you save the model?
This workflow works for me:
In PyTorch 0.3.1.post3:
model = nn.BatchNorm1d(3)
torch.save(model.state_dict(), 'test.pt')
In PyTorch 0.4.0:
model = nn.BatchNorm1d(3)
model.load_state_dict(torch.load('test.pt'))
x = torch.randn(1, 3, 2)
model(x)
Did you save the comple… |
Mactarvish | Hello, I’m trying to create such a Network:class Net(torch.nn.Module):
def __init__(self):
super(Net, self).__init__()
self.linears = [torch.nn.Linear(5, 10)] * 10
self.special_linear = torch.nn.Linear(100, 500)
model = Net()Because I need lots of linears so I just put them into a list at o... | ptrblck | Alternatively, you could use nn.ModuleList, which acts like a list, but registers your modules:
self.linears = nn.ModuleList([nn.Linear(10, 10) for _ in range(10)]) |
NimenDavid | I am new to PyTorch.When I was reading some examples, I have some questions.Latest github example of mnist, in line 15 there is a number 320 in nn.Linear(), but I don’t know how to get that number.class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 10, ke... | ptrblck | Well it’s 4*4*20 = 320.
You can calculate the shape for the forward pass for each operation.
While a convolution with kernel_size=5 and no padding shrinks the activation by 4 pixels in height and width, a max pooling of kernel_size=2 and stride=2 pools the activation to half its size.
From the fo… |
Hunbo | I have a tensor of size (24, 2, 224, 224) in Pytorch.24 = batch size2 = matrixes representing foreground and background224 = image height dimension224 = image width dimensionThis is the output of a CNN that performs binary segmentation. In each cell of the 2 matrixes is stored the probability for that pixel to be foreg... | ptrblck | You could just use torch.argmax():
a = torch.randn(1, 2, 4, 4)
print(a)
b = torch.argmax(a, 1)
b.unsqueeze_(1)
print(b) |
lxtGH | The problem is when doing validation , the input image is 1024 * 2048 , 4 images for 4 1080ti gpu (each gpu per image).I met this error.THCudaCheck FAIL file=/pytorch/aten/src/THC/generic/THCStorage.cu line=58 error=2 : out of memoryTraceback (most recent call last):File “train_cityscape.py”, line 229, intrain(cfg)File... | ptrblck | Have you wrapped your validation code into torch.no_grad()? |
John1231983 | Hello all, I want to make one hot encoding with ignoring label for semantic segmentation. Mylabelshas 22 values from 0 to 20 and one value is 255, called an ignored label. I want to convert thelabelsto one-hot encoding without considering the ignored label.def make_one_hot(labels, num_classes):
'''
Converts an ... | ptrblck | How would you like to ignore the class in your one-hot encoded tensor?
Do you want to remove it completely?
This code should just remove the unwanted class channel:
batch_size = 10
n_classes = 5
h, w = 24, 24
labels = torch.empty(batch_size, 1, h, w, dtype=torch.long).random_(n_classes)
one_hot =… |
Naman-ntc | I am getting the following error of doing a forward pass on my modelFile "/media/newDrive/rishabh/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 491, in __call__
result = self.forward(*input, **kwargs)
File "/media/newDrive/rishabh/anaconda3/lib/python3.6/site-packages/torch/nn/modules/ba... | ptrblck | It looks like some tensors are on the CPU, while the code would like to call a function on a tensor which was pushed to the GPU.
Could you post a small code snippet reproducing this error? |
Yongjie_Shi | I have a tensor and the shape of it is 7x748. However, I want to reshape it to 7x748x1, and I use the torch.viewfor example, data.view(7, 748,1), but it does not work. Could anyone give me some advice to reshape the data to (7,748,1)? | ptrblck | Why doesn’t it work?
x = x.view(7, 748, 1) should return your desired tensor.
Alternatively you could use .unsqueeze(2). |
Naman-ntc | Is copying weight in convnet layers a bad idea?I was performingmodel inflationover 2D conv architecture (that is taking 2D kernel and stacking its copies together to form 3D kernel).I manually copied the weights recursively from the 2D architecture but got the following error : “cuDNN requires contiguous weight tensor”... | ptrblck | It’s most likely due to your copies. Try to call .contiguous() on your weight tensors. |
NAVEEN_PALURU | Please some one help me.I have written the following code.import torchimport torchvision.models as modelsimport numpy as npimport matplotlib.pyplot as pltimport torchvision.transforms as transformsimport cv2image=cv2.imread(‘Dog.jpg’)image is numpy arraycv2.imshow(‘Display’,image);cv2.waitKey(10000);cv2.destroyAllWindo... | ptrblck | After loading your model, you should set it into evaluation mode with:
densenet.eval()
I’ve tested your code and the result for this image is class 207, which is golden retriever. |
Jonghyuk_Kim | I’m trying to finetune the resnet model on Kaggle’s dogs and cats redux, and I successfully trained and test when all the train and validation process is seperated for each model. But, when I tried to load 4 of the resnet models at once( for ensemble), memory problem pop up and the kernel is gonna die. (both on GPU and... | ptrblck | You could load the Models one by one, save all predictions to your disc, and ensemble separately.
In that way you are not memory bound and you could even create many more different models. |
yxchng | Currently, I have to pass adeviceparameter into my custom layer and then manually put tensors onto the specified device manually using.to(device)ordevice=device.Is this behavior expected? It looks kind of ugly to me.Shouldn’tmodel.to(device)put all the layers, including my custom layer, to device for me? | ptrblck | In that case you should useregister_buffer. |
kenmikanmi | Hi, I have parametersparam.pthand I want to load them intomodellike:model = Net()
model.load_state_dict(torch.load("param.pth"))but it causeKeyError: 'unexpected key "0.weight" in state_dict'How can I load params in state_dict?Following are details ofNetandparam.pth:Networkclass Net(nn.Module):
def __init__(self):
... | ptrblck | Well, there is a way, but it’s a bit ugly, so sorry for that, but I can’t come up with a cleaner way at the moment.
I’ve created a small example how to change the keys in the state_dict:
# Create Sequential model
modelA = nn.Sequential(
nn.Conv2d(3, 6, 3, 1, 1),
nn.ReLU(),
nn.Conv2d(6,… |
NAVEEN_PALURU | Let A be a tensor(CxHxW).What is the difference between torchvision.transforms.ToPILImage(A) and torchvision.transforms.ToPILImage()(A) ? | ptrblck | transforms.ToPILImage() takes an argument mode, which defines the PIL.Image.mode of the input data:
mode (PIL.Image mode) – color space and pixel depth of input data (optional). If mode is None (default) there are some assumptions made about the input data: 1. If the input has 3 channels, the mode… |
jsn | Is there an official callback feature in PyTorch? If not, I’d like to know the relevant files to modify to make it happen. Basically, I want callbacks for functions likeon_batch_end(),on_epoch_end()etc. | ptrblck | Ignitehas some nice callbacks. |
Maogic | I try to understand the structure of a network but got confused. I want to know what determines the structure of a network, theinitfunction or the forward()?In the tutorial, I saw a network can be defined asclass DynamicNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
super(DynamicNet, self).__init... | ptrblck | In the first use case the middle_linear layer will be used a few times with the same weights, since its output is fed into the layer again.
In the second example, the extra_layer will be registered as a parameter in the model but won’t be updated, since the forward method doesn’t use it. You can ha… |
Kexiii | I’m trying to write some code like below:x = Variable(torch.Tensor([[1.0,2.0,3.0]]))
y = Variable(torch.LongTensor([1]))
w = torch.Tensor([1.0,1.0,1.0])
F.cross_entropy(x,y,w)
w = torch.Tensor([1.0,10.0,1.0])
F.cross_entropy(x,y,w)However, the output of cross entropy loss is always 1.4076 whatever w is. What is behind ... | ptrblck | You are using it correctly!
However, I think there is an explanation missing on how size_average works regarding the weight in thedocs.
Have a look at the docs ofNLLLoss. It states, that each loss will be divided by the sum of all corresponding class weights, if reduce=True and size_average=True.… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.