user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
Can_Keles
Hi, i was looking for a Weighted BCE Loss function in pytorch but couldnt find one, if such a function exists i would appriciate it if someone could provide its name.
ptrblck
nn.BCEWithLogitsLosstakes a weight and pos_weight argument. From the docs: weight (Tensor, optional ) – a manual rescaling weight given to the loss of each batch element. If given, has to be a Tensor of size nbatch. pos_weight (Tensor, optional ) – a weight of positive examples. Must be a…
John_Deterious
I have a parameter that is learnable, I want the model to update it. Here is how I attached it to the model:class Dan(nn.Module): def __init__(self): super(Dan, self).__init__() blah blah blah self.alpha = t.tensor(0.5, requires_grad=True).cuda()It is alpha. However, after training, I find its value...
ptrblck
Although the tensor was defined in the __init__ method, it won’t show in the interal parameters: class Dan(nn.Module): def __init__(self): super(Dan, self).__init__() self.alpha = torch.tensor(0.5, requires_grad=True) model = Dan() print(list(model.parameters())) > [] As@Mazh…
Bruno1
Hi,I would like to collapse a serie of 2d convolutions to a single conv operation.Basically I’d like to make the pytorch convolution associative.For example if I have something likey = F.conv2d(F.conv2d(a1,k1),k0)I’d like to write it this way: y = F.conv2d(a1,K) (where K depends on k1 and k2).If my calculus are not wro...
ptrblck
The convolution operator in PyTorch is a cross-correlation and not a convolution in the signal processing sense. From thedocs: […] where ⋆\star⋆ is the valid 2Dcross-correlationoperator, N is a batch size, C denotes a number of channels, H is a height of input planes in pixels, and W is width …
Qu_Yukun
vggface_bug21247×207 34.4 KBAs the pictures show, I used pytorch to load vgg_face. But it appeared error.I switch a package to load vggface. It can handle t7 format file. But it aslo did’t wrok.The error message is as follows:Traceback (most recent call last):File “”, line 1, inFile “C:\Users\qu199\AppData\Local\Progra...
ptrblck
It looks like you are trying to load a Torch7 model. Note that Torch7 is not under active development anymore and I would recommend to switch to PyTorch. There should be a few vggface-pytorch repos on GitHub.
John_Deterious
The following is from official tutorial. My question is: what’s the point of no_grad here? My understanding is that it is only useful if you want to save costs while in running the forward pass.with torch.no_grad(): for param in model.parameters(): param -= learning_rate * param.grad
ptrblck
The no_grad guard disables gradient calculations, so Autograd won’t track any operations applied in this block. While it’s useful for inference, it can be also applied when you would like to manipulate some internal parameters without using the .data attribute.
ljj7975
I am trying to train a model for 1d data that has 500 features.Unfortunately, since the common implementation of GAN is for image,I wasn’t able to find a working version of GAN for 1d data.Does anyone know any public implementation?Is there anything specific that I have to keep in mind?I preprocessed the input data to ...
ptrblck
I’ve reimplemented a toy example fromthis blog posta while ago and you can find the codehere. Since this code is quite old by now, you might need to change some details (e.g. swap data[0] for .item()).
SamT
Hi, did anyone successfully implemented the pixel-wise weighted loss function that was described in the Unet paper?Thanks
ptrblck
I’ve implemented a weighted pixelwise NLLLoss a while ago inthis topic. The code is quite old (e.g. don’t use Variables anymore), but might be a good starter for your custom loss.
isalirezag
so im using the pytorch-nighty and wanna see how to use tensorboard in pytorchI am following steps here:https://pytorch.org/docs/stable/tensorboard.htmleverything works okaywhen i reach to this line:tensorboard --logdir=runsI have no clue what should i do? how should i visualize?if i just have that in my code it will g...
ptrblck
In your Python script, you would have to create a SummaryWriter and log some values/images/etc. using it as described in the code example in thedocs. In another terminal you then start TensorBoard using tensorboard --logdir=runs with additional arguments if needed. This will create the tensorboar…
mchowdhu
I am trying to load my custom data set in Pytorch but every time getting ‘NotImplementedError’.I could not make sense where I am wrong.here is my codefrom __future__ import print_function, division import os from torch import nn import torch,torchvision import pandas as pd import pandas from torchvision.transforms im...
ptrblck
__len__ and __getitem__ are at the wrong indentation, thus not part of the Dataset class. Move them an indentation to the right and run your code again.
vihas_makwana
import torch.nn as nnimport torch.nn.functional as Fimport numpy as npimport matplotlib.pyplot as pltimport torchvisionimport torchvision.transforms as transformsdata2=torchvision.datasets.VOCDetection("./",download=True,transform=transforms.ToTensor(),target_transform=transforms.ToTensor())img,tar =data2[0]I get the f...
ptrblck
You would have to remove the target_transform and use the XML tree for your detection task. Have a look atthis tutorial. While another dataset is used, it might be a good starter for your VOCDetection.
xingjici
Hi.I am running a NAS (neural network search). The capacity of these models are too large even with batch_size =1 accounting for 18GB memory for a single GPU.I have 4GPUs with with 12GB memory (48 GB totaly), how to run these code?
ptrblck
Depending on the model architecture, you could try to apply model sharding as shown inthis exmaple. This approach would store submodules on different devices and transfer the output to the corresponding device in the forward method. Would this be possible or is a single layer already creating the…
Vigneswaran
Hi, the question is very basic. PyTorch uses default weight initialization method as discussedhere, but it also provides a way to initialize weights using Xavier equation. In many places1,2the default method is also referred as Xavier’s. Can anyone explain where I am going wrong? Any help is much appreciated
ptrblck
The post is from January 2018 and outdated by now. You can find the current weight inithere, which is init.kaiming_uniform_(self.weight, a=math.sqrt(5)) for the weights.
vihas_makwana
import torchvision.transforms as transformsdata=torchvision.datasets.VOCSegmentation("./",download=True,transforms=transforms.Compose([transforms.ToTensor()]))img,tar=data[0]I get following error:/usr/local/lib/python3.6/dist-packages/torchvision/datasets/voc.py ingetitem(self, index)205206 if self.transforms i...
ptrblck
You are currently trying to pass a single transformation to transforms, which expects a StandardTransform object as seenhere. Try to use transform=transforms.ToTensor() instead (note the missing s on the left hand side) to transform the data. If you also want to pass a transformation for the targ…
AndrewSoul
Hi, I want to ask about the difference between the following two pieces of code:class ModelOutputs(): """ Class for making a forward pass, and getting: 1. The network output. 2. Activations from intermeddiate targetted layers. 3. Gradients from intermeddiate targetted layers. """ def __init__(self,...
ptrblck
I’m not sure, why the shapes differ, but apparently the wrong gradients are stored. Here is a small dummy example using vgg16: grads = [] def save_grad(grad): grads.append(grad) # Create model model = models.vgg16() model.eval() # First approach x = torch.randn(1, 3, 224, 224) output = model…
Diego
I installed pytorch nightly for cuda10 using pip3 by running:pip3 install torch_nightly -fhttps://download.pytorch.org/whl/nightly/cu100/torch_nightly.htmlNow whenever I try to import torchvision I get:from torchvision import _CImportError: libcudart.so.9.0: cannot open shared object file: No such file or directoryCuda...
ptrblck
The mentioned package was maintained by@stasand, if I’m not mistaken, wasn’t updated anymore, so you would have to wait for the next official torchvision-nightly release or build from source.
ahmed
I am designing a object detector. I want to ignore images in the dataset that do not have any annotations. Is there any way I can do that?
ptrblck
Would it be possible to compute the invalid indices before and pass them as a list to your Dataset? If so, you could just add an offset to an index vector using the invalid indices. E.g. if the invalid indices are at 2 and 4, the indices list could be: self.indices = [0, 1, 3, 5, ...] index = sel…
Hasan_Sait_ARSLAN1
Hi,I am using a linear layer like the following:self.emb_to_seq = nn.Linear(512, 40000)img_seq = self.emb_to_seq(V)the tensor V has the shape of (8, 121, 512) and type of CudaFloatTensor.When I want to print it as the following;print img_seq,I get the following error:RuntimeError: cuda runtime error (59) : device-side ...
ptrblck
Could you run the code an CPU and check, if you’ll get any errors? Often the error messages for a CPU run are clearer than the CUDA equivalent.
ajhanwar
Hi all, I’m working with the MNIST dataset available throughtorchvisionand am trying to visualize the data (average digit, overlaid digits, etc.). While I am able extract/transform/load the dataset I can’t seem to find a way to extract the data itself to perform operations such as slicing and subsetting.Any clarificati...
ptrblck
You could access the underlying .data and .target attributes: import torchvision.transforms.functional as TF dataset = datasets.MNIST(root='./data', transform=transforms.ToTensor()) data = dataset.data print(data.shape) # torch.Size([60000, 28, 28]) img = TF.to_pil_image(d…
WeiQin_Chuah
Hi,So I did the training of my neural network, say on GPU#3and the state dict is saved. Do I have to use GPU#3every time when I want to load my state dict?Also, will it work if I don’t put my model to cuda before loading the state dict into the model?Thank you.
ptrblck
You can use the map_location argument in torch.load to map your GPU tensors to the CPU as explained in thenote section. Alternatively you could of course push the model to the CPU before saving its state_dict.
DuttaAbhigyan
So I was experimenting with my NN when while changeF.leaky_relu(x,0.2)toF,relu(x)I accidentally changed it toF.relu(x, 0.2). The training progressed fine, but is there any significance of the 0.2?
ptrblck
The 0.2 in F.relu will be treated as the inplace argument, which will be interpreted as inplace=True.
Niki
I am new about using CUDA. I am using the following code for seeding:use_cuda = torch.cuda.is_available() if use_cuda: device = torch.device("cuda:0") torch.cuda.manual_seed(SEED) cudnn.deterministic = True cudnn.benchmark = Falsethat is correct if I use this code for the network?if ...
ptrblck
If you would like to use the benchmark mode, then yes. If activated, cudnn will perform some benchmarking internally using the current input shape and your model to determine the best performing algorithms to use for the operations. This will most likely slow down the first iteration, but should g…
chaslie
Afternoon,I am hoping someone can help me i am getting the following error message:output = input.matmul(weight.t())RuntimeError: size mismatch, m1: [2 x 10], m2: [2 x 10] at C:/w/1/s/tmp_conda_3.7_044431/conda/conda-bld/pytorch_1556686009173/work/aten/src\THC/generic/THCTensorMathBlas.cu:268class Decoder(nn.Module): ...
ptrblck
I’m not familiar with your use case, but you could reshape the output of your linear layer before feeding it to the nn.ConvTranpose1d layer or just add a dummy channel dimension using: output = output.unsqueeze(1) Based on the number of input channels in co1, it seems the dummy channel dimension i…
dasayan05
I was running this very simple (toy) code to observe the change in LR with epochs when there is a schedular. I used the simpleStepLR().import torch print('PyTorch version: {0}'.format(torch.__version__)) model = Net(n_in, n_out) # 'Net' is a simple MLP optimizer = torch.optim.SGD(model.parameters(), lr=1e-2) schedular...
ptrblck
This seems to be related tothis issue. If you print the optimizer’s learning rate, you should see that it’s behaving as expected: model = nn.Linear(1, 1) # 'Net' is a simple MLP optimizer = torch.optim.SGD(model.parameters(), lr=1e-2) schedular = torch.optim.lr_scheduler.StepLR(optimizer, step_si…
AndrewSoul
Hello.Three different input: images1, images1_sub(a subset of images1), images2,.One network: model.... ... optimizer.zero_grad() output1,intermediate_feature_map_1 = model(images1) # get output and intermediate feature map output1_sub, intermediate_feature_map_sub1 = model(images1_sub) # get output and intermediate ...
ptrblck
Thanks for the information. I though you would like to split the spatial size. If you split the batch, you would have to take care of e.g. batch norm layers, as the running stats will differ. Besides that it should yield the same output. What results did your test yield?
kekday
Hi,Looking at the example for how LBFGS needs a closure() function to be used (https://github.com/pytorch/examples/blob/master/time_sequence_prediction/train.py), is there a way I could plot the loss as well? Simply appending the loss calculated inside closure() to a list initialized outside closure doesn’t seem to wor...
ptrblck
Do you get any error or why is it not working? Simply appending loss.item() to a list seems to work: losses = [] def closure(): optimizer.zero_grad() out = seq(input) loss = criterion(out, target) print('loss:', loss.item()) losses.append(loss.item()) loss.backward() r…
Achakma
Hello,I have two classifiers and two associated discriminator networks. While I can create the instances of Classifier networks but I can’t in the case of discriminator networks. It generates an “AttributeError: ‘torch.device’ object has no attribute '_apply’”. I’ve seen several related posts and I also checked my PyTo...
ptrblck
You are not creating an instance of the discriminator, i.e. you forgot the parentheses. Try to call Discriminator().to(DEVICE) instead. PS: It’s better to post the code directly by wrapping it in three backticks ``` instead of screenshots. This will allow the search to index it and allows us to co…
zahra
Dear ExpertsI try to generate a simple custom linear layer as follows, but the prediction of the network is incorrectI tried hard for more than 2 weeks but I could not solve it. I hope someone help me.class linearZ(torch.autograd.Function): @staticmethod def forward(ctx, input, weight): ctx.save_for_b...
ptrblck
I’m not sure how linearZ is supposed to work, as it seems like you would like to calculate the gradients in backward as well as manipulate some model parameters. Could you explain the use case a bit as I think both steps (gradient calculation and parameter manipulation) should be done separately. …
jchaykow
If I overwrite a layer in the pretrained model the training is fine, but if I remove the final layer and then re-append the same layer - the training fails.I’m starting here:https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.htmlHere’s my final code:import torch import torch.nn as nn import torchvision.m...
ptrblck
If you wrap all modules in an nn.Sequential module, you are not using the original forward method anymore, and thus are missingthis reshape operation. You could add a custom Flatten layer or write your own forward method using a custom nn.Module: class Flatten(nn.Module): def __init__(self): …
shinyeyes
Hi,I’m bit puzzled on howscatter_add(https://pytorch.org/docs/stable/tensors.html#torch.Tensor.scatter_add_) works.ProblemWhy can’t I reproduce the same result with for-loops?self[index[i][j][k]][j][k] += other[i][j][k] # if dim == 0 self[i][index[i][j][k]][k] += other[i][j][k] # if dim == 1 self[i][j][index[i][j][k]...
ptrblck
The second example yields the same result on my machine. Could you make sure to reinitialize b and check the result again? The first call raises an error, since you have a dimension mismatch. If you expand indices and updates, the code will also return the same values: array = np.array([[1,2,3],…
MasayoMusic
I am going through the tutorial below, but I am confused as to how the right image shape is created via the generator.https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.htmlIt seems the latent vector created is a one dimensional vector of size 100:We are feeding that into ConvTranspose2D as getting back a 512...
ptrblck
By feeding the noise tensor of [batch_size, nz, 1, 1] into the first transposed conv layer, the spatial size will be increased. Let’s have a look at a simple use case using just a single pixel value: b = 1 nz = 1 noise = torch.ones(b, nz, 1, 1) conv = nn.ConvTranspose2d( nz, nz, 4, 1, 0, bias=Fals…
Alan_Wang
I have an autoencoder deep network, and I notice that when I usenn.Sequential, the generalization performance is better than when I don’t use it (i.e. explicitly pass the inputs through layers). Has anyone else noticed this behavior, or can provide an explanation as to why this is? Does Pytorch handle regularization di...
ptrblck
Thanks for the code. The difference is indeed in the usage of the batch norm layers. While you are initializing two different nn.BatchNorm1d layers in your sequential approach, you are reusing the same in your manual approach. Could you create two separate batch norm layers and run the test again…
blackbirdbarber
I am using this code and I have single question:import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader, Dataset, TensorDataset from torch.optim import * import torchvision dl = DataLoader( torchvision.datasets.MNIST('/data/mnist', train=True, download=True, ...
ptrblck
You should find plenty of custom Datasets in this discussion board. Here is an example: class MyLazyDataset(Dataset): def __init__(self, image_paths, targets, transform=None): self.image_paths = image_paths self.targets = targets self.transform = transform …
crytorch
I would like to index a 2-D matrix row-wise and re-assign values.For example, first consider a 1-D vector case where we have three 1-D tensorst1, indexes, t2with the same shape. We can do this indexing and re-assignment as follows:indexes = torch.tensor([0, 2, 1, 3]) t1 = torch.tensor([0.0, 0.0, 0.0, 0.0]) t2 = torch.t...
ptrblck
.scatter_ should work in this case: indexes = torch.tensor([[0, 2, 1, 3], [1, 0, 3, 2]]) t1 = torch.zeros_like(indexes).float() t2 = torch.tensor([[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]]) t1.scatter_(1, indexes, t2)
caiom
Using the following code:import torch import numpy as np from vgg_unet_aspp_detection import UNetVgg import os import psutil import gc process = psutil.Process(os.getpid()) device_str = "cpu" device = torch.device(device_str) model = UNetVgg(4, device) model = model.eval() model = model.to(device) for i in ran...
ptrblck
Could this be related to22127?
Omar2017
Hican anyone help me how to solve this problem pleasemodel = ViolenceModel(modelUsed,pretrained) svclassifier = SVC(kernel='linear') trainParams = [] for params in model.parameters(): if params.requires_grad: trainParams += [params] model.train(True) if(torch.cuda.is_available(...
ptrblck
features seems not to be detached, so could you call features = features.detach().cpu().numpy() before passing it to the svm?
aklagoo
I’m trying to implement a skip-gram model. When I pass the input vector to the hidden layer, I get the error:RuntimeError: Expected object of scalar type Long but got scalar type Float for argument#2‘mat2’ONE_HOT_SIZE = len(dictionary) EMBEDDING_DIM = 200 EPOCH_NUM = 5 def one_hot(index): one_hot_array = torc...
ptrblck
Could you print the shape or words? nn.Linear expects the input as a tensor of shape [batch_size, *, in_feautres]. Also, nn.NLLLoss expects a LongTensor as the target containing the class indices. It should therefore not be one-hot encoded.
talhak
As the title clearly describes, the loss is calculated asnanwhen I useSGDas the optimization algorithm of myCNNmodel. Between, no issues et al when I useAdamas the optimizer of my network.Here is the whole code:num_epochs = 20 # 1000 batch_size = 8 learning_rate = 0.0001 momentum = 0.5 # for SGD log_interval = 50 cl...
ptrblck
Do you see the NaN from the first iteration or after a while? In the latter case, could you check the loss values, as they might just blow up? If that’s the case, check the gradients (or their norm). Is the input to your model normalized? If not, try normalizing it, as large input values might al…
talhak
I have a CUDA supported GPU (Nvidia GeForce GTX 1070) and I have installed both of the CUDA (version 10) and the CUDA-supported version of PyTorch.Despite my GPU is detected, and I have moved all the tensors to GPU, my CPU is used instead of GPU as I see almost no GPU usage when I monitor it.Here is the code:num_epochs...
ptrblck
That’s strange, since the data loading time seem to be completely hidden behind the computation. I just tried your code on my machine and simplified it a bit: removed the test loop used random inputs (torch.randn as data and torch.randint as target) used an input batch of [20, 1, 100] Using thi…
marx_was_right
I’m trying to load trained model weights and get this error message:IncompatibleKeys(missing_keys=[], unexpected_keys=[])I can’t figure out the issue because when I inspectmodel.state_dict().keys()andstate_dict.keys()all of the keys are the same!model.state_dict().keys() == state_dict.keys()producesTrueWhat else can be...
ptrblck
This message just states, that no incompatible keys were found. Since this message confused a lot of users, it was changed inthis PR, which should make it available in the current nightly build.
Shakir_Khurshid
**The model is 79.82897162437439 % certain that the image has a predicted class of2How to make the output show the real name if the class instead of the index ?def predict(image, model): # Pass the image through our model image = image.to(device) output = model.forward(image) # Reverse the log fun...
ptrblck
You could create a mapping between the class indices and the corresponding names using a dict: idx_to_name = { 0: 'class0', 1: 'class1', ... } print(idx_to_name[target])
jack1234
if I callmodel.cuda()in pytorch where model is where model is a subclass ofnn.Module, and say if I have four GPUs, how it will utilize the GPUs and how do I know which GPUs that are using?
ptrblck
model.cuda() will push the parameters to the default device. If you print a parameter’s device, you should see, which GPU is used: print(model.fc.weight.device) > device(type='cuda', index=0) Also, have a look at nvidia-smi to see, which GPUs are used. If you would like to use data parallel (cop…
styx97
Hi All,I’m trying to remodel alexnet to a binary classifier. I wanted to add a Softmax layer to the classifier of the pretrained AlexNet to interpret the output of the last layer as probabilities. Till now the code I have written is -model_ft = models.alexnet(pretrained=True) # Frozen the weights of the cnn layers towa...
ptrblck
The first dimension is the batch_size, so if you are passing 4 samples, the output will have the shape [4, 2].
ASHUTOSH_CHANDRA
I’ve 2 doubts in the official formula for calculating shape of output after applying 2d convolutional operation :Why do we add 1 and take floor, why don’t just take ceiling ?Why do we add 1 in the numerator ?
ptrblck
floor + 1 is different to ceil for the case of a zero, which is needed in the calculation: floor(0) + 1 = 1, while ceil(0) = 0 We subtract 1 in the numerator. Have a look at theConv arithmeticto derive the formula. Basically if you reformulate the dilated conv output shape formula, you’ll ge…
dean
I want to compute a pixel-wise loss by summing up distances to pixels neighbors. Is there a “sliding window” manner to do that with Pytorch?
ptrblck
You could probably use unfold to get the image patches and calculate the loss on these. Have a look atthis postfor an example.
NOP
This will at the very end give me the max element in 3D tensor.Is there a better way?values = torch.randn(32, 32, 32) values, indices = values.max(0) print(values, indices) values, indices = values.max(0) print(values, indices) values, indices = values.max(0) print(values, indices) #tensor(4.0173) tensor(31)
ptrblck
If you just skip the dim argument, you’ll get the max value: a = values.max() # if you need the index also b = torch.argmax(values) idx = np.unravel_index(b, values.shape)
Even_Oldridge
I’m curious why the .cuda is necessary in this line of code when targs is on the gpu?ts = targs[::self.ns].type(torch.FloatTensor).cuda()-1.without the .cuda I get an error about a cpu backend. Does casting really move a tensor, and what’s the reasoning behind that?Also I’m hoping behind the scenes this is being kept ...
ptrblck
.type(torch.FloatTensor) should move the tensor to the CPU. I assume you would like to change the dtype of the tensor without changing the device? If so, you could use targs[::self.ns].float() or targs[::self.ns].to(torch.float).
noornk
Hi all! I’m trying to find objects in medical images, which are grayscale, and I only have two class: background and the lesion.I’m scaling my images to 256*256, and I’ve mapped the masks png color numbers as suggested by@ptrblckin multiple topics. However, I’m still getting the error in the title for this line:loss =...
ptrblck
If your targets contain the class indices already, you should remove the channel dimension: target = target.squeeze(1)
barakb
Hi I have 2 tensors, let’s say Image with size (batch,3,224,224) each, lets name it T1 and T2.I want to concatenate the tensor in the channels dimension, means an output of (batch,6,224,224).Now I want the output tensor will look like this (In the channel dimension): (1st channel of T1,1st channel of T2,2nd channel of...
ptrblck
This code should work: a = torch.arange(0, 3).unsqueeze(0).unsqueeze(2).expand(2, -1, 4) b = torch.arange(3, 6).unsqueeze(0).unsqueeze(2).expand(2, -1, 4) c = torch.stack((a, b), dim=2) print(c.view(2, 6, 4)) Note that I initialized each channel with a certain value, so that you can check the in…
Robin_Chacko
Hello, I would like to have the MNIST data loader (torchvision package) to return an extra item for eg, Mean pixel value of the image along with the Image and the target. I have created a subclass which override theget_itemmethod and returns the extra item.import torchvision.datasets as dataset from torch.utils.data im...
ptrblck
img will have 3 dimensions ([1, 28, 28]), which will yield this error. The reason for the additional channel dimension is, that each sample will already be transformed in the super().__getitem__() method. In particular Normalize will add the channel dimension, if you pass the MNIST images to this …
NOP
class M(nn.Module): def __init__(self): super().__init__() self.l1 = nn.Linear(50*50,100) self.l2 = nn.ReLU() self.l3 = nn.Linear(100,100) self.l4 = nn.Tanh() self.l5 = nn.Linear(100,10) self.l6 = nn.LogSoftmax()Having module M, if I don’t setself.l6 ...
ptrblck
The dim argument defines which dimension should be used to calculate the log softmax, i.e. in which dimension the class logits are located. Have a look at this small example using softmax: x = torch.randn(5, 3) x0 = F.softmax(x, dim=0) print(x0) > tensor([[0.1313, 0.0170, 0.4122], [0.0167,…
Muhsinka
In:img.shapeOut:torch.Size([1, 28, 28])In:img = images.unsqueeze(1)In:img.shapeOut:torch.Size([4, 1, 1, 28, 28])Can anyone pls tell me why .unsqueeze fauntion adds 2 dimentions?batch size = 4
ptrblck
Are you sure you are not mixing up img and images? Additionally to the unsqueezed dimension img also has suddently a batch size of 4, which wasn’t there previously. Could you print images.shape before unsqueezing it?
ljj7975
I have simple GAN so I do following.real_target = 1s fake_target = 0s gen_net.train() dis_net.eval() gen_optimizer.zero_grad() generated = gen_net(noise) gen_loss = loss_fn(dis_net(generated), real_target) gen_loss.backward() gen_net.eval() dis_net.train() dis_optimizer.zero_grad() input_data = torch.cat(generated...
ptrblck
If your generator was already trained in the first step, you could try to detach the generated tensor from it before feeding it to the discriminator: input_data = torch.cat(generated.detach(), real) This will detach generated from the computation graph, so that the backward pass will stop at this …
Manik_Hossain
whats the difference between nn.relu() vs nn.functional.relu()and if there no difference so why such duplication…?
ptrblck
nn.ReLU() creates an nn.Module which you can add e.g. to an nn.Sequential model. nn.functional.relu on the other side is just the functional API call to the relu function, so that you can add it e.g. in your forward method yourself. Generally speaking it might depend on your coding style if you pr…
NOP
Fromhttps://pytorch.org/docs/stable/_modules/torch/nn/functional.htmlI see[docs]@weak_script def dropout(input, p=0.5, training=True, inplace=False): # type: (Tensor, float, bool, bool) -> Tensor r""" During training, randomly zeroes some of the elements of the input tensor with probability :attr:`p` us...
ptrblck
You can find the implementationhere. A quick code sample also shows that the behavior is changed in training/eval: x = torch.randn(1, 10) print(F.dropout(x, p=0.5, training=True)) >tensor([[-0.0000, 1.2927, -0.0000, 0.0000, 1.2973, -0.0000, -1.5645, -0.0000, -0.0000, -0.0000]]) print…
shubhvachher
You shouldn’t be doing that, right? fmi as well asmy issue here
ptrblck
torch.optim.Adam for example has internal states, as it computes the running averages of gradient and its square. If you don’t need to reset the optimizer (there might be use cases I’m not aware of), I would recommend to initialize it once and just use it inside the training loop.
AmardeepGanguly
This is my codeclass MyModel(nn.Module): def __init__(self, num_classes1, num_classes2): super(MyModel, self).__init__() self.model_inception = models.inception_v3(pretrained=True) num_ftrs = self.model_inception.AuxLogits.fc.in_features self.model_inception.fc = nn.Sequential() ...
ptrblck
The inception_v3 model returns two outputs in the default setting: the output from the last layer and an auxiliary output. If you don’t want to use the aux_output, just pass the last output to self.fc1: x = self.model_inception(x) out1 = self.fc1(x[0]) out2 = self.fc2(x[0])
NOP
This small code:import torch import torch.nn as nn class M(nn.Module): def __init__(self): super().__init__() self.l1 = nn.Linear(10,100) def forward(self, inp): out = self.l1(inp) return out m = M() inp = torch.empty(10, 100) out = m(inp) print(...
ptrblck
The number of input features for the linear layer is defined as 10, while you pass an input of [batch_size=10, features=100]. Also note, that torch.empty returns an uninitialized tensor, so you might have random values, Infs, NaNs, etc. in the tensor.
blackbirdbarber
In case:t=torch.Tensor(64,3,28,28)I would like to have all values 32, not 0 by default.
ptrblck
torch.Tensor won’t initialize all values with 0s, but will use uninitialized memory, so you should manually initialize it. To set all values to a constant value, you could use several approaches: t = torch.empty(64, 3, 28, 28).fill_(32.) t = torch.ones(64, 3, 28, 28) * 32.
M_S
Hi,Many torchvision models are also available in a fully trained mode.As it is not obvious, I’d like to know what’s the input format that the models are trained on.I’m assuming it’s color images so 3 channel tensors, but is it RGB or BGR (like in OpenCV \ cv2)?Also what’s the range values? Is it uint8 ([0:255]) or a fl...
ptrblck
From thedocs: All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded in to a range of [0, 1] and then normalized using mean = [0.485, 0.456,…
mtbler
Hi thereI am trying to index a one-dimensional tensor with a two-dimensional index.Innumpy, the following works:a = np.array([5 6 7 8 9]) idx = [[1 2] [4 4] [3 3] [0 1] [2 0]] # such that a[idx] = [[6 7] [9 9] [8 8] [5 6] [7 5]]How do I achieve the same thing in pytorch 1.0?Doinga = torch.tensor(a) idx = tor...
ptrblck
Your code just works fine: a = torch.tensor([5, 6, 7, 8, 9]) idx = torch.tensor([[1, 2], [4, 4], [3, 3], [0, 1], [2, 0]]) a[idx] > tensor([[6, 7], [9, 9], [8, 8], [5, 6], [7, 5]])
singhvishal0209
how do I change predicted output pixel value which lies between 0 to 1 to binary values 0 or 1 for each pixel in semantic segmentation?This is how my input, predicted and label image looks like. I want to make the predicted image into black & white.result21224×426 68 KBI am implementing U-net codeMy training code:for e...
ptrblck
You can just apply a threshold: threshold = 0.5 pred = outputs > threshold If your model has a single output channel with predictions in the range [0, 1], _, predicted = torch.max(outputs_new.data, 1) will give you an output of all zeros. This method is usually applied for multi-class classificat…
Nimrod_Daniel
Hi,I have a MDNet with 3 conv layers and a few fully-connected layers afterwards, and I want to do feature selection after the third conv layer, because there’s some redundancy (the net is doing tracking for a single object, thus it’s like a two class classification - background and object).I have the feature vector (o...
ptrblck
Sure! This code snippet would work for a batch size of 2. Note that I assume you are using a constant number of selected features in each batch (in this case 3 features). class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.conv1 = nn.Conv2d(1, 5,…
ahmed
I want to train from scratch the AlexNet model:model = models.alexnet(pretrained=False) num_features = model.classifier[6].in_features features = list(model.classifier.children())[:-1] # Remove last layer features.extend([nn.Linear(num_features, 4)]) # Add our layer with 4 outputs model.classifier = nn.Sequential(*feat...
ptrblck
Your current code will only save the model.state_dict, i.e. all parameters of your model. The model structure will not be saved, so you should always keep the model definition close to the checkpoint. Also, if you would like to use this checkpoint for finetuning, I would recommend to store the opt…
akhilpan
I want to remove a few channels depending on some criterion. For example, I may remove based on probabilities. If my probability vector is [ 0.5, 0.3, 0.1, 0.1] corresponding to four channels. How can I keep top 50% channels and remove all others?
ptrblck
Probably I misunderstood your use case. I thought you wanted to sample using the probabilities. In case you just want to keep the two channels with the highest probabilities, you could use a mask or slice the input. This depends on your current use case. batch_size = 1 c, h, w = 4, 5, 5 x = torch.…
blackbirdbarber
How do you calculate the number of activations for :l = nn.Linear(10, 100) c = nn.Conv2d(1, 2, kernel_size=(3,4))I would say 1000 forl, if this is the number of weights. But I am not sure.
ptrblck
The linear layer is pretty straightforward, as the output activation will have the shape [batch_size, *, out_features]. The activation of the conv layer is a bit trickier, as the shape depend on the spatial size of your input: x = torch.randn(2, 10) out = l(x) print(out.nelement()) # batch_size *…
blackbirdbarber
Strange but I would like to load mnist labels usingtorchvision.datasets.MNIST. I loaded images like this:train_loader = torch.utils.data.DataLoader( torchvision.datasets.MNIST('/data/mnist', train=True, download=True, transform=torchvision.transforms.Compose([ ...
ptrblck
You can print the labels using dataset.targets.
gtm2122
Hi, I recently installed torchvision 0.3 on linux from sourcemy below code does not work during training mode but works during eval mode. It gives the error“Expected more than 1 value per channel when training, got input size torch.Size([1,256,1,1])”import torchvision.models.segmentation as seg_modelimport torchimg = t...
ptrblck
Most likely you’ll see this error in a batchnorm layer, which cannot calculate the running batch statistics from a single value in each channel. It’s similar to the Inception3() from torchvision, which also expects at least two samples in a batch during training. Would it be possible to provide mo…
YN-Tang
Hi guys,I’m troubling with the cuda version for pytorch. Lately I’ve changed my working environment from Titan Xp to RTX2080ti. Then the same code went into problems like this:File "train.py", line 183, in train outputs = model(inputs) File "/usr/local/lib/python3.5/dist-packages/torch/nn/modules/module.py", line...
ptrblck
Did you install PyTorch from source or did you use the binaries? In the latter case CUDA (and other libs) will be shipped in the binaries, so that you don’t have to install a local CUDA version (and it will be ignored). Have a look at theinstall instructionsand select the command for CUDA10. I …
patrick-han
I see this question has been previously asked, but the solutions posted don’t seem to be working for me/the traceback message is different. For some reason my model is failing during an application oftransforms.Normalize():transforms_ = [transforms.Normalize((0.5,), (0.5,))] self.transform = transforms.Compose(transfo...
ptrblck
This was a known bug and was recently fixedhere. Since the PR was merged 4 days ago, you might need to build from source.
blackbirdbarber
Forconv2Dcan you specifyconvolution or correlation.Fromsource:Many machine learning libraries implement cross-correlation but call it convolution.Is this the case with PyTorch? Does it matter. I haven’t found corelate2D class.Comments…
ptrblck
PyTorch uses cross-correlation. It shouldn’t make any difference, since the kernels will just be flipped for a convolution. However, if you are trying to apply some manually defined kernels for image processing (e.g. edge detectors), you should flip them to get the desired results. That being sai…
mateja
I’m trying to create a mask based on an index tensor.The mask size is [6, 1, 25]The index size is [6, 1, 12]First I have an index tensorindices:print(indices) tensor([[[ 0, 1, 2, 5, 6, 7, 12, 17, 18, 22, 23, 21]], [[ 2, 3, 4, 7, 8, 9, 15, 16, 20, 21, 22, 13]], [[ 0, 1, 5, 6, 10, 11, 15, 1...
ptrblck
I think you could use scatter_: mask = torch.zeros(6, 1, 25) mask.scatter_(2, indices, 1.)
Nikronic
Hi all,I want to implement Gram Matrix of a tensor with shape(batch_size, channel_size, patch_size, height, width)We can calculate it only by this code in numpyA @ A.T.My question is why inneural style transfer tutorial, first we convert our matrix into 2D matrix, then use.mmfunction to multiply it by its transpose?def...
ptrblck
The tutorial explains it as: F_XL is reshaped to form F̂_hat_XL, a KxN matrix, where K is the number of feature maps at layer L and N is the length of any vectorized feature map F^k_XL. It doesn’t seem to be working and I’m not sure, what this operation calculates in your case: a, b, c, d = 2,…
Nikronic
Hi all,My question is about the image segmentation task.I have a tensor with the size of(batch_size, 150, height, width)and the second number(150) corresponds to the number of classes.Now I want to merge those classes into25classes by summing their probabilities.First of all, is this procedure correct? It seems it shou...
ptrblck
I’m not sure, if I understand the use case correctly, but would scattering the output logits using a mapping work? Here is a small example: batch_size = 10 nb_classes = 2 nb_features = 5 nb_out = 10 x = torch.randn(batch_size, nb_features) target = torch.randint(0, nb_classes, (batch_size,)) map…
Carl
Hi!I’m confused to see that two weight checkpoints from the same network can have very different inference times on CPU. I’ve seen cases where one checkpoint makes inference consistently 2X slower than another checkpoint. I have not seen this kind of inconsistency on GPU.I have prepared a minimal working example for wh...
ptrblck
Hi Carl, thanks for the nice script to reproduce this issue. You are seeing the time difference most likely due to denormal values (float values close to zero), which are apparently slower to process. If you set torch.set_flush_denormal(True), you’ll see that both checkpoints are faster to proces…
I-Love-U
-0.9955 ** 0.0448 Out[11]: -0.9997979654463205 torch.Tensor([-0.9955]) ** torch.Tensor([0.0448]) Out[16]: tensor([nan])I want to usepytorchget the number-0.9997979654463205. Thanks.
ptrblck
The plain Python code calculates: -(0.9955 ** 0.0448) > -0.9997979654463205 While you are trying to calculate (-0.9955) ** 0.0448 > (0.989911956308302+0.14025081271947198j) in PyTorch, which is a complex number. If you want the first output in PyTorch, just use: -1.0 * torch.tensor([0.9955]) *…
wxystudio
I use anaconda prompt to install pytorch in the following command:conda install pytorch torchvision cudatoolkit=10.0 -c pytorchBut because of the bad network I got a HTTP ERROR, so I download the four required packages:cudatoolkit-10.0.130-0.tarninja-1.9.0-py37h74a9793_0.tarpytorch-1.1.0-py3.7_cuda100_cudnn7_1.tartorch...
ptrblck
Did you try to call conda install PATH_TO_TAR? This URL might work: https://download.pytorch.org/whl/cu100/torch-1.1.0-cp37-cp37m-linux_x86_64.whl
martinoywa
I’ve been stuck here for a while now. Any help.
ptrblck
The last batch given by your DataLoader might be smaller, if the length of your Dataset is not divisible by the batch size without a remainder. Try to get the current batch size inside the training loop: for data, target in testloader: batch_size = data.size(0) ... for i in range(batch…
MaybeAustin
I was trying to find out what Pytorch is using for random number generation. I think I see in “THCTensorRandom.cpp” that Pytorch uses Mtgp32 from curand. Anyone know if this is correct? Thanks.
ptrblck
Based onthis recent PRthe curandStateMTGP32 usage was removed and instead curandStatePhilox seems to be used now.
Neuperc
I’ve trained WaveGlow model fromherewith multiple GPU, but when I try to load the checkpoint to do inference (through inference.py), some checkpoints are loaded without any problem, but most of them raise the error below:Traceback (most recent call last): File "inference.py", line 105, in <module> args.sampling_r...
ptrblck
This usually happens when multiple processes try to write to a single file. However, this should be prevented with the if condition if rank == 0:. Did you remove it or changed the save logic somehow?
barthelemymp
Hello,While making a very custom NN, I had to take into account in the forward the fact of being in train mode or not.I discovered that I could use the function model.train(True) , but I don’t know how to access this mode.I need to get boolean tensor in order to make an if statement in the forward:def forward(self, x):...
ptrblck
You can access this flag via self.training.
Daniel_Joseph
How to use the Dataloader to load two different datasets like :train_set = DataCustom(path=path, train=True) train_loader = torch.utils.data.DataLoader(dataset=(train_set1, train_set2), batch_size=args.batch_size, pin_memory=True, ...
ptrblck
You would wrap it in additional parentheses: for idx, ((data1, target1), (data2, target2)) in enumerate(zip(loader1, loader2)): print(data1.shape) print(data2.shape)
DuttaAbhigyan
Say I want to add a loss term (i.e. gradients from this loss should be propagated) from the output of hidden layers itself i.e. we use the output of a hidden layer and say pass it to a square function (hidden_output/activation)^2. How can I implement this in PyTorch?Thanks in advance!
ptrblck
Here is a small dummy example to use the some intermediate activation in your loss: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.fc1 = nn.Linear(10, 64) self.fc2 = nn.Linear(64, 10) def forward(self, x): x1 = F.relu(self…
AladdinPerzon
The problem: I have images that I’ve loaded and then stored to numpy arrays. The dataset is quite big so I realized I have to split it into different files where I can load one at a time. I’ve tried to create my own dataset class as followsclass my_Dataset(Dataset): # Characterizes a dataset for PyTorch def __i...
ptrblck
Thanks for the information! I misunderstood the data loading and thought each file was saved separately. Do you still have the large file containing all images? If so and if it’s saved as a binary file using numpy, you might load only certain parts of this file withnp.memmap.
Daniel_Joseph
Hello everyone,How to combine two models parameter of two different datasets to generate one model like :class NetworkA(nn.Module): def __init__(self, Input, Output): super(NetworkA, self).__init__() def forward(self, x): return x class NetworkB(nn.Module): def __init__(self, Input, Output)...
ptrblck
Sure! Here is a small example concatenating the outputs of two linear layers: class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.features1 = nn.Sequential( nn.Conv2d(3, 6, 3, 1, 1), nn.ReLU(), nn.MaxPool2d(2), …
vaibhavkumar049
How can we append tensorsSo my situation is I have a for loop that goes through all rows from a 2-D tensor and then does argmax in each row, and returns a tensor position of the maximum value in that row. And finally, I want to append all those a value and creates a 1-D tensorHow can I achieve that
ptrblck
If you want to get the maximal indices for each row, you could just call .argmax(1): x = torch.randn(10, 15) x.argmax(1)
voqtuyen
Why do we have to call scheduler.step() every epoch like in the tutorial by pytorch:Observe that all parameters are being optimizedoptimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)Decay LR by a factor of 0.1 every 7 epochsexp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)...
ptrblck
It won’t follow these scheme, if you don’t call scheduler.step() in each epoch. Here is a small example: optimizer = optim.SGD([torch.randn(1, requires_grad=True)], lr=1e-3) exp_lr_scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)…
ASHUTOSH_CHANDRA
Pytorch data loader is supposed to take a dataset as input. The dataset is an instance of Dataset class which defines the “len” and “get” functionality.What if instead of dataset, I give simple csv file as input to pytroch data loader. I tried and the data loader is working, but I’m not sure about the behavior of the c...
ptrblck
We had recently a similar discussionin this topic. The DataLoader might take inputs, where __getitem__ and __len__ is defined. E.g. this code will work: x = [0, 1, 2] print(x.__getitem__) print(x.__len__) loader = DataLoader(x) for data in loader: print(data) However, I would still recomme…
eFroD
Hello,I am very new to pytorch and DNNs in general.I’ve created a classifier on top of a pretrained densenet161, to classify images of flowers, into the groups: daisy(0), dandelion(1), rose(2), sunflower(3) and tulip(4).The training-process works fine and in order to test the model I went on implementing the example fr...
ptrblck
Did you also call model.eval() before testing the single image?
Ravi_Gupta
I got stuck due to this error. I try to resolve it in many ways but I can’t.Please anyone help me to solve it effectivelylink of code:-Google Colaberror1790×855 57.4 KB
ptrblck
Most likely this error is thrown because esp is still on the CPU while mu and std seem to be calculated by the linear layers and might thus be on the GPU (if the model was pushed to the GPU of course). Try to create esp using the device argument of mu: esp = torch.randn(*mu.size(), device=mu.devic…
god_sp33d
Hi,I am doing an experiment where I use the output of intermediate values of batchnorm layer from resnet50. So, I forward hook at different layers and work on the output. But, the weird thing I observed is the min value of the batchnorm output clamps to zero at all the layers. To reproduce the result I wrote a toy prog...
ptrblck
The output of the Bottleneck layer might be misleading: model.layer2[1] Out[42]: Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=…
alan_ayu
I want to fix the randomness of the training for compare the performance of different super-parameters. Now I fix the random seed of random.seed(), numpy.random.seed(), torch.manual_seed() and torch.cuda.manual_seed(), but I found I still can’t get the same result in different training process, even I set the p of drop...
ptrblck
Additionally to setting the seeds you should also disable cudnn.benchmark and enable the cudnn deterministic behavior, if you are using a GPU. Have a look at theReproducibility docsfor more information. Also, how large are the differences? As explained in the docs, some atomic operations might yi…
dragen
i have a tensorx = [2, 3, 2, 1, 2, 3, 2]I want to randomly sample a number from all same number, e.g. randomly sample the2from all 2’s index, and get index may be0, namely sampled the first 2; randomly sample the3, and get index may be5. and randomly sample the1, get index3since only single1exists. so the return index ...
ptrblck
In that case, I would just sample the values using torch.multinomial: x = torch.tensor([2, 3, 2, 1, 2, 3, 2]) unique = torch.unique(x) weight = x.unsqueeze(0) == unique.unsqueeze(1) torch.multinomial(weight.float(), num_samples=1)
omarabdelaziz
I’m training my model but the prediction is being broadcasted over the whole tensorclass CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Conv2d(1, 6, kernel_size=4, padding=1) self.conv2 = nn.Conv2d(6, 12, kernel_size=4) #self.conv2_drop = nn.Dropout2d...
ptrblck
I assume the number of input features is 103. In that case, your output is not being broadcasted, but apparently your model is currently overfitting to class4, since the output shape of [29, 1] matches r_out's shape after slicing and the linear layer.
kekday
What kind of operations can I perform on tensors while still being able to compute gradients? For instance when I tryx = torch.rand(1, requires_grad=True)y = x+2print(y.grad_fn)I get <AddBackward0 object at 0x7fd459552320>but when I try something likex = torch.rand(1, requires_grad=True)y = torch.tensor([x , 0])print(y...
ptrblck
Recreating a tensor will break the computation graph. If you would like to concatenate two tensors, you should use torch.cat or torch.stack instead: x = torch.rand(1, requires_grad=True) y = torch.cat([x , torch.tensor([0.])]) print(y.grad_fn) <CatBackward object at 0x7fdb08dca6d8>
AmardeepGanguly
I am dealing with a multi-label classification problem ,the image belongs to one of the10 classes from two distinct labels i.e desired output is [batch_size,2,10],how can i modify ResNet50 to Get Multiple outputs
ptrblck
Probably you are using an older PyTorch version, as the nn.Identity module was introduced in 1.1.0. Have a lookherefor install instructions.
badesairam
I am trying to check the time taken by two different models(ELMO vs BERT) while predicting in named entity recognition , It involves getting logits data from GPU to CPU which is taking different times with different models.this code snippet is same for both the modelslogits = torch.argmax(F.log_softmax(logits,dim=2),d...
ptrblck
CUDA operations are called asynchronously, so you should synchronize the code before starting and stopping the timer using torch.cuda.synchronize(). In your current code snippet logits = logits.detach().cpu().numpy() will create a synchronization point, so that your code will wait at this line of c…
qoqo
Best way to extract smaller image patches(3D)?First step, I would like to read 10 three-dimentional data with size of (H, W, S) and then downsample these data to (H/2, W/2, S/2).Second step, I want to design a sliding window to extract patches with size of (64, 64, 64) from the above images.Are there some examples abou...
ptrblck
For the second use case you could use Tensor.unfold: S = 128 # channel dim W = 256 # width H = 256 # height batch_size = 10 x = torch.randn(batch_size, S, W, H) size = 64 # patch size stride = 64 # patch stride patches = x.unfold(1, size, stride).unfold(2, size, stride).unfold(3, size, stride) pr…
rbunn80110
If I want to split grayscale images into 14x14 patches (4 pieces total for each image in the code below) I tried the following code:S = 1 # channel dimW = 28 # widthH = 28 # heightbatch_size = 10x = torch.randn(batch_size, S, W, H)size = 14 # patch sizestride = 14 # patch stridepatches = x.unfold(2, size, stride).unfol...
ptrblck
You already have the results. The 4 patches are stored as 2x2 patches in dim2 and dim3, so you can just call .contiguous().view(batch_size, S, -1, size, size) on the result.
Nimrod_Daniel
I need to solve an unsupervised problem with images from MNIST and SVHN, in which I have 100 images from MNIST and 10 images from SVHN). I need a pre-trained net to learn how to classify if a given image is from MNIST or SVHN (the anomaly). Basically, it’s an anomaly detection problem.I know I’ll have to tackle that l...
ptrblck
I think the easiest approach would be to write a custom Dataset, and load the desired samples inside of __init__. Since the data format is different for MNIST and CIFAR (size and number of channels), you would also need to specify some dataset-specific transformations. Here is a small sample code,…
hiepnguyen034
I received this errorExpected object of backend CUDA but got backend CPU for argument #2 'mat2'while trying to run my model. Here is what I have.torch.cuda.current_device() device = torch.device("cuda:0" if (torch.cuda.is_available() and ngpu > 0) else "cpu") class Flatten(nn.Module): def forward(self, x): ...
ptrblck
Currently you are re-creating a nn.Linear layer in your forward method in each call. This will reinitialize its parameters in each forward pass, so that this layer won’t be able to learn anything. That being said, the to() operator also cannot push this module to the device, so that you would have…