user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
Mactarvish | I just tried therequires_gradin torch.tensor:x = torch.tensor([[1., -1.], [1., 1.]], requires_grad=True)But when I used requires_grad in FloatTensor, I got an error:xx = torch.FloatTensor([[1., -1.], [1., 1.]], requires_grad=True)Traceback (most recent call last):
File "/home/SSS/Desktop/SS/playground.py", line 54, i... | ptrblck | In your current example you’ll already create a torch.FloatTensor, since the type will be inferred automatically using the passed values.
However, if you would like to specify it, you could pass the dtype argument:
x = torch.tensor([[1., -1.], [1., 1.]], dtype=torch.float, requires_grad=True)
prin… |
KelleyYin | I have a index matrix and a matrix filled by zero .For example :index = Tensor([[ 0, 1],
[ 1, 2],
[ 4, 1]])
a = Tensor([[ 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0.]])Therefore, I would like to fill 1 to the zero... | ptrblck | Here is another approach without a for loop:
a[torch.arange(a.size(0)).unsqueeze(1), index] = 1. |
John1231983 | Hello all, I have a sequential layer likeself.conv_norm_relu = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True))I want to changenn.BatchNorm2dtoGroupNorm, so the new one isself.conv_norm_relu = nn.Seque... | ptrblck | What about defining a method which returns the desired layer based on your keyword:
def get_norm_layer(out_channels, layer_type='BatchNorm'):
if layer_type == 'BatchNorm':
return nn.BatchNorm2d(out_channels)
elif layer_type == 'GroupNorm':
return nn.GroupNorm(16, out_channel… |
fahadakhan96 | Hi! I’m trying to implement the baseline model described in the Stanford MURA paper. The following is the code for my model:model = densenet169(pretrained=True)
model.classifier = nn.Sequential(
nn.Linear(in_features=1664, out_features=1),
nn.Sigmoid()
... | ptrblck | Most likely you’ll get the tensor shapes for the tensors where the mismatch occurred.
In your case, it’s:
RuntimeError: size mismatch, m1: [1 x 26624], m2: [1664 x 1] at …
If you change the in_features of your linear layer to 26624, your code will run successfully with 320x320 shaped inputs.
A… |
Purvak-L | I’m trying to implement the following network in pytorch. I’m not sure if the method I used to combine layers is correct. In given network instead of convnet I’ve used pretrained VGG16 model.deeprank909×516 35.2 KBmodel = models.vgg16(pretrained=True)
new_classifier = nn.Sequential(*list(model.classifier.children())[... | ptrblck | Thanks for the code.
It looks like to padding of your second max pooling layer is wrong, since you are using the same argument in Keras.
Try this definition self.maxpool2 = nn.MaxPool2d(7,2,padding=3) and your output will be [batch_size, 96, 4, 4] for both branches. |
S.F | Hi all,To be more specific about this question, I tested on the simple MNIST example.mnist. I also fixed the seed to ensure the reproducibility. But if I add one additional layer in the module constructor, and I didn’t use that layer in the forward function, e.g. as follows:class Net(nn.Module):
def __init__(self):... | ptrblck | Yeah, like I said, seeding is a bit tricky in such a situation. That is why in my example I’ve loaded the state_dict and also set the random seed for both forward passes to get the same result.
As@musicpieceexplained, each additional call to the pseudo random number generator might yield a differ… |
farazk86 | Ive trained my segmentation network using a U-Net model. I want to now visualize the result from the network output.Theshape of output is[1,2,256,256]. One channel for background and the other for foreground. Here is what I get forprint(output.detach().squeeze()):tensor([[[ 6.1109, 6.1109, 6.1126, ..., 6.1580, 6.1... | ptrblck | Yes your approach is right and I still think that the zero tensor is a valid answer, if your model just overfits to class0.
Have a look at this example:
x = torch.cat((torch.ones(1, 1, 5, 5), torch.zeros(1, 1, 5, 5)), 1)
print(x)
> tensor([[[[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
… |
YNX | I have a forward method as the following code (simplified):def forward(self, Y, D):
L0_1=self.relu(self.low_level(D))
cas_input=self.relu(self.conv_genesis(L0_1))
for i in range(self.N+1):
L_1=self.relu(self.D_convs[i](cas_input)) #leak1
L_2=torch.cat([L_1,Y_features[i]],1) #... | ptrblck | Are you sure it’s a memory leak?
It seems you are passing cas_input in a “recurrent” way into your modules, such that its computation graph will be stored. If you don’t want to calculate the gradients for cas_inputs, you could call .detach() on it before passing it to self.D_convs[i]. |
blackberry | OpenCV loads images as BGR by default, which needs extra care when using pre-trained models in RGB.OpenCV has a lot of image processing functionality, which may be useful in data augmentation.Apart from this, is there a performance (speed) difference between OpenCV and PIL Image?Which image handling library would you r... | ptrblck | There seem to be some benchmarks showing a better performance for OpenCV, while others show some use cases where PIL is the winner (or Pillow-SIMD).Pillow-SIMDis a drop-in replacement for PIL using SIMD operations.
You can find some benchmarkshere, but as always with benchmarks I would be skept… |
hotcheetos_puff | What difference are there in using an optimizer ( torch.optim.ChosenOptimizer) to vary learning rates as opposed to an lr_scheduler (torch.optim.lr_scheduler.ChosenScheduler)?What are some possible consequences of using both? | ptrblck | Additionally to what@kiraexplained, note that the lr_scheduler just adjusts the learning rate. It does not update the weights of your model. You would still have to create and call an optimizer.
Usually the scheduler is also called once in every epoch, while the optimizer is called for every mini… |
Sulantha_Sanjeewa | I am testing using Pytorch with multiple GPUs. I am not using DataParallel, but I want to use Model Parallelism.My Model design is two input branches (each in separate GPUs). I have done an example with MNIST for reproducibility.But at training, I get the exception mentioned below. Any help would be appreciated.import ... | ptrblck | Your code looks generally alright besides this line of code:
out2.to(gpu1)
While nn.Modules are transferred inplace, you have have to assign tensors back:
out2 = out2.to(gpu1)
Could you fix this line and see it it’s working? |
Ali_Mirzaeyan | Hi,I’m trying to train a simple model with cats and dogs data set. When I start training on CPU the loss decreased the way it should be, but when I switched to GPU mode LOSS is always zero, I moved model and tensors to GPU like the bellow code but still loss is zero. Any idea ?import os
import os.path
import csv
import... | ptrblck | If you use datasets.ImageFolder then yes, your images should be located in separate folders which represent the classes.
If you don’t want that, you can easily write your own Dataset and load the images using your own logic.Hereis a good tutorial explaining, how to use Dataset.
One way would be… |
DuaneNielsen | I’m implementing an atari pong playing policy gradient agent.The main loop at the moment is.Run the policy to gather some experience and save the experience (images, actions, rewards) in a dataset.Run a single iteration of training over the gathered experience to update the policy.Throw all the data away and start agai... | ptrblck | The downside of creating GPU tensors in __getitem__ or push CPU tensors onto the device is that your DataLoader won’t be able to use multiple workers anymore.
If you try to set num_workers > 0, you’ll get a CUDA error:
RuntimeError: CUDA error: initialization error
This also means that your hos… |
sohaib_attaiki | I’m getting the following error:AttributeError: cannot assign module before Module.__init__() call.I’m trying to create an instance of my class :class ResNetGenerator(nn.Module):
def __init__(self, input_nc=3, output_nc=3, n_residual_blocks=9, use_dropout=False):
# super(ResNetGenerator, self).__init__()
... | ptrblck | Oh, it seems I’ve missed an important line in the stack trace.
File "train.py", line 40, in <module>
model = ColorizationCycleGAN(args)
Could you check your definition of ColorizationCycleGAN?
I would always recommend to update to the latest release, but this error seems unrelated to your PyT… |
Shisho_Sama | If I set batch-size to 256 and use all of the GPUs on my system (lets say I have 8), will each GPU get a batch of 256 or will it get256//8?If my memory serves me correctly, inCaffe, all GPUs would get the same batch-size , i.e 256 and the effective batch-size would be 8*256 , 8 being the number of GPUs and 256 being th... | ptrblck | nn.DataParallel splits the data along the batch dimension so that each specified GPU will get a chunk of the batch. If you just call .cuda() (or the equivalent .to() call), you will push the tensor or parameters onto the specified single device. |
Neda | I am wondering how I can test the trained model for semantic segmentation and visualise the mask for the test image. There is an example for classification problem in Pytorch but couldn’t find any obvious example for the segmentation.I foundthis pagethat test the network, but it’s for classification problem.I did manip... | ptrblck | I’m not sure, why it’s not working.
If you would like to visualize both probability maps for the two classes, your code should work:
plt.figure()
plt.imshow(torch.exp(outputs[0,0,:,:]).detach().cpu()) # plot class0
plt.figure()
plt.imshow(torch.exp(outputs[0,1,:,:]).detach().cpu()) # plot class1… |
beginner1010 | I read a couple of threads here but I could not resolve the issue in my code. I am a newbie in deep learning and Pytorch. I was wondering why the loss does not change and, at the end of the code, I found the weights all are zeros.I would appreciate if you can help me with this.def generate_minibatch (X, y): # X and y a... | ptrblck | Thanks for the data sample.
It looks like you are dealing with some kind of indices, is that correct?
If that’s the case, I would recommend to use an nn.Embedding layer to map these indices to some dense floating point representation.
Here is a small code modification to your model:
class revie… |
arvindmohan | Hello,I am trying to implement gradient checkpointing in my code to circumvent GPU memory limitations, and I found aPytorch implementation. However I could not find any examples anywhere online. All I see right now is:>>> model = nn.Sequential(...)
>>> input_var = checkpoint_sequential(model, chunks, input_var)This is ... | ptrblck | I usedthis tutorialfrom@Priya_Goyalto see how different models should be used for checkpointing. |
mukhtar | hello everybody,I am new to pytorch and had a problem with channels in AlexNet.I am using it for a ‘gta san andreas self driving car’ project, I collected the dataset from a black and white image that has one channel and trying to train AlexNet using the script:from AlexNetPytorch import*
import torchvision
import torc... | ptrblck | It looks like your fix regarding the input channels is right, but the spatial size might be too small.
How large is your input? AlexNet should work with 224x224 sized images. |
evo | Hello, I did FNN for 4 class classifications.How is it possible to calculate confusion matrix? | ptrblck | To calculate the confusion matrix you need the class predictions. Currently it looks like pred contains the logits or probabilities for two classes.
Try to call torch.argmax(pred, 1) to get the predicted classes.
Here is a small example:
output = torch.randn(1, 2, 4, 4)
pred = torch.argmax(output… |
pipibo | a = torch.randn(3,2)for example:tensor([[ 0.5957, 1.6250],
[-0.4354, 2.0719],
[ 0.8076, -1.2720]])anda[1] = tensor([-0.4354, 2.0719]), but I want to get the cols’ data of a,such astensor([1.6250,2.0719,-1.2720]), what shoud I do? thanks for your help! | ptrblck | You could index in the second dimension:
a[:, 1] |
pipibo | I trained a model with two class,and it works well in mydataload, but when I want to test it with an arbitrary data, thepredis wrong, and I find that the two score oflog_softmaxare always the same. I’m confused with this data.my net is here :class Mnet(nn.Module):
def __init__(self, k = 2):
super(Mnet, self)._... | ptrblck | Usually your data will have the batch dimension in dim0, so using F.log_softmax in dim0, will normalize your log probabilities in this batch dimension, which is most likely wrong.
Your logits are probably in dim1, so F.log_softmax(tensor, dim=1) should give you the right results. |
Soumya_Sanyal | Hi,My question is related to loading input data using the combination ofDatasetandDataLoader. Sincepin_memoryoption in aDataLoaderworks for CPU tensors, I understand that there are two ways to load the input data:In theDatasetcreate CPU tensors and then usingpin_memorytransfer it to GPUDirectly create CUDA tensors in ... | ptrblck | I would stick to the first approach, as this would push a whole batch to the device (avoiding multiple small tranfers), which might potentially be executed asynchronously while your GPU is busy. Using pinned memory will also speedup the transfer. Have a look atNVIDIA’s blog postfor some more infor… |
pipibo | At first, I write a samll net namedTnet, and it works well, but now I want to use it in a bigger net namedMnet, so I writeself.tnet=Tnet()in Mnet’s__init__function, but it catches a error during forward process like this:out, _ = cls(data)
File "/home/zqk/anaconda2/envs/torch/lib/python2.7/site-packages/torch/nn/modu... | ptrblck | Thanks for the code.
The __init__ method in MNet has a typo (the second two underscores are missing). |
sebscholl | I’m new to Pytorch and trying to understand why something didn’t break.Details:I’m building a model that detects skin cancer given an image (it seems this is a common starter project…) and used a pre-trained Resnet50 model for transfer learning.I incorrectly added a final fully connected layer like this:model.fc1 = nn.... | ptrblck | There is a small mistake in reassigning the last linear layer.
In resnet50 the last linear layer is called self.fc instead of self.fc1.
Even though you assigned a new layer to self.fc1, this layer wasn’t used and your model was basically a pretrained ResNet with 1000 output classes.
Fix this typo… |
yusei | I want to build a neural network classifier for binary class.trainset.shape = (41712, 231)testset.shape = (10429, 231)It outputs:ValueError Traceback (most recent call last)in ()10 running_loss = 011—> 12 for inputs, labels in trainloader:13 optimizer.zero_grad()14 ... | ptrblck | You don’t need to use torch.exp, if you’ve used F.sigmoid in your model.
Also, you should use a threshold on the probabilities to get the corresponding class, e.g. 0.5.
tensor.topk will return a zero tensor in your current setup. |
minister_79 | Good day all,I was trying to do some signal processing in Pytorch. I have written the same code in Tensorflow and it worked, but the one below is not.Thank you.import osimport torchfrom torch.autograd import Variableimport numpy as npclass Modulator(object):def __init__(self, mod_type, K):
# Set modulation type
... | ptrblck | If you have already imported the Variable class, you won’t need to use the torch namespace before it.
However, since Variables are deprecated since 0.4.0, you should completely skip this step and just use tensors. |
Hong | Does relu have any parameters? My understanding is that relu function (relu = max(0, x)) just pick a value between 0 and x and has no parameters involved. But in this pytorch official tutorialDeep Learning with PyTorch: A 60 Minute Blitzwhen one prints the parameters of the modelparams = list(net.parameters())print(le... | ptrblck | They shouldn’t be in there, and in the tutorial you’ll get a list of 10 parameters.
These are two parameters for each of the five layers (weight and bias). |
Ankitnau25 | I am trying to write a binary addition code, I have to provide two bits at a time so input shape shouldbe (1,2) and I am taking hidden layer size 16rnn = nn.RNN(2, 16, 1)
input = torch.randn(1, 2)
h0 = torch.randn(2, 16)
output, hn = rnn(input, h0)I am getting error input must have 3 dimensions, got 2 when defining in... | ptrblck | Based on your code it looks you would like to learn the addition of two numbers in binary representation by passing one bit at a time. Is this correct?
Currently it seems you are not detaching the hidden state at any time, just in the initialization step of your model. Could you try to create a new… |
dashesy | When we use pybind11 for example to forward using:std::vector<at::Tensor> lltm_forward(
at::Tensor input,
at::Tensor weights,
at::Tensor bias,
at::Tensor old_h,
at::Tensor old_cell) {
}Are tensors passed by reference, or by value? Can I modify them? | ptrblck | As far as I know, at::Tensors are always passed by reference.
If you would like to get a copy, you can call clone() inside your method. |
gulfaraz | Please reproduce the behaviour and explain why this happens.resnet50 = models.resnet50(pretrained=True) # load pretrained model
resnet50.eval() # set model to eval mode
# batch size > 1
for index, batch in enumerate(imagenet_val_loader): # iterate over dataloader
output = resnet50(batch) # predict for a batch of i... | ptrblck | I cannot reproduce the issue. I’ve used two DataLoaders with a batch size of 10 and a batch size of 1, respectively. Both loops yield the same results using model.eval().
I haven’t used model.train(), since e.g. the BatchNorm layers will update their running estimates, which might yield different r… |
sweets | Hi everybody,I’ve been trying to debug what is happening but don’t know what’s wrong.If you need more info let me know.Regards!epochs = 10steps = 0running_loss = 0print_every = 5for epoch in range(epochs):for inputs, labels in train_loader:steps += 1inputs, labels = inputs.to(device), labels.to(device)
optimizer.z... | ptrblck | Thanks for the code.
It looks like you would like to swap the last linear layer of the pretrained ResNet with your nn.Sequential block.
However, resnet does not use self.classifier as its last layer, but self.fc. This also explains the error, since you are currently setting the required_grad flag … |
Krish | Pytorch beginner here. I am trying to predict the output of an AND gate using a neural network, but when I train the model, the loss doesn’t decrease and output stays at 0.2500 for every input. What am I doing wrong?import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init_... | ptrblck | Your code generally seems to work after fixing some minor shape issue in a (removing the unnecessary dim1).
I also tried to run your code with 10 random seeds and all seem to converge. |
Shisho_Sama | hello everyone,Is it possible to use two different GPUs for training the same network? I mean in a multi-gpu scenario, or should all the GPUs be the same?I’m planning to get a new GTX1080TI(from Asus, my GTX1080 is from gigabyte so the brand is also different), but don’t know if I should use each separately or I can us... | ptrblck | You could use different GPUs, but note that the slowest GPU might be the bottleneck for your overall performance. This means your GTX1080TI would have to wait for your GTX1080 to finish its operations before the next training iteration can be started. |
John1231983 | Hello all, I have my own network, it trained for the binary classifier (2 classes). After 10k epochs, I obtained the trained weight as10000_model.pth. Now, I want to use the model for 4 classes classifier problem using the same network. Thus, I want to copy all trained weight in the binary classifier to 4 classes probl... | ptrblck | The error message sounds like you already changed the conv_class layer.
Could you check, if you are using two different layers as the output, since the error points to conv_class, while you are manipulating conv_classify.
Here is a small code snippet of what I was thinking about:
class MyModel(nn… |
mattrobin | I’m using a GAN structure where my discriminator trains on some labeled data batches, some unlabeled data batches, and some generated data batches. I’d like to keeptrack_running_statsturned on, but only for the labeled data. That is, during the unlabeled and generated batches, it just uses the statistics from the label... | ptrblck | You could just set the BatchNorm layer into eval mode, either by indexing it directly or recursively.
Here is a small example for the latter approach:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 3, 1, 1)
sel… |
se7en | In pytorch seq2seq tutorial: embedded = self.embedding(input).view(1, 1, -1), just wondering do I always need to reshape it to (1, 1, -1) -->(batch_size=1, seq_size=1, input_size)? | ptrblck | No, you don’t. In this tutorial the “words” are fed one by one, so that the output of self.embedding is in this shape. You could also use an arbitrary batch size and sequence length (which would need some changes in the code for this tutorial).
Also note that the GRU expects the input to have the s… |
Shinobi-D | I am training a FCN-alike model for semantic segmentation. The output of model is [batch, 2, 224, 224], and the target is [batch, 224, 224]. I used nn.CrossEntropyLoss() as the loss function.As for the training process, I randomly split my dataset into train and validation with [0.8, 0.2] random split.The code for trai... | ptrblck | Your dataset is indeed quite small. I would try to add a lot of data augmentation and maybe remove some capacity of your model (smaller layers in the decoder part), if that’s possible. |
jkwening | I’m trying to pre-calculate the convolution layers of a pre-trained model prior to training the fully-connected classifier layer, specifically densenet161 model. The goal is to gain some speed in training the model if it doesn’t have to consistently calculate the conv layers which I have frozen.I’m getting size mismatc... | ptrblck | You are right. In the original model adaptive pooling is used in the forward method.
Have a look atthis line of code.
Did you add it to your model as well? |
Novak | I am trying to understand what is happening under the hood of any generic type of optimizer when it is passed a list of parameters. (Specifically, I am playing with CycleGANs and am trying to emulate the more Tensorflow-style of passing parameters to special purpose optimizers, rather than the PyTorch-style of selecti... | ptrblck | If you print id(param) in the first print loop, you’ll get the same ids.Currently you are printing the id of the name object. |
vfmatzkin | I’d like to comment or ask about this issue that I realized yesterday. I was migrating a big script into a Class version of it, but by doing this I forgot to add that when training, the input tensor has to require grad (I usually do this by using inputTensor.requires_grad_()).Despite this, the model managed to converge... | ptrblck | Your input doesn’t need to require gradients, if you just would like to train your model.
It might require gradients, if you would like to use the gradients in the input itself.
Some use cases could be e.g. to generate adversarial examples or visualize some activations in the input using the gradi… |
anjali-chadha | I am a beginner in PyTorch and I am currently going through the official tutorials.In theTransfer Learning tutorial, the author used different transformation steps for Training and Validation data.data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomH... | ptrblck | The general approach is to use some data augmentation in your training so artificially create “new” samples of your data, and to use some “constant” pre-processing in your validation/test case.
As you can see the training transformation has some random transforms, e.g. RandomResizedCrop, which is f… |
Zichun_Zhang | from __future__ import print_function
from torch.autograd import Variable
import torch
xx = Variable(torch.Tensor([2]), requires_grad = True)
yy = 3*xx
zz = yy**2
yy.register_hook(print)
zz.register_hook(print)
tar = Variable(torch.Tensor([100]), requires_grad = False)
loss = zz-tar
loss.backward()
#normally here fol... | ptrblck | The solution to the MAE criterion gives you the median, while the solution to the MSE criterion gives you the mean. In the former case you’ll get a robust solution, which means that your solution is robust to outliers, but might have multiple minima. So even though your derivative is partially const… |
clement643 | Hi,I’m interested in using DataParallel with two inputs behaving differently :model(S,A)Where S would be split but not A. I didn’t find anything about the possibility of doing that.Thanks. | ptrblck | In that case nn.DataParallel won’t help, since it would copy the data onto all GPUs.
You could try to push S1 and S2 onto different GPUs and calculate the loss there.
Here is a small pseudo-code for this use case:
S1, S2 = torch.chunk(S, 2, 0)
S1 = S1.to('cuda:0')
S2 = S2.to('cuda:1')
SA1 = torch… |
Zichun_Zhang | Why my pytorch process keep expanding usage of GPU while running?I just run a normal train file of my model, and today I suprisingly found that my process has been expanding the usage of GPU by the rate of 2 MB per training round.Is that because I did not free some .cuda() Variable after use? I thought I did not ha... | ptrblck | Are you storing the loss or some other variable, which is attached to the computation graph, somewhere?
Make sure to call detach on your model output etc., if you would like to store the predictions, loss etc. for further analysis. |
overlapjho | I’m getting the errorValueError: Expected input batch_size (128) to match target batch_size (32).for the following code:class Custom(nn.Module):
def __init__(self):
super(ParallelNet, self).__init__()
self.conv1 = nn.Conv2d(3, 32, 7)
self.bn1 = nn.BatchNorm2d(32)
self.conv2 = nn... | ptrblck | I’m currently not seeing, where the batch sizes 32 and 128 are coming from, but I guess the torch.cat call yields the error, since it concatenates the tensors in dim0 by default.
Try to use out = torch.cat((x1, x2, x3, x4), 1) instead. |
isalirezag | How I can change the name of the weights in a models when i want to save them?Here is what i want to do:I dotorch.loadto load the pretrained model and update the weights forself.Conv1(whereself.Conv1 = nn.Conv2d(3,3,kernel_size=1, stride=1, padding=0, bias=False))after training my model i like to save the weights ofsel... | ptrblck | You code should rename the self.conv1 layers:
class ModelA(nn.Module):
def __init__(self):
super(ModelA, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 3, 1, 1)
self.fc1 = nn.Linear(6*4*4, 2)
def forward(self, x):
x = F.relu(self.conv1(x))
x =… |
rsd352 | I am trying to display an RGB image using imshow, but it does not let me display it and gives the error - “Invalid dimensions for image data”.The dimensions of the image variable that I am trying to display are 33232. | ptrblck | matplotlib usually expects the images to have the channel in dim2, so try to permute your image tensor using tensor = tensor.permute(1, 2, 0) before passing it to imshow. |
Naruto-Sasuke | After I had installed torchvison, I found thatpillow-simdthat may boost the performance of processing images.I want to switch pillow to pillow-simd. Then just remove pillow and install pillow-simd, then pillow will automatically switch to pillow-simd, or I need to reinstall torchvision? | ptrblck | It should be a drop-in replacement, i.e. since torchvision just imports PIL, Pillow-SIMD should be loaded if available. |
Dominik | I have training data available asdtype = torch.float64and I want to use this data type to train my model. Now it seems that thenn.Layer(e.g.nn.Linear) interface doesn’t offer the possibility of specifying a data type. Right now I getRuntimeError: Expected object of type torch.DoubleTensor but found type torch.FloatTens... | ptrblck | You can call it on the whole model which will cast all layers and parameters to the type.
Alternatively, you could set the default type at the beginning of your script using torch.set_default_dtype(). |
kenmikanmi | Hi, I’m considering to build a network like this:Each linear layerA,Breceive 128 dim output fromCNN(Φ).CNN’s parameters are trained in another task, and saved asmodel.pth.Now I want to trainA,Blayers andCNNin new task.In this case, is next pseudo code works properly?model = CNN() # class CNN() defines Φ's... | ptrblck | Your code looks alright. Note that the gradients will be accumulated in the CNN from both losses.
A small side note: you shouldn’t call forward but the model directly: model(input_tensor).
This will make sure to register all hooks properly (if there are any) etc. |
datadog | I have a machine learning model designed as follows:model = nn.Sequential(OrderedDict([
('fc1', nn.Linear(631, 500)),
#('drop1', nn.Dropout(0.5)),
('relu1', nn.ReLU(inplace=True)),
... | ptrblck | If you’re using nn.CrossEntropy you should remove the last nn.LogSoftmax from your model.
In case you would like to keep the nn.LogSoftmax layer, you would need to use nn.NLLLoss instead. |
Daniel_Morris | The DataLoader class is hanging (or crashing) in Windows but not in Linux with the following example:#Demo of DataLoader crashing in Windows and with Visual Studio Code
import torch
from torch.utils.data import Dataset, DataLoader
class SimpleData(Dataset):
"""Very simple dataset"""
def __init__(self):
... | ptrblck | Windows needs this if-clause protection, since it’s using spawn for multiprocessing.
If you don’t protect your code, the script will be called multiple times executing all module-level code, thus yielding an error.
Have a look at theWindows FAQfor further information. |
Sumching | Sorry for my terrible English…I run the code from 60mins tutorial,like this.trainset = torchvision.datasets.CIFAR10(root=’./datasets’, train=True, download=True, transform=transform)trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2)dataiter = iter(trainloader)And return a err... | ptrblck | There is an issue regarding multi-processing on Windows machines, since apparently Windows subprocesses will import (i.e. execute) the main module at start, which will result in recursively creating subprocesses.
Try to protect your code in if __name__ == '__main__'.
Also you could check, if this … |
JuanFMontesinos | Hi!I was wondering if it’s possible to train partially with fp16.I’m dealing with a very big network. I would like to use fp16 in a submodule of the network.Does autograd deal with casting from float16 to float32 during the backprop?In other post i saw someone who recommends to use fp32 on batch normalization not to ha... | ptrblck | Yes, it’s possible.
However, using FP16, you should take care of some possible pitfalls, e.g. imprecise weight updates or gradient underflow. NVIDIA recently published their mixed precision utilities for PyTorch namedapex.
On the one side you have the automatic mixed precision training using amp,… |
holiv | Hello Dear, i want to use the output of my rnn as a tensor to compute. But when i change the list of tensor to one tensor using torch.stack, it becomes too slow and consume a lot memory. Is there anyway i can optimize this loop? thx for your reply.output = []hx_0=Variable(torch.randn(1000, 4))for i in range(1000):hx= r... | ptrblck | Thanks for the info regarding the shapes!
Could you try the following code and see, if it’s working:
batch_size = 32
hidden= 4
nb_samples = 1000
output = torch.zeros(batch_size, nb_samples, hidden)
for i in range(nb_samples):
output[:, i:i+1, :] = torch.randn(batch_size, 1, hidden) |
mabdullahrafique | Hello guys !I am working on a problem in which I have the coordinates to slice the image like [y, y+height, x, x+width]. So if if I have torch image obtained usingimg = Variable(img.cuda())how can we slice the image to get that specific area of image [y:y+height, x:x+width] .Thanks | ptrblck | You can directly index your image tensor:
img = torch.randn(1, 3, 10, 10, device='cuda')
x, y = 1, 1
width, height = 5, 5
img[:, :, y:y+height, x:x+width] |
trancong21 | I want to fine tuneSqueezeNetmodel fromtorchvision/models/squeezenet.pyfor MNIST dataset.What should i do? Thanks! | ptrblck | You could use theMNIST exampleas your template and just change a few lines of code.
Since the MNIST data comes as grayscale images in the resolution 28x28, you would need to repeat the channel to simulate an RGB image as well as resizing it to 224x224 to fit your SqueezeNet.
Here is a small exam… |
John1231983 | I have four vectors size of1x8. I want to a new vector where each element row of the new vector is a linear combination of each element row in the four vectors as the figure. The expected output should be1x8.My solution is that using convolution to learn the weight. I convert the vector size of1x8toBxCxHxW, where W=1, ... | ptrblck | Oh, I clearly misunderstood your use case, sorry!
I thought the kernel would be the dotted line in your figure, but I’ve apparently didn’t read the indices carefully enough.
So basically you have a weight for each input value. Both of my approaches use some kind of weight sharing and are not doing… |
pira | Thank you for your feedback,@ptrblck!I’ve changed targets totargets = targets.reshape(seq_len, input_size).long()So now Outputs is torch.Size([226, 1, 128]) while targets is torch.Size([226, 128]) if I understood your answer in 1. correctly. However, I keep getting the second errors abour invalid indices. I’m not sure... | ptrblck | In that case, your shapes should be [batch_size, seq_length, nb_classes].
Try to permute your ourput using output = output.permute(1, 0, 2) and squeeze the additional dimension in your target target = target.squeeze(2).
Where does dim2 in your target come from? |
beneyal | Hi,In theevaluatemethodherethe loss is calculated like so:total_loss += len(data) * criterion(output_flat, targets).item()Why is that? Why not justcriterion(output_flat, targets).item()? Especially that during training, the loss is calculatedloss = criterion(output.view(-1, ntokens), targets)One might say that I’m in a... | ptrblck | This is sometimes done during evaluation or testing to get the exact loss in case the last batch is smaller than the rest. If you just add the test losses together, remember that in the default case each one will be an average over the current batch. If all batches have the same length, you can just… |
Manik_Singhal | Hi,I am trying to recreate this paper:Continuous Learning in Single Incremental TasksAnd one of the algorithms in the paper involves training the final layer w.r.t to a loss function (eg. cross-entropy), but learning all preceding layers using a regularization term in addition to the back-propagated loss. So I know tha... | ptrblck | Not necessarily. The regularization term will modify all parameters which are is its computation graph.
Have a look at this dummy example:
model = nn.Sequential(
nn.Linear(1, 1, bias=False),
nn.Sigmoid(),
nn.Linear(1, 1, bias=False)
)
criterion = nn.MSELoss()
x = torch.randn(1, 1)
tar… |
aredd-cmu | My model has many parameters for each data value in the data set. I initialize them in my model constructor as follows.init_lev_sms = []
init_seas_sms = []
init_seasonalities = []
for i in range(num_series):
init_lev_sms.append(nn.Parameter(torch.Tensor([0.5])))
init_sea... | ptrblck | The reason that init_lev_sms and seas_sms are showing up as model parameters while init_seasonalities does not, is that you are rightly using a nn.ParameterList for the former ones while a plain Python list for the latter.
Change the last line to:
self.init_seasonalities = nn.ParameterList(init_se… |
Neda | I am trying to do CIFAR10 tutorial on GPU. since, I am worling on windows machien I was getting an error BrokenPipeError: [Errno 32] Broken pipe which solved aftre wrap the code inif __name__=='__main__': main(), then I did check that is cuda available or not which is available.device = torch.device("cuda:0" if torch.c... | ptrblck | It should be alright. You could put the net creation, datasets, and loaders into main, but this shouldn’t yield this error.
However, it looks like you’re not pushing the data and target onto the GPU in your eval loops:
with torch.no_grad():
for data in testloader:
images, labels = data… |
joxeankoret | Hi!I’ve adapted the example classifier from the tutorial based on the CIFAR10 dataset to load my own, train and test it, and it’s working OK. However, now that I’ve the model finished I don’t know how to test just a single input.Here is the whole source code of my classifier. The part where I don’t really know what to ... | ptrblck | It seems your input is missing the batch dimension.
Generally you should pass the input as [batch_size, channels, height, width].
In your use case, if you load a single image it will be in the shape [c, h, w].
Just unsqueeze the input and pass it to the model:
img_data = img_data.unsqueeze(0)
se… |
Ryanzsun | Hi guys,I’m trying to load point cloud data with dataloader. These data has different size like tensor (100,3) tensor (200, 3). I’m able to load them with my custom collate function, but there will be no batch dimension in this case. Could someone please help me with it? Thanks. | ptrblck | Thanks for the info!
Do you want to use all 300 samples at once?
I see the disadvantage of this approach, since your batch size is not flexible anymore.
I’ve created a small example to use a list of different sized point clouds and load each sample in the Dataset:
class MyDataset(Dataset):
d… |
smonsays | I am experimenting with randomly removing individual weights after the model has been trained. In order to restore the original state of the network after these experiments, I cache them before. However, the restoring does not work as expected, can somebody point out my mistake?[...]
cache = self.state_dict()
for layer... | ptrblck | Try to call cache = copy.deepcopy(self.state_dict()), as currently cache holds a reference to your state dict and will be updated with it. |
Carson | So I have and (N,3) shape tensor, I would like to have the each of the (1,3) shaped rows to be converted to a (1,3) shaped row with a 1 in the place that the maximum of the row is and a 0 in the other place.So is there a function that changes the maximum entry of a tensor to a 1 and the rest to 0 along a given axis, no... | ptrblck | This code snippet should work:
x = torch.tensor([[2.3, 3.1, 1.2],
[5.6, 4.1, 3.1]])
idx = torch.argmax(x, 1)
output = torch.zeros_like(x).scatter_(1, idx[:, None], 1.) |
Neda | I have two dataset folder of tif images, one is a folder called BMMCdata, and the other one is the mask of BMMCdata images called BMMCmasks(the name of images are corresponds). I am trying to make a customised dataset and also split the data randomly to train and test. Thank you in advance. at the moment I am getting a... | ptrblck | Currently you are just returning the length of the path, not the number of images.
image_paths should be a list of all paths to your images.
You can get all image paths using the file extension and a wildcard:
folder_data = glob.glob("D:\\Neda\\Pytorch\\U-net\\BMMCdata\\data\\*.jpg")
folder_mask … |
Carson | Hi, I’m learning how to make Convolutional neural networks right now and I ran into something unexpected. I get the an error when I pass an MNIST image to a convolutional layer.I have pytorch 0.4.1 with no cuda on my laptopI made my own module to let me choose a variable number of convolutional layers and linear fully ... | ptrblck | Since you have a CNN you should pass your input as images.
Try to remove the image = images.reshape(-1, 28*28) line and run it again.
Your code already flattens the activation after the conv and before the linear layers. |
ChandanVerma | Hi,i am trying to train pnasnet5large from scratch of my custom dataset and i am using pretrainedmodels package. i have modified my input and final layers as suggested in this sitehttps://github.com/Cadene/pretrained-models.pytorch.My code snippetmodel = pnasnet5large (pretrained=“imagenet”)model.conv1 = nn.Conv2d(4, 6... | ptrblck | Based on the error message, it looks like the BatchNorm layer after conv1 is using 96 input channels, while you are passing 64.
Try to change the number of kernels to 96 and try it again. |
PABCSoft | Hi there! Can you suggest a simple model for complex photo enhancement (noise removal, especially in evening photos, clarity)? I am ready to train independently, I have no GPU. | ptrblck | I quite likedDeep Image Priorfor image denoising.
However, you should also find some other denoising / restoration models using PyTorch on Github. |
Mdhvince | Hi,I just want to know, how can I load my own test data (image.jpg) in pytorch in order to test my CNN.I’ve triedtest_data = datasets.ImageFolder(data_dir + '/test_cnn', transform=test_transforms)but during the test, I have too many indices because my test data is automatically labeled by ImageFolder. A solution is to ... | ptrblck | No need to excuse for that.I’ve just used an underscore in the data loading loop, to drop the targets:
for data, _ in loader:
data = data.to(device)
...
In this loop only the data is used and no targets are available.
You could also just get the targets and not use them in any way. |
Rajesh_Karmakar | Hi,I have input of dimension 32 x 100 x 1 where 32 is the batch size.I wanted to convolved over 100 x 1 array in the input for each of the 32 such arrays i.e. a single data point in the batch has an array like that.I hoped that conv1d(100, 100, 1) layer will work.How does this convolves over the array ? How many filter... | ptrblck | Well, not really. Currently you are using a signal of shape [32, 100, 1], which corresponds to [batch_size, in_channels, len].
Each kernel in your conv layer creates an output channel, as@krishnavishalvexplained, and convolves the “temporal dimension”, i.e. the len dimension.
Since len is in you… |
BlueBlazin | I got curious about how my model which is composed of several other models knows the parameters of all of them.For instance, assume I had the following code:class Net1(nn.Module):
def __init__(self):
super().__init__()
self.fc = nn.Sequential(
nn.Linear(2, 2),
nn.ReLU(),
... | ptrblck | If you set the sub-modules as attributes to the main model, its internal __setattr__ method is called.
This method makes sure to register all parameters properly. Have a look atthe source code. |
Mona_Jalal | I am not sure how to make the following code work as expected–maybe it is working correctly actually. Can you please refer to the line number with a fix or suggestion? line numbers can be seen here:https://pastebin.com/Ccy6P0DiBefore showing the code, it seems the training is actually working. However, it is very slow.... | ptrblck | In this case, yes, you should pass the entire DataLoader to train_model, since the sampler should make sure you are not sampling the test image.
You could create a list before the LOOCV loop and store all probabilities in it additionally to the predictions:
loocv_probs = []
for idx in range(nb_sam… |
bluesky314 | I have a stack of MRI images that look like10%20AM660×624 50 KBsay in shape [train_size, h,w,d]There is alot of black space making my convolution very heavy so I want to trim the images from the minimum index of the first non-zero pixel value from all the 4 corners. i.e identify the maximum distance I can trim my image... | ptrblck | This code should work for a [batch, channel, height, width]-shaped tensor:
x = torch.zeros(1, 3, 24, 24)
x[0, :, 5:10, 6:11] = torch.randn(1, 3, 5, 5)
non_zero = (x!=0).nonzero() # Contains non-zero indices for all 4 dims
h_min = non_zero[:, 2].min()
h_max = non_zero[:, 2].max()
w_min = non_zero[… |
bachir | I have a NN that ends with the following linear layersdense = nn.Linear(input_size, 1)if I useCrossEntropyLossas loss function (as I’myis supposed to be the class number) I get the following errorRuntimeError Traceback (most recent call last)
<ipython-input-39-72a754e03ca3> in <module>()
... | ptrblck | The output layer should have the number of classes as out_features.
Currently your output layer only returns one neuron, which corresponds to class0.
For a binary use case, this should work:
batch_size = 5
nb_classes = 2
in_features = 10
model = nn.Linear(in_features, nb_classes)
criterion = nn.… |
ErlendFax | On this page (deeplearning4j.org)it says:A good standard deviation for the activations is on the order of 0.5 to 2.0. Significantly outside of this range may indicate one of the problems mentioned above.How can I find the std of my activations using PyTorch?I can find the gradients like this, and they look a bit small ... | ptrblck | You could use forward hooks to print the std deviation of the layer outputs:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 3, 1, 1)
self.pool1 = nn.MaxPool2d(2)
self.conv2 = nn.Conv2d(6, 1, 3, 1, 1)
… |
fangyh | I want to normalize the input data by subtracting the 6th value. However, the results are unexpected.import numpy as np
import torch
a = np.array([[[ -29.8316, 506.7845, 5400.1382],
[ -155.6416, 73.0718, 5448.8071],
[ -52.9619, -309.7045, 5251.0830],
[ -300.4998, -332.3928, 5156... | ptrblck | Oh, this looks like a bug using the inplace subtraction.
If you use this code, it seems b has the right result:
a = torch.from_numpy(a)
b = a - a[:, 7:8, :]
a -= a[:,7:8,:]
print(a)
print(b)
I was able to reproduce this issue in 1.0.0a0+dfad8b6 and 1.0.0.dev20181007.
Thanks for catching it! Coul… |
bachir | How I could initialize the kernels of a convolution layer in pytorch? e.g.He initializationIn Keras It’s as simple asy = Conv1D(..., kernel_initializer='he_uniform')(x)But looking the signature ofConv1din pytorch I don’t see such a parametertorch.nn.Conv1d(in_channels, out_channels, kernel_size, stride=1, padding=0, di... | ptrblck | Hereis a small example how to use the same initialization as is used in Keras. |
Diego | Could anyone explain what these methods do? And in which situation should I use them?. I looked at the documentation but it only saysRegisters a * hook on the moduleand it’s not clear to me what that means. Thanks in advance! | ptrblck | Have a look atthis tutorial.
Basically the hooks can be used used to manipulate or get the intermediate activations and gradients.
You can find a simple example of using forward hookshere. |
athina | Hello, I am trying to run the code from here:GitHubphillipi/pix2pixImage-to-image translation with conditional adversarial nets - phillipi/pix2pixSpecifically I am at the bulletpoint (CPU only) and run“DATA_ROOT=./datasets/facades name=facades_generation which_direction=BtoA gpu=0 cudnn=0 batchSize=10 save_epoch_freq=5... | ptrblck | It looks like you are using LuaTorch. As LuaTorch is not in active development, I would recommend to give PyTorch a try. There is a link in the repo to the PyTorch implementation of Pix2Pix. |
Rooney.SM_Yang | x = self.tanh(x) made this RuntimeError. But if this code line is changed with “x += bias”, no error exists.Can anybody help me with error reasion?RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operationdef conv(in_channels, out_channels, kernel_size, ... | ptrblck | I’m not sure, but maybethis answeris related to this question. |
pira | load_chunks1050×264 85 KBI need to extract every 0th and 2nd Tensor from chunks.fulldata and put them in two separate Tensors (features and targets) that can be loaded into Pytorch’s DataLoader - what’s the best way to do this? I’m sure there’s some simple way to do this, but I’m new to this, so I’m kind of lost here | ptrblck | Based on your screenshot it looks like fulldata is a tuple containing 43 tensors.
I’m not sure, how you would like to split this tuple, but this would be one way:
fulldata = tuple(torch.randn(1) for _ in range(100))
features = torch.stack(fulldata[::2])
targets = torch.stack(fulldata[1::2]) |
shivangi | Can someone help me create a custom dataloader where each image and its corresponding segmentation mask is stored as a numpy array?I have no clue how to create loaders for this segmentation task | ptrblck | Sure!
The important part creating your own Dataset is to get the shapes for the data and target right.
In a simple segmentation use case where each pixel can only belongs to a single class, we would want to use a criterion like nn.CrossEntropyLoss.
Therefore your data should have the input shape … |
Abhay_Aradhya | Considering a multi-layer network L1 -> L2 -> L3 -> …and using “loss.backward()” function to update the weights.Is there a way to compute the loss between each layers as it is propagated? L1 <-(loss here?) L2 | ptrblck | If you want to use two models sequentially, you can just pass the output of one model to the other:
output1 = model1(x)
output2 = model2(output1)
As long as you don’t detach the tensors, the loss will be backpropagated to model1. |
ChandanVerma | File “C:\ProgramData\Anaconda3\envs\pytorch\lib\site-packages\torch\nn\modules\module.py”, line 479, incallresult = self.forward(*input, **kwargs)TypeError: forward() takes 2 positional arguments but 33 were givenPlease help me resolve this problem. | ptrblck | To fix your new error message, it seems you would need to add the batch dimension to your input, as currently you are passing it as [C, H, W].
Try something like data = data.unsqueeze(0) before passing it to the model.
The code you’ve posted does not show the code snippet where you pass the input … |
farazk86 | I’ve understood the process of labeling for semantic segmentation for 2D images. I was able to create label or target tensors using a colour coded method provided for the dataset. The colour codes provided were:("Animal", np.array([64, 128, 64], dtype=np.uint8)),
("Archway", np.array([192, 0, 128], dtype=np.uint8))... | ptrblck | Basically you could handle it like a 2-dimensional convolution with another “spatial” dimension.
I.e. the target should contain the class indices without a channel dimension in the shape [batch_size, d, h, w].
I’ve created a small dummy example using a simple model to segment a square in the volum… |
JuJu | I am having serious speed issues using ImageFolder and DataLoader for feeding my model. I am loading 128x128 png image frames from the KTH dataset stored on my local HDD. Initially the training is relatively fast for a few iterations using about 50% of my CPU but then it crawls to a halt with just 5% CPU usage and very... | ptrblck | If your data is stored an a HDD, I doubt you can do a lot to avoid the IO bottleneck besides maybe reducing the batch size. Based on your explanation it seems that your code is IO bound so even pre-calculating the preprocessing would not change anything.
An SSD would provide a speedup, if that’s an… |
isalirezag | I have a little difficulty understanding what happens when we use pytorch cosine similarity function.considering this example:input1 = torch.abs(torch.randn(1,2,20, 20))
input2 = torch.abs(torch.randn(1,2,20, 20))
cos = nn.CosineSimilarity(dim=1, eps=1e-6)
output = cos(input1, input2)
print(output.size())
torch.Size([... | ptrblck | Thanks for the explanation.
In this case, would you want to use the 10x10 pixels as the vector to calculate the cosine similarity?
Each channel would therefore hold a 100-dimensional vector pointing somewhere and you could calculate the similarity between the channels.
a = torch.randn(1, 2, 10, 1… |
HaziqRazali | I have a dataset that contains both the training and validation set. I am aware that I can use theSubsetRandomSamplerto split the dataset into the training and validation subsets. The dataset however, has an unbalanced class ratio. How can I also use theWeightedRandomSamplertogether with theSubsetRandomSampler? Below i... | ptrblck | That’s an interesting use case!
Basically you could just use the subset indices to create your WeightedRandomSampler, i.e. calculate the class imbalance, weights etc.
Here is a small example:
# Create dummy data with class imbalance 99 to 1
numDataPoints = 1000
data_dim = 5
bs = 100
data = torch.… |
beneyal | Hi,I’m trying to train an LSTM for language modeling using bigrams. I managed to get through the training (I don’t know if it was any good), but now I can’t use the model for inference.Code for the dataset:class RNNIndexLMDataset(data.Dataset):
def __init__(self, train):
self._bigrams = list(nltk.bigrams(tr... | ptrblck | I think your way to permute the dimensions might not work, if you provide a single sample with a batch size of 1.
Currently you are squeezing and unsqueezing the output of your embedding to change the dimensions to [seqlen, batch, input].
However, if your batch size is only 1, you’ll squeeze this … |
spacemeerkat | Hi PyTorch users,I’m training an autoencoder, but I’m interested in the output of the encoder (so the small linear layer in the middle) for my test values.Is there an efficient way of testing the encoder, once trained, separately rather than testing on the full network and pulling out the encoders output values?If not…... | ptrblck | Since your forward method just combined the encoder with the decoder, you could use this code:
model = autoencoder()
x = torch.randn(1, 4)
enc_output = model.encoder(x)
Of course, this wouldn’t work, if your model applies some other calls inside forward.
Another approach would be to use forward h… |
bluesky314 | Hey I have a very simple NN with only one layer. I was going through someones tutorial and they did not take the log in the negative log likely hood loss. This is on the MNIST flattened dataset. When I take the log and train, my model does not learning anything while without the log it achieves 90% accuracy. How can lo... | ptrblck | Your model already returns the log_softmax. So using another log on this tensor is not a good idea.
You could just for the sake of debugging use softmax and then call your nll2 method to see if the model is learning.
However, calling log on softmax might be numerically unstable and is generally no… |
Srinjay_Sarkar | Does Pytorch support something like transforms(used for DataLoader) for image data loaded with a TensorDataset method? | ptrblck | Most image transformations are defined for PIL.Images.
You could add transforms.ToPILImage() as the first transformation, which will add a small overhead, but allows you to use any torchvision.transforms. |
HaziqRazali | I installed PyTorch on my laptop only to find out that my GPU is not supported. Is there a version that I can use that still supports my GPU ? Or are there any other solutions ?/home/haziq/anaconda3/envs/dl/lib/python3.5/site-packages/torch/cuda/init.py:97: UserWarning:Found GPU0 GeForce GTX 780M which is of cuda capab... | ptrblck | You could build PyTorch from source.
The installation is describedhere.
Let me know, if you encounter any problems. |
hleb | Hi, I’ve done a simple neural network program with pytorch but gets this RuntimeError: Expected object of type torch.LongTensor but found type torch.FloatTensor for argument#2‘mat2’Can anyone help me out with it please? here is my code:import torch.nn as nn
import torch
class NeuralNet(nn.Module):
def __ini... | ptrblck | state is a torch.LongTensor, since you created it using integer values.
You could transform it to a FloatTensor, if you
pass float values (torch.tensor([1., 4., 3., 6., 0.])),
define a dtype, state = torch.tensor([1, 4, 3, 6, 0], dtype=torch.float32)
transform the tensor, state = torch.tensor([1… |
bluesky314 | Hey, I am training a simple Unet on dice and BCE loss on the Salt segmentation challenge on Kaggle. My model’s loss is not changing at all. In this example, I pick a dataset of only 5 examples and keep interacting through and get a constant loss. My gradients are not getting backdroped I think, what can I do?class Data... | ptrblck | Just to make sure, you are runningthiscode and get a constant loss?
Which PyTorch version are you using? If you are using an older version (< 0.4.0), could you wrap your tensors into Variables and run it again? |
Charmander | Is there any method to reset the parameters of the model?Or I have to save the state_dict of a new model and load it when I want to retrain the model? | ptrblck | It depends on your use case.
If you need exactly the same parameters for the new model in order to recreate some experiment, I would save and reload the state_dict as this would probably be the easiest method.
However, if you just want to train from scratch using a new model, you could just instan… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.