user_q
stringlengths
3
20
question
stringlengths
20
31k
user_a
stringclasses
5 values
answer
stringlengths
18
302
Filos92
Hello, dear Pytorch community.I am new here and happy to have found this forum.I am currently writing on a network that is supposed to have both image pixels and other variables as inputs (cost in dollars, power readings or simple on-off signals).I wanted to ask if anyone has experience with this kind of network and ca...
ptrblck
Hi Filos, it’s a bit hard to give you a general answer, as a suitable model architecture will most likely depend on the problem you are dealing with. One way to deal with this kind of data is to use separate model “paths”, e.g. a CNN for your image input and a feed-forward model for the other feat…
HaziqRazali
I am facing an issue whereby using theinception_v3network results in the error message./train.sh: line 63: 20266 Segmentation fault (core dumped) CUDA_VISIBLE_DEVICES=None python train.py “${args[@]}”class CRM(nn.Module): def __init__(self, args): super(CRM, self).__init__() s...
ptrblck
The Inception model returns in its default setting the aux_logits with the output as described in the original paper. This logic is implemented in theforward method. Wrapping all child modules in a nn.Sequential module will most likely not work properly in that case. If you just need certain lay…
Seongkyun_Han
I want to load ImageNet pre-trained Resnet weight file before the fully-connected layer.I mean, I just want to load CNN weight parameters only.Is there any way to do that? Please help me
ptrblck
You would just have to load the pre-trained model and change the last linear layer to the new number of classes as described in theTransfer Learning tutorial.
Intel_Novel
I checked some threads, and need some clarification on these:torch.zeros(100, device="gpu")torch.zeros(100).to("cuda")Both of these will end on GPU as far as I know, but is there any difference?
ptrblck
The first one should be more efficient, as the tensor will be directly created on the device, while the other will be created on the CPU first, then pushed onto the GPU.
Mohsen_Hosseini
I’m new in pytorchI’ve created a simple mlp as folow:class MLP(nn.Module): def __init__(self): super(MLP, self).__init__() self.L1 = nn.Linear(6,4) self.l1_drop = nn.Dropout(p=0.2) self.L2 = nn.Linear(4, 2) self.l3_drop = nn.Dropout(p=0.1) self.out = nn.Linear(2,1) ...
ptrblck
Your code basically looks alright. You could try the following to make the model learn: lower your learning rate and see if the loss is decreasing (a learning rate of 1e-3 might be a good starter for Adam try to normalize your input. Currently it looks like you are dealing with some kind of categ…
Komoriii_Sen
Hi. I want to use ImageFolder to load my dataset. However, I got a error messageTraceback (most recent call last): File "lenet.py", line 106, in <module> train(10, net, device, training_data, optimizer, epoch=ep_id) File "lenet.py", line 46, in train for batch_idx, (data, target) in enumerate(train_loader):...
ptrblck
Currently you are passing the composed transformation as the target_transform. Since it consists of a Resize, I think you wanted to pass it as the transform instead. Could you try to change that and see if it’s working?
Zhenlan_Wang
I am going through the DCGAN tutorialstutorials.One question I have is how do you turn off the gradient history tracking for discriminator when you are training the generator. In the tutorial, it is not turned off as shown below.... # this part trains generator netG.zero_grad() label.fill_(real_label) ...
ptrblck
Thanks for the debugging!This postmight explain the benefits you are seeing.
Sherlock_c787
I tried to my data set and test set, the original pictures are grayscales with format ‘.bmp’.I used the following mothod :addrBase1 = '../Train/' addrBase2 = '../Test/' transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) # TrainSet trainSet...
ptrblck
transforms.Grayscale works on PIL.Images so you should put it before transforms.ToTensor. Also, transforms.Normalize would then only take a single value for the mean and standard deviation. transform = transforms.Compose([ transforms.Grayscale(1), transforms.ToTensor(), transforms.Norm…
marsggbo
Because my dataset is imbalanced, I want to use torch.utils.data.WeightedSampler to sample data. Before do that I did a experiment, and the code is as follow:import torch from torch.utils.data.sampler import Sampler from torch.utils.data import TensorDataset as dset batch_size = 5 inputs = torch.randn(15,2) # print(in...
ptrblck
The weight should provide a weight for each sample, while in your code it looks like you are trying to pass class weights. Have a look atthis exampleon how to use the WeightedRandomSampler.
Zhenlan_Wang
I have seen people doing both, torch.nn.init.normal_(m.weight) or torch.nn.init.normal_(m.weight.data). Could someone tell me which is the right way and why? Thanks.Best,Zhenlan,
ptrblck
I would avoid using the .data attribute anymore and instead wrap the code in a with torch.no_grad(): ... block if necessary. Autograd cannot warn you, if you manipulate the underlying tensor.data, which might lead to wrong results.
AkashGanesan
Hi,In torch, when I try to do this, I getimport torch y_rel = torch.randn(16,2,8) # (Batch, n, seq_len) y_start = torch.randn(16,2) y_rel + y_startThis throwsRuntimeError: The size of tensor a (8) must match the size of tensor b (2) at non-singleton dimension 2In Julia, I can do something like this. Is there anything...
ptrblck
If you add dim2 to y_start the tensor will be automatically broadcasted: y_rel + y_start.unsqueeze(2)
Nikronic
Hello everyoneI have a huge dataset (2 million) of jpg images in one uncompressed TAR file. I also have a txt file each line is the name of the image in TAR file in order.img_0000001.jpg img_0000002.jpg img_0000003.jpg ...and images in tar file are exactly the same.I searched alot and find outtarfilemodule is the best ...
ptrblck
Based on your description it seems to be better to extract all files beforehand and read them separately. Alternatively, would it be possible to call tf.getmembers() once in your __init__ method or use the filenames stored in your filelist.txt to get each file using tf.extractfile([self.filelist[in…
raymondlucky
Dear All,For curiosity, I extracted network layers and calculated output by hand, given a new input.A very simple regression model:NeuralNet( (l0): Linear(in_features=6, out_features=256, bias=True) (relu): ReLU() (l00): Linear(in_features=256, out_features=1, bias=True) )My manual calculation:ReLU = lambda x: np...
ptrblck
In training mode nn.BatchNorm layers will use the batch statistics and update the running estimates. If you call .eval() on this layer or your complete model, the running estimates will be used. Are you comparing a training run of your model with a manual eval implementation?
MariosOreo
Hi guys,When I useDataloaderto load data withnum_worker>0, I got the following error:Exception in thread Thread-1: Traceback (most recent call last): File "/home/Maro/anaconda3/envs/pytorch/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/home/Maro/anaconda3/envs/pytorch/lib/python3....
ptrblck
I’ve never seen this error on my machine, but searching for it it looks like Python 3.7 could fix this issue. Would it be possible for you to create a new conda environment and try the code with Python 3.7? If not, could you post a code snippet so that we can reproduce this error?
isalirezag
considering these two nets:class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 6, kernel_size=1, stride=1, bias=False) self.conv2 = nn.Conv2d(6, 6, kernel_size=1, stride=1, bias=False) self.conv3 = nn.Conv2d(6, 6, kernel_size=1, st...
ptrblck
Both models work identically as seen here: model1 = Net() model2 = Net2() model2.load_state_dict(model1.state_dict()) x = torch.randn(1, 3, 24, 24) outputs1 = model1(x) outputs2 = model2(x) # Compare outputs print((outputs1[0] == outputs2[0]).all()) print((outputs1[1] == outputs2[1]).all()) # C…
HaziqRazali
I am getting an issue with the dimensions when I load the alexnet model and change the it such that it is a single list. For example, the code below gives me an error. Why is this so? I have done nothing except merge the list.RuntimeError: size mismatch, m1: [98304 x 6], m2: [9216 x 4096] at /pytorch/aten/src/THC/gener...
ptrblck
Since you are wrapping all submodules into an nn.Sequential module, you are losing the flatten operation which is performed in the forward method. Similar tothis issueyou can add a custom Flatten module and it should work: class Flatten(nn.Module): def __init__(self): super(Flatten, …
Yoohv_Zo
My information:system: ubuntu:18.04python: 3.7.1torch: 1.0.1.post2Code:import torch import torch.nn as nn class RNN_ENCODER(nn.Module): def __init__(self, num_embeddings, input_size=300, drop_prob=0.5, hidden_size=256, layers=1, bidirectional=True): super().__init__() self.encoder...
ptrblck
Could you try to disable cuDNN using torch.backends.cudnn.enabled = False and run your code again? The code you’ve posted here runs fine on my machine, so the error might come from some setup issue on your machine or the way you are using your model. Here is a small code snippet which is working: …
fanl
Hi,As far as my understanding, the state dict should contain all the information about the model. I am sure that all the parameters will be contained.But does the state dict contain other settings, like model.eval()?
ptrblck
The state_dict contains all parameters and buffers registered to your module (not the architecture or some other code). The training attribute is not part of the state_dict and will be set to True in newly initialized models.
isalirezag
In pytorch 0.3 we used to have Variable and when training we needed to do Variable(input).Therefore, in this wayinput.requires_gradbecame True.so my assumption was thatinput.requires_gradshould always be true for training. is that true?but now im reading ‘training a classifier’ in pytorch website and see that theinpu...
ptrblck
Wrapping a tensor into Variable didn’t change the requires_grad attribute to True. You had to specify it while creating the Variable: x = Variable(torch.randn(1), requires_grad=True) Usually you don’t need gradients in your input. However, gradients in the input might be needed for some special u…
jGsch
Hello,I’m looking for the best way to measure the timing of a process:time.perf_counterortime.process_time?I have seen in several topics that people use moreperf_counterbutprocess_timeis process-wide (1).But in the docs, you can see that process_time “Return the value (in fractional seconds) of the sum of the system an...
ptrblck
time.perf_counter() might be a good first approach to time your code. Note that CUDA calls are asynchronous, so that you would have to synchronize your code before starting and stopping the timer using torch.cuda.synchronize().torch.utils.bottleneckmight be also a good utility to profile your co…
koelscha
When training a model, it seems, the optimizer occupies some GPU memory which it does not release anymore. Let me explain this with an example:import torchvision.models as models import torch from torch import optim, nn model = models.resnet18(pretrained=True).cuda() optimizer = optim.Adam(model.parameters()) criteri...
ptrblck
I think you are right and you should see the expected behavior, if you use an optimizer without internal states. Currently you are using Adam, which stores some running estimates after the first step() call, which takes some memory. I would also recommend to use the PyTorch methods to check the al…
Deb_Prakash_Chatterj
Guys, I am making a classifier using ResNet and I want to get the Sensitivity and specificity of the particular dataset. Right now I have accuracy, Train loss, and test loss. I have already studied from Wikipedia and YouTube, about True positive/negative, false negative/positive and know the formula. But I do not know ...
ptrblck
@MariosOreoThanks for the catch! I’ve fixed it in my post.@Deb_Prakash_ChatterjYou could count it manually of create a confusion matrix first. Based on the confusion matrix you could then calculate the stats. Here is a small example. I tried to validate the results, but you should definitely …
Xiaoyu_Song
Hi, I have a very imbalanced data where the weight is in the range [0.0000000012,1], in order to use the weighted NLLloss, if I apply directly these extreme small value weight, I get the very small loss, so if I want to get the same indicator as the case without weight before. What is the strategy of assigning weights?...
ptrblck
The loss will be rescaled with the weights as described in thedocsif you keep reduction='mean'. You can see in the formula, that each sample loss will be divided by the corresponding weight. This also means, you shouldn’t have to change the learning rate or other parameters. Is there a reason yo…
hhh
Hi, everyone,I am using LSTM to predict the stock index of someday using the ones of 30 days before it as the input only. I think in this example, the size of LSTM input should be [10,30,1],so I uset_x=x.view(10,30,1)to reshape the input. But there is an RuntimeError(shape '[10, 30, 1]' is invalid for input of size 150...
ptrblck
It seems the data provided by the DataLoader does not contain enough values to be reshaped to [10, 30, 1]. Could you check the shape of train_x_np? However, if the error occurs later in the training and the first iterations are running successful, the last batch might be smaller, thus yielding this…
hhh
Hi, everyone!In LSTM of PyTorch, if it is time series data, does time_step equal to input_size? For example, use the Nasdaq index of 1000 days as a training set, divide them into 10 batches, and predict the index of one day by the indexs of 30 days before it. Are the parameters just like below:batch_size=100, time_step...
ptrblck
input_sizes defines the expected features in the input x. In your example you might pass different signals, e.g. the Nasdaq index, the weather, the moon phase etc. as features to your model. The sequence length is independent from the number of features. If you just pass a single signal (Nasdaq in…
Intel_Novel
Hi, this works,a = torch.LongTensor(1).random_(0, 10).to("cuda"). but this won’t work:a = torch.LongTensor(1).random_(0, 10) a.to(device="cuda")Is this per design, maybe I am simple missing something to convert tensor from CPU to CUDA?
ptrblck
If you are pushing tensors to a device or host, you have to reassign them: a = a.to(device='cuda') nn.Modules push all parameters, buffers and submodules recursively and don’t need the assignment.
mahsa
I have a tensor with size N*K with float numbers. I want to change the values of top K in every row of it to 1 and change all other values to 0. What is the best way for doing so in pytorch?thanks.
ptrblck
I assume the second K is smaller than the first one. This code should work: x = torch.randint(0, 10, (10, 5)) k = 3 kvals, kidx = x.topk(k=k, dim=1) x.zero_() x[torch.arange(x.size(0))[:, None], kidx] = 1
mahsa
I have a tensor which contains zero and non-zero values. I want replace every non-zero value with its logarithm. Is there any simple way?Thanks
ptrblck
This code should work: x = torch.arange(0, 10, dtype=torch.float) idx = x!=0 x[idx] = torch.log(x[idx])
Alethia
I run the following pytorch code on my machine, but the result is not expected. Why and how can I fix this problem?>>>linear = nn.Linear(300, 300) >>>input = torch.randn(10, 300, 300) >>>out1 = linear(input) >>>out2 = linear(input[0]) >>>out1[0].equal(out2) False >>>out2.equal(out1[0]) False >>>(out1[0] - out2).pow(2)....
ptrblck
You are seeing the limited floating point precision using float32. If you need more precision, you could cast all tensors and the parameters to double.
duygusar
I am training a model. To overcome overfitting I have done optimization, data augmentation etc etc. I have an updated LR (I tried for both SGD and Adam), and when there is a plateu (also tried step), the learning rate is decreased by a factor until it reaches LR 1e-08 but won’t go below than that and my model’s validat...
ptrblck
Have you tried to set the eps argument of your ReduceLROnPlateau scheduler? Adam’s eps is different to the one used in the scheduler. From the docs: eps (float) – Minimal decay applied to lr. If the difference between new and old lr is smaller than eps, the update is ignored. Default: 1e-8. I…
Ali_Mirzaeyan
Hi,I’m trying to change the used size of channels at layer4 of resnet 18, I wrote something like the follwoing piece of code. but when I run it complains about the size mismatch at the fc layer, I don’t know exactly how should I realize which size should I use.class Inception(nn.Module):def __init__(self, in_channels=2...
ptrblck
Static frameworks can infer the input size based on the computation graph. I.e. if we know which activation will be passed to the linear layer in advance, we can set the number of input features based on the activation shape. However, as the forward pass is not known in advance in PyTorch and the …
WangBo12
hi, i am a beginner of pytorch.The problem is i have 16 tensors(each size is 14 * 14), and how could i use global max pooling and then calculate the average value of every 4 tensors, and return an output tensor with 4 * 1.Thanks.
ptrblck
You could use an adaptive pooling layer first and then calculate the average using a view on the result: x = torch.randn(16, 14, 14) out = F.adaptive_max_pool2d(x.unsqueeze(0), output_size=1) # Calculate result manually to compare results out_manual = torch.stack([out[:, i:i+4].mean() for i in ran…
andreydung
Given a 2D pytorch tensor, I want to update specific columns for each row as following:import torch a = torch.zeros(3,7) index = torch.LongTensor([2, 1, 3]) for i in range(a.shape[0]): a[i][index[i]:] = 1Expected output data:tensor([[0., 0., 1., 1., 1., 1., 1.], [0., 1., 1., 1., 1., 1., 1.], [0., 0....
ptrblck
You could just compare each index to a torch.arange tensor: b = torch.arange(7).unsqueeze(0) >= index.unsqueeze(1) b = b.float()
jmiano
I’m trying to implement simulated annealing as a custom PyTorch optimizer to be used in a neural network training loop instead of a traditional gradient-based method. The code I currently have runs, but the loss just keeps growing rather than decreasing. I’ve tested on this dataset using a traditional gradient-based me...
ptrblck
I think your old_dict will just hold a reference to the state_dict and will thus be changed, too. Could you add this code snippet to clone the old state_dict and try it again: # Save init values old_state_dict = {} for key in model.state_dict(): old_state_dict[key] = self.model.state_dict()[ke…
StrausMG
Hi! I am working on a simple classification problem. However, in my setup, I would like to create batches smarter than just by uniform sampling. Namely, I am trying to mine hard batches as following:sample a big batch uniformly (e.g. 1024 samples)apply my model to the big batch and calculate lossessample a normal batch...
ptrblck
If you set num_workers > 0, each worker will load a batch in the background and inplace modifications of your Dataset won’t be noticed until the next epoch. As you said, num_workers=0 might work and I can’t see any reason to use multiple workers, as your workflow seems to be sequential, i.e. you ca…
andrewnaguib
Consider the following list:[[3], [1, 2], [4], [0], [2]]And zeros tensor of size(5, 5)I want to fill these indices according to their index in the list to the tensor with 1.So, the expected output should be:tensor([[0., 0., 0., 1., 0.], [0., 1., 1., 0., 0.], [0., 0., 0., 0., 1.], [1., 0., 0., 0....
ptrblck
You could duplicate the single elements in your index tensor, so that you could create a tensor to use in .scatter_. I’m not sure, if there is a better way besides the obvious one using a loop.
ShawnGuo
I was wondering about how can I implement an environment purely on GPU. Say, if all the variables in the environment class are torch.Tensor, well they stay on GPU during run-time?Take the following environment for example:class ENV_GPU(object): def __init__(self, a=3): self.num = torch.zeros((a,), dtype=tor...
ptrblck
.to() is implemented in nn.Module. If you derive your class from nn.Module and define step as forward it should work: class ENV_GPU(nn.Module): def __init__(self, a=3): super(ENV_GPU, self).__init__() num = torch.zeros((a,), dtype=torch.int8) self.register_buffer('num',…
Carsten_Ditzel
So here I am wondering why i cannot write the followinglabels = labels.byte() # shape [20] pred = pred.byte() # shape [20] print('labels', labels.shape) print('pred', pred.shape) true_positives = torch.zeros_like(labels) true_positiv...
ptrblck
Thanks for the detailed code and explanations! Now I understand the problem and use case a bit better. Yes, you are right in that the tp, fp, tn, fn tensors are treated as logical indices. This advanced indexing behavior is different to the vanilla indexing and is explained a bit better in thenu…
Michael_Baumgartner
I am experiencing some inconsistent predictions when running the same file multiple times. I followed thehttps://pytorch.org/docs/stable/notes/randomness.htmlguide to set all the seeds and enable/disable the respective cudnn flags.Training a small 3D network with some pooling layers on the CPU runs smoothly and the res...
ptrblck
Thanks for the code snippet! I debugged it a bit and think you are seeing some non-determinism due to some atomic operations. From the reproducibility docs: There are some PyTorch functions that use CUDA functions that can be a source of non-determinism. One class of such CUDA functions are atom…
subhashnerella
I have the following error:Traceback (most recent call last):File "odenet_mnist.py", line 343, in <module> logits = model(x) File "/home/subhashnerella/.conda/envs/pytorch/lib/python3.7/site-packages/torch/nn/modules/module.py", line 489, in __call__ result = self.forward(*input, **kwargs) File "/home/subha...
ptrblck
As far as I know, your RTX2080Ti needs CUDA10 to work properly. Could you create a new conda environment, install the PyTorch binaries containing CUDA10, and try it again?
MisBah_Awan
i want to run this coded but i am stuck here code not showing error or output. kindly anyone guide me how to solve this problem.image1366×731 52.5 KBthanks in advance
ptrblck
Is your code working in a terminal? Are you using multiple workers in your DataLoader? If so, could you add the “if-clause protection” as describedhere.
ender46
Hello,I am running in the backpropagation error that states that “Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time”.However, I don’t see where is my code trying to run through the graph a second time. Let me show ...
ptrblck
Part of your computation graph is outside the loop (xx = x/10). After the first optimizer.step() call, the intermediate values will be cleared and thus x cannot be optimized anymore. If you move xx = x/10 into the loop, the code should work.
Carsten_Ditzel
I am confused about the followingsnippettaken from the tutorials about transfer learning.for phase in ['train', 'val']: if phase == 'train': scheduler.step() model.train() # Set model to training mode else: model.eval() # Set model to evaluate m...
ptrblck
model.train() and model.eval() change the behavior of some layers. E.g. nn.Dropout won’t drop anymore and nn.BatchNorm layers will use the running estimates instead of the batch statistics. The torch.set_grad_enabled line of code makes sure to clear the intermediate values for evaluation, which ar…
suice07
Hello ,everyone, I was trying to do some segenmentation jobs with Unet. I have only 10 Images , and I use 8 of them as train Images, 2 of them as test. The images are greyscale images, and the mask(groundtruth) are binarized images(black stand for backgrounds, white for objects). I am using almost the most basic Unet. ...
ptrblck
You can find a small example of using the same “random” transformationshere, which would be important as@bluesky314described.
Ali_Mirzaeyan
Hi,I was trying to fine-tune resent 152 and I was using this piece of code:> for param in list(model.parameters())[:-1]: > param.requires_grad = Falsebut I notice this was not working I changed it to :> child_counter = 0 > for child in model.children(): > if child_counter < 9: > for param in chil...
ptrblck
In the first code snippet you are setting all requires_grad flags to False except the model.fc.bias, while the second code snippet additionally keeps model.fc.weight.requires_grad as True.
Intel_Novel
When shuffle isTrueforDataLoaderclass what is the default Sampler then?From the docs:shuffle (bool, optional): set to ``True`` to have the data reshuffled at every epoch (default: ``False``).If I don’t set the Sampler one must be used by default. Can you give any clue?
ptrblck
If no sampler was specified and shuffle=True, the RandomSampler will be used as shown inthis line of code.
Deb_Prakash_Chatterj
Hey, I have implemented ResNet and Densenet in PyTorch. I am now using Inception V3. But when I was first using it throws me an error, that I solved by changing the -transform_train = transforms.Compose([transforms.RandomHorizontalFlip(), transforms.RandomResizedCrop(244), to ...
ptrblck
Might be unrelated to the first issue. Could you set num_workers=0 and run the code again to get a proper error message?
Mohammed_Awney
Hi, i ma followcs230-code-examplesand I have miss understanding the loss functionhow dose this line works" return -torch.sum(outputs[range(num_examples), labels])/num_examples"where outputs is result of the model with shape = batch_size x num_classes , labels with shape = batch_sizeThanks in advance
ptrblck
Let’s first have a look at outputs[range(num_examples), labels]. As you said, outputs contains the model outputs and has the shape [batch_size, num_classes]. labels seems to be a torch.LongTensor, containing the ground truth class for each sample in the batch. In this code we are basically indexi…
shangeth
this is the shape of numpy array, (35628, 1, 16000)i train/test split itfrom sklearn.model_selection import train_test_splitx_train, x_test ,y_train, y_test = train_test_split(datan, label, test_size=0.2, shuffle=True, random_state=40)(this works fine)make dataset from split arraysimport torch.utils.data as utilstenso...
ptrblck
It should work with any size as long as your system can handle it properly. If you are using np.float32 values, the data should take approx 2GB of RAM. Are you using multiple workers in your DataLoaders? I’m not sure, what limitations Colab has on the RAM. Also, could you try to use torch.from_n…
onimusha702
So i am trying to train a Variational Auto Encoder, and i have created a custom loss function to train the network, the network throws the errorRuntimeError: grad can be implicitly created only for scalar outputsheres the Loss functiondef loss_function(recon_x, x, mu, logvar): BCE = F.binary_cross_entropy(recon_x, ...
ptrblck
As@bharat0tosaid, your loss is most likely a multi-dimensional tensor, which will thus throw this error. You could add some reduction or pass a gradient with the same shape as loss.
smu226
Hello! I trained a model and I want to test it on some given values. I load the values like this:factors = torch.from_numpy(variables) factors = factors.cuda() factors = factors.float()and then I put the model in the evaluation mode and run it:model = SimpleNet(n_variables).cuda() model.load_state_dict(torch.load("weig...
ptrblck
model.eval() changes the behavior of some layers, e.g. nn.Dropout won’t drop anymore and nn.BatchNorm will use the running estimates instead of the batch stats. To save some memory you should wrap your code in with torch.no_grad(): so that the intermediate activations won’t be stored: with torch.n…
kevin-ssy
Hi there,Now I have a tensor A with the shape (n, c, h, w). Suppose the first channel of the tensor is like:[[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],[13, 14, 15, 16]]I want to reshape the tensor into the shape (n, c, h*w) by grids. If the grid is 2x2, then the reshaped tensor should be:[1, 2, 5, 6,3, 4, 7, 8,9, 10, 1...
ptrblck
For a general use case using a grid you could use .fold(): x = torch.arange(1, 17).float().view(1, 1, 4, 4) kh, kw = 2, 2 # kernel_size dh, dw = 2, 2 # stride # get all image windows of size (kh, kw) and stride (dh, dw) input_windows = x.unfold(2, kh, dh).unfold(3, kw, dw) output = input_windows…
isalirezag
I recently start using a server that has cudnn.Although the GPUs are better than what i used to hav, the same code runs slower.How I can disable cudnn so my code does not use it?I think cudnn is the reason behind this slownessshould i dotorch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = False...
ptrblck
torch.backends.cudnn.enabled = False would disable cuDNN. Could you post your results, if cuDNN slows down your code?
aerinykim
Simple question. I’d like to see the initialized parameter of LSTM. How do I see it?Do I need to always put lstm in the model to see the params?import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim ​ torch.manual_seed(1) torch.__version__ ​ lstm = nn.LSTM(3, 3) ​ lstm.weight_i...
ptrblck
You need to specify the layer index of your parameters. I.e. if your LSTM has one layer (as in your example): print(lstm.weight_ih_l0) print(lstm.weight_hh_l0)
John1231983
Hello all, I have an architecture likesThe input is fed to Gen network to generate a fake image (fakeA). I use L1 loss to compute the different between input and fakeA. I called it islossGen.The fakeA then is fed to the segmentation network to create a predA. I used cross entropy to compute the loss between the label a...
ptrblck
Both approaches should compute the same gradients. In the second approach you would need to call lossGen.backward(retain_graph=True), otherwise the intermediate values will be cleared and you’ll get an error calling lossSeg.backward(). However, currently you are using lossSeg to calculate gradient…
1234
I am interested in implementing max pooling using PyTorch without thenn.MaxPoolfunctions in an efficient way (i.e. can run on GPU) for the sake of learning. My input is a standard batched tensor of size(N, C, X, X), for simplicity I will assume that the size of my stride is equal to to the size of the kernel, which can...
ptrblck
@fmassahas created an example of max pooling using unfolehere.
mmisiur
Hi there,I’m quite new to torch, so maybe it’s sth simple. I’ve trained my net, which is:class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5) self.pool = nn.MaxPool2d(4, 4) self.conv2 = nn.Conv2d(6, 16, 5) self.pool = nn.MaxPoo...
ptrblck
If you try to create a new nn.Sequential model using the layers from Net, the flatten operation will be missing. Additionally, you are currently using only one pooling layer, as both are defined as self.pool. Probably the most straightforward way would be to derive another class from Net and just …
woaichipinngguo
I have a resnet18 model that the filters of each layer are half of the original ImageNet resnet18 model. Now, I want to load the pertained weight of ImageNet resnet18 model to my own resnet18. How can I load it?
ptrblck
By “half” do you mean the number of filters or their spatial size? You could try to load the weights manually: with torch.no_grad(): new_model.conv.weight = old_model.conv.weight[:3] # assuming old model used 6 filters # or for half the spatial size new_model.conv.weight = old_model.c…
MultiSeedLoaf
Hi, I have implemented a network for multi-label, multi-class classification, this has been done using BCEWithLogits outputting to 6 sigmoid units. However, I have a class imbalance and was wondering if there were a way to weight such classes in the multi-label sense.I have labels in the following one-hot encoded forma...
ptrblck
I think the easiest approach would be to specify reduction='none' in your criterion and then multiply each output with your weights: target = torch.tensor([[0,1,0,1,0,0]], dtype=torch.float32) output = torch.randn(1, 6, requires_grad=True) weights = torch.tensor([0.16, 0.16, 0.25, 0.25, 0.083, 0.08…
erobertc
Hi,I’m trying to follow the instructions athttps://pytorch.org/get-started/locally/to install PyTorch on my Ubuntu (16.04) machine. I already have the NVIDIA drivers and CUDA 10.0 set up.When I attempt to run the command from that pageconda install pytorch torchvision cudatoolkit=10.0 -c pytorchin a Conda environment, ...
ptrblck
I just created a new conda env and this command runs successfully on my machine (Ubuntu 18.04). Could you try to update conda using: conda update conda and run the command again?
mahsa
I wanted to calculate the sum of 1st to K-th power of an array and equally calculate the sum of 1st to k-th power of a tensor. I found out that the following codes and their results are totally different and I don’t know why.I debugged the code and I know that the results are equal in the first round.Numpy code:adj_k_p...
ptrblck
The error is regarding the shallow/deep copy. If you add a copy() after assigning the numpy arrays, your code runs fine with an error of ~2e-7: adj_k_prob = adj_prob.copy() adj_k_pow = adj_prob.copy()
Yilin_Liu
Hi, I’m wondering how to use the ignore_index for handling void targets in segmentation task. Should I manually create some fake label maps for those data? i.e., a map full of -1, then set ignore_index to -1? Thanks!
ptrblck
It seems to work: criterion = nn.CrossEntropyLoss(ignore_index=-1) output = torch.randn(2, 10, requires_grad=True) target = torch.tensor([-1, 1]) loss = criterion(output, target) loss.backward() print(loss, output.grad) > tensor(1.4096, grad_fn=<NllLossBackward>) tensor([[ 0.0000, 0.0000, 0.00…
Yuerno
I have two tensors of shape (4096, 3) and (4096,3). What I’d like to do is calculate the pairwise differences between all of the individual vectors in those matrices, such that I end up with a (4096, 4096, 3) tensor. This can be done in for-loops, but I’d like to do a vectorized approach. NumPy lets you do some broadca...
ptrblck
I’m not sure if I understand it correctly, but I think this will do it: a = torch.randn(5, 3) b = torch.randn(5, 3) res = a.unsqueeze(1) - b # res[i] corresponds to (a[i] - b)
ptrblck
You don’t need the channel dimension for the labels.nn.CrossEntropyLossexpects the labels to have the shape[batch_size, height, width]in your semantic segmentation use case, containing class indices.It looks like you can just passlabelswithout any modification.
ptrblck
Your target is probably all zeros. I would recommend to avoid narmalizing the target and rescaling it again. Instead just keep the class indices and remove the transformation for your target. If you call target.long() on small numbers, they will be all zeros. Scaling with 255 won’t change that. A…
rasbt
I’ve sum troubles getting a MLP classifier to train with MSE loss for some reason. Maybe it’s too late in the day and I am overlooking sth, but I am wondering how autograd can be made compatible if the model outputs are a [num_examples, num_classes] matrix. I.e., each column has a probability for a given example to bel...
ptrblck
I think you should also pass the predictions as a hot encoded tensor. If you pass the argmax as the prediction, it will be internally broadcasted to something like this (line of code): num_features, num_hidden, num_classes = 5, 20, 10 batch_size = 10 features = torch.randn(batch_size, num_feature…
Khilan_Pandya
I am getting this error while visualizing the dataThis is how I have loaded the data.num_classes = 2 batch_size = 13 net=CNN(out_1=13, out_2=32) DATA_PATH_TRAIN ="F:/project/d2" DATA_PATH_TEST ="F:/project/d2" trans = transforms.Compose([ transforms.ToTensor(), #transforms.Resize((100, 100)) ]) train_da...
ptrblck
Did you run the imshow code again? This code works for me: def imshow(img): plt.imshow(np.transpose(img.numpy(), (1, 2, 0))) plt.show() dataset = datasets.FakeData(transform=transforms.ToTensor()) image, target = dataset[0] print(image.shape) imshow(image) loader = DataLoader( datase…
Khilan_Pandya
Now the error of Mymodel is not defined has occured.Can you give me reference to a post or an article on how to perform segmentation and recognition using pytorch…
ptrblck
That’s good to hear! Is the initialization working now? This code runs perfectly on my machine: import torch import torch.nn as nn class CNN(nn.Module): def __init__(self, out_1=13, out_2=32): super(CNN, self).__init__() self.cnn1 = nn.Conv2d(in_channels=3, out_channels=…
ahathinking
Hi, I was using Anaconda for pytorch. Everything works perfectly until a few days ago. It stops working.I tried many different ways to solve this problem. However, the issue still exists.I remove anaconda and reinstall a new anaconda, create a new environment and install a new pytorch.Unfortunately, the errors are stil...
ptrblck
These is somewhere the libaten still on your system. Could you check your LD_LIBRARY_PATH for unnecessary paths? Also just to make sure we get rid of all installs, could you run this again: conda uninstall -y pytorch-nightly conda uninstall -y pytorch pip uninstall -y torch pip uninstall -y torch…
Yuerno
As far as I’m aware, if I usetorch.manual_seed(12), that will seed the PyTorch random number generator globally, so every time I use any Torch function involving random number generation, it’ll be automatically use the set seed. Is it possible to have seeding for one part of my PyTorch code, but then remove it and allo...
ptrblck
You could pass your torch.Generator manually to the random function. I’m not sure, if this API will change in the future, as this argument is not documented as far as I know and maybe shouldn’t be exposed in the current implementation. However, I think this code should work: gen0 = torch.Generato…
farazk86
Im using a Unet network for semantic segmentation. The loss reported by the network is very poor and so is the accuracy which is simple the intersection over union. Even after tens of thousands of iterations the loss does not seem to go below 0.91.Yet, if I manually see the results the network seems to have segmented e...
ptrblck
nn.BCEWithLogitsLoss expects your model output to be logits, so you shouldn’t use a threshold on them. On the other side, your custom DiceLoss might expect class predictions, but that depends on your implementation of it.
Valar_Morghulis
Im new in these area. So i have too many defiencies. Firstly i say to sorry for easy questions. i can not find on internet. Can anybody tell me this codes:#howcan unsqueeze add batch dimensions. what is the meaning of 0 and [:3,:,:] what is this?image = in_tansform (image)[:3,:,:].unsqueeze(0)#howthis code match size. ...
ptrblck
As I said I’m not familiar with the Udacity course, but I will try to answer your questions based on the code snippet you’ve provided. A try ... except block runs some code in the try section. If an exception is throws (e.g. due to an indexing error), the except section will be executed. Usually …
bluesky314
I am writting a custom version of dropblock and want to switch it off in evaluation mode by calling model.eval(), however I have no clue how to go about this. I tried looking at functional dropout but it is not defined there. How can this be done?
ptrblck
You could use the self.training flag in your custom module to switch between the different behaviors: apply your mask and scale the activations if self.training disable the mask and just forward the activations if self.training == False Let me know, if that works for you.
Ozzy_Codes
File "<ipython-input-1-68fc3e10bc2f>", line 141, in update action = brain.update(last_reward, last_signal) # playing the action from our ai (the object brain of the dqn class) File "/media/ozzycodes/ExtraData/Documents/Programming Files/Artificial Intelligence/OzzyCodes-AI/ozzyAI.py", line 100, in update sel...
ptrblck
batch_action seems to be a torch.FloatTensor. You can cast it to a torch.LongTensor using batch_action.long().
rsrade
Hello!I am a beginner in pytorch and had some doubts regarding creating a custom Neural Network class which has two functions -init() and forward(). I am getting different results when I keep an unused layer ininit() function (i.e, the layer is not used in forward() function) with respect to those obtained by removing ...
ptrblck
If you want to reproduce the exact same results, it might be tricky to just seed the script, if you are using additional layers. Each additional layer will get a random parameter initialization, which calls to the pseudo-random number generator, and will thus most likely yield small differences. Ha…
John1231983
Hello all, I am using below code to load dataset. However, theImageFolderonly worked for png format.transform = transforms.Compose([ transforms.Scale(opts.image_size), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ...
ptrblck
You could write your custom Dataset as described in theData loading tutorial. Basically, you would provide the image paths in the __init__ method, while loading and transforming each sample in __getitem__.
nulledge
In some projects, they calledtorch.saveandtorch.loadwith ‘pth.tar’ extension.I think ‘pth’ is for ‘PyTorcH’, but what is ‘tar’ for…?Actually I had tried to open ‘pth.tar’ files with Archive Manager and failedJust for curious.Thanks in advance.
ptrblck
.tar refers to tarball and is an archive file. As far as I know, the legacy serialization module used tarfile. You can find more information about this file formatin the Wikipedia article.
Ayshine
I’m trying to classify my images using transfer learning with inception_v3 and having an errorRuntimeError: cuDNN error: CUDNN_STATUS_BAD_PARAMWhat would be the reason of this error ?My transformtransform = transforms.Compose([ transforms.CenterCrop(1000), transforms.Resize((299,299)), ...
ptrblck
Could you print the shape out logps[0]? It should be [batch_size, nb_classes]. I also just realized, that you are assigning your Sequential classifier module to model.classifier. If you are using inception_v3, you should use model.fc instead. Here is a minimal code snippet which should work: mod…
joeyIsWrong
I am attempting to backward the loss on each different model. However, there is bug that statedRuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time.From my understanding, I have placed the 2 models on se...
ptrblck
Variables are deprecated since PyTorch 0.4.0, so you can just use tensors instead. You should detach the tensors coming from your generator, which should not create gradients in the generator. In a vanilla GAN setup you don’t want gradients in your generator while training your discriminator with t…
skyunyoo
My code is…batch_size = 16 transform = transforms.Compose([transforms.Resize((299,299)) ,transforms.ToTensor() ,transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) dataset = ImageFolder('.data/',transform=transform) kf = K...
ptrblck
kf.split will return the train and test indices as far as I know. Currently you are passing these indices to a DataLoader, which will just return a batch of indices. I think you should pass the train and test indices to aSubsetto create new Datasets and pass these to the DataLoaders. Let me kno…
Max1
BCEWithLogitsLoss()combinesmy binary classifier’s output Sigmoid layer and the BCELoss. Having the model trained and switched to.eval(), how do I obtain sigmoid output for given sample[s]?For an inference on a single sample, I could provide a target of1and reconstruct the sigmoid output from the loss value. But what co...
ptrblck
Yes, BCEWithLogitsLoss would be the criterion, so your training loop most likely looks like this: criterion = nn.BCEWithLogitsLoss() model = MyModel() for data, target in loader: optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimiz…
RonMcKay
Good evening everyone,I got a problem with loading multiple datasets and did not find a solution so far.For loading multiple datasets into one dataloader I can use the ConcatDataset class, but how do I concatenate e.g. CIFAR10 and MNIST. For this I would have CIFAR10 to resize and convert to grayscale without applying ...
ptrblck
You could specify the transformations for each dataset. This code should work: mnist = datasets.MNIST( root='/home/ptrblck/python/data', download=False, transform=transforms.Compose([ transforms.ToTensor() ]) ) cifar = datasets.CIFAR10( root='/home/ptrblck/python/data'…
a-parida12
I have 2 classification being trained back to back. when I do loss back in the second model, I get a error asking me to put retain_graph=True on the previous call. Which does not make sense to me.the training schematics is belowmodel1.train() model2.train() for i, data in enumerate(dataset): for _ in range(100): ...
ptrblck
y depends on x - the output of model1. If you call loss2.backward() Autograd tries to calculate the gradients using the computation graph. Since model2 and model1 are connected through x, Autograd also tries to calculate the gradients again for the parameters in model1. So save memory, the interm…
zephyr
HiI recently started with Pytorch. I was trying to build a model for multi-class image classification using pre-trained models from torchvision. My models seem to work fine. I used categorical entropy loss /NLLLoss.I was wondering if internally in the Pytorch framework, the labels are being converted to one-hot encodin...
ptrblck
Not in the case of nn.CrossEntropyLoss or nn.NLLLoss (which are equivalent). If you have a look at theformulato calculate the loss, you’ll see that only the current class index is needed to get the corresponding log probability. I guess other frameworks convert the one-hot encoded vector to an in…
ksanjeevan
I’m implementing an LSTM on audio clips of different sizes. After going through padding/packing, the output of the lstm is:a.shape = torch.Size([16, 1580, 201])with(batch, padded sequence, feature). I also have a list of the actual lengths of the sequences:lengths = [1580, 959, 896, 881, 881, 881, 881, 881, 881, 881, 8...
ptrblck
The following indexing should work: x = torch.randn(16, 1580, 201) idx = torch.tensor( [1580, 959, 896, 881, 881, 881, 881, 881, 881, 881, 881, 881, 881, 335, 254, 219] ) idx = idx - 1 # 0-based index y = x[torch.arange(x.size(0)), idx]
hanbit
I have two tensors, each size of (3x3), (5x5).How can I add or assign a smaller tensor to a bigger tensor starting from a specific position?Ex)A is a zero tensor size of (5x5).B is a tensor, all valued with 1.Then, I want to make C as below.(1)[[0, 0, 1, 1, 1],[0, 0, 1, 1, 1],[0, 0, 1, 1, 1],[0, 0, 0, 0, 0],[0, 0, 0, 0...
ptrblck
You could just index the bigger tensor and assign the smaller one to these positions: a = torch.zeros(5, 5) a[2:, 2:] = torch.ones(3, 3)
Pierre_Ouannes
Hi !So I might be missing something basic but I’m getting a weird behavior withF.interpolate:I created a 3D-tensor using :t = torch.randn(4,4,4)Or a least I thought it was 3D, butF.interpolatedoesn’t seem to agree. The following code :F.interpolate(t, scale_factor=(1,2,1))gives the errorValueError: scale_factor shape ...
ptrblck
The error message might be a bit weird, but it refers to an input of shape [batch_size, channels, *addidional_dims]. Given that you provide a “1D” input with a length of 4. Here would be an example using an image tensor: batch_size, c, h, w = 1, 3, 4, 4 x = torch.randn(batch_size, c, h, w) x = F…
dhecloud
Hello,I have aDatasetwhose__getitem__gives me a question and its correct answer (no problem here). Here’s my question: At every step, my model takes in 3 tensors:the questionthe correct answera random wrong answer from other questionsObviously I would have no problem getting item 1 and 2, but how can I cleanly get item...
ptrblck
You could just sample another index which is different to the one you are getting in __getitem__(self, index) and return this negative sample. Something like this should work: class MyDataset(Dataset): def __init__(self): self.data = torch.randn(100, 1) def __getitem__(sel…
mechatron
Hi,I have written the GAN network based on my understanding of the DCGAN tutorial and I am getting a runtime error that I do not fully understand. The code I use to train the networks is given belowGenerator_Loss = [] Discriminator_Loss = [] generated_images = [] for epoch in range(args['epochs']): for i,data in enu...
ptrblck
Could you try to detach the generator output when you train the discriminator on the fake data? y_pred_fake = discriminator_net(fake_data_on_gpu.detach()) This will make sure to create gradients in the generator in this step. When you train your generator you should just pass the fake input witho…
andreiliphd
Hello!I need to fast converge a neural network in a limited number of epochs. Image classification: CNNWhat I discovered:The network should be shallow.Learning rate balance is needed to converge fast.Could you give me the fastest converging optimizer and recommendation for learning rate and activation function in the l...
ptrblck
Fast.ai performed some interesting experiments with super-convergence and released a blog post about ithere. Maybe it could also be applicable to your use case.
Carsten_Ditzel
I dont quite get the difference between those two tensor entities. I roughly remember to have read somewhere that at::Tensor should best be avoided for some reason I cannot recall, but what is the general advise here?thanks in advance
ptrblck
at::Tensor is not differentiable while torch::Tensor is. It was similar to the difference between Variables and pure tensors in Python pre 0.4.0. As far as I know torch::Tensors won’t have any overhead in using them even if you don’t need to differentiate them, so that might be the reason to prefer…
chari8
I am working on image classifying task. I am usingtorch.utils.data.DataLoaderto load validation dataset.When I change the parametershufflefromTruetoFalse, I got different result, the sensitivity dropped. (Here, the result means sum of results from all validation data, so it should be the same as long as I am using same...
ptrblck
Are you setting your model to evaluation using model.eval() before feeding in your data? If that’s the case, could you post a (small) executable code snippet, so that we could have a look?
MariosOreo
I followed the example ImageNet to complete a project for semantic segmentation task.the code structure as follows:def main() ... for epoch in range(start_epoch, epochs+1): _train_epoch(epoch) _valid_epoch(epoch) ... ... def _train_epoch(epcoh): ... ... model.train() for steps,...
ptrblck
Yes, I would interpret these samples in a different range as samples from another data distribution. By saturation I mean that the parameters of your model were trained to create useful features using a normalized input. If you provide now much larger input values, the magnitude of your activation …
Saewon_Yang
I’m trying to apply image denoising through GAN.First I downsampled my images and then added noise using torch.randn.Is there any problem with this method? I trained the net and surely it didn’t work.I visualized my input data before feeding in, and I found that there are too much noise going in the input dataset. How ...
ptrblck
You could scale your noise with a standard deviation smaller than 1 to add less noise: std = 0.1 noise = torch.randn(opt.batchsize, 3, opt.imagesize, opt.imagesize) * std
farazk86
Hi ,I have a binary segmentation problem. Where the label/target tensor is a simple binary mask where the background is represented by 0 and the foreground (object I want to segment) by 1.I read that for such problems people have gotten great results using a single channel output, so the output from my U-Net network is...
ptrblck
You could just pass a torch.FloatTensor for the positive weight: output = torch.randn(1, 1, 10, 10, requires_grad=True) target = torch.randint(0, 2, (1, 1, 10, 10)).float() criterion = nn.BCEWithLogitsLoss(pos_weight=torch.tensor(10.)) loss = criterion(output, target) Let me know, if that works fo…
HappyPants
Greetings, I am relatively new to pytorch (also not very familiar with manipulating tensors) and I am trying to implement a function with the same behavior asnumpy.diff(https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.diff.html). I would like that this function works only with torch Tensors. After look...
ptrblck
I think indexing should just work: x = torch.tensor([1, 2, 4, 7, 0]) x_diff = x[1:] - x[:-1] print(x_diff) > tensor([ 1, 2, 3, -7])
hhh
Hello,everyone,I am new to PyTorch, and I feel confused about the reason of 16×5×5 in the codes below. Can anyone tell me why we choose 16×5×5 here? Thank you:)import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() ...
ptrblck
The number of input features to your linear layer is defined by the dimensions of your activation coming from the previous layer. In your case the activation would have the shape [batch_size, channels=16, height=5, width=5]. In order to pass this activation to nn.Linear, you are flattening this ten…
Gilles_Jack
In Pytorch, when using torchvision MNIST dataset, we can get a digit as follow :import torchvision import torchvision.transforms as transforms from torch.utils.data import DataLoader, Dataset, TensorDataset tsfm = transforms.Compose([transforms.Resize((16, 16)), transform...
ptrblck
Yeah, I’ve built torchvision from source, where these names were modified (source). You are right, if you need to transform the PIL.Images, my suggestion won’t work. I had in mind to push the already transformed tensors onto the GPU. However, I’m not even sure if you’ll really see a performance b…
Neda
I think I don’t have a good understanding of train accuracy. This is the snippet for train the model and calculates the loss and train accuracy for segmentation task.for epoch in range(2): # loop over the dataset multiple times running_loss = 0 total_train = 0 correct_train = 0 ...
ptrblck
You are currently summing all correctly predicted pixels and divide it by the batch size. To get a valid accuracy between 0 and 100% you should divide correct_train by the number of pixels in your batch. Try to calculate total_train as total_train += mask.nelement().
sun
class exampleNet(nn.Module): def __init__(self): super().__init__() self.layer = torch.nn.Sequential( torch.nn.Conv2d(3, 3, 9) ) def forward(self, x): x = self.layer(x) x = self.layer(x) x = self.layer(x) x = self.layer(x) return x
ptrblck
Your model contains one trainable layer which apparently should be used 4 times in a loop. Since the number of output channels does not match the number on input channels, your code won’t work currently. Also you’ve forgot to return x in your forward method.
sun
I am implementing a custom dataset class. If I set batchsize>=1, the code doesn’t work, please help me.import glob import os from torch.utils.data import Dataset from PIL import Image import torchvision.transforms as transforms from torch.utils.data import DataLoader class ImageDataset(Dataset): def __init__(sel...
ptrblck
It looks like some of your images are RGB (3 channels) images while others might be in grayscale format (1 channel). Could you try to convert all the RGB using: item_A = self.transform(Image.open(self.files_A[index % len(self.files_A)]).convert('RGB')) item_B = self.transform(Image.open(self.files…