user_q stringlengths 3 20 | question stringlengths 20 31k | user_a stringclasses 5
values | answer stringlengths 18 302 |
|---|---|---|---|
isalirezag | HelloI want to use the pretrained models, such as resnet101, and get the features after the layer 4, and save them.I dont want to load a pretrained model because i dont have memory to do thatThen have another model that i want to use those saved features.To clarify, the features that i want to save have size of1x1024xW... | ptrblck | If you would like to store the activations, you could use forward hook as described inthis example. Instead of the print statements use torch.save to save the activations using the dict.
Later, you can restore these activations using torch.load and use them as your training samples for the second … |
bmartin | Hi,I am trying to solve a mystery.The following code snippet generates a number of randomCUDAtorch tensors of various sizes and operates a few operations on these tensors.The stangness occurs when measuring the elapsed time using Python’stimeit.repeatfunction.Somehow, the first few iterations are a couple of orders of ... | ptrblck | Since CUDA operations are performed asynchronously, your time measurements are most likely a bit off.
You should call torch.cuda.synchronize() before starting and stopping your timer. |
Gautam_Venkatraman | Hi,I am a noob and am creating a model in PyTorch for the first time. I am trying to create a convolutional autoencode. No matter what optimizer or learning rate I use, I get the same loss pattern. The code I am using is:class MyDataset(Dataset):
def __init__(self, image_paths, target_paths, train=True):
se... | ptrblck | The fluctuating loss behavior might come from your hyperparameters, not from a code bug.
Did the model architecture work in the past with your kind of data?
Your model is currently quite deep, so if you started right away with this kind of deep model, the behavior might be expected. I’m usually th… |
bharat0to | Hi,I am trying to train a cnn to classify dogs, cats. But the network always outputs loss as 0.6931 and accuracy 50%. I have seen the same issue in this tutorialhttps://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.htmlI expect the val accuracy to increase slowly in case of scratch_model but wh... | ptrblck | Could you post your training code so that we can have a look and debug it?
Sometimes some hyperparameters are off, e.g. a too high learning rate was used. |
Neda | I am looking for how can I read a b8 file in Pytorch. Any comment will be appreciated. My images are cardiac ultrasound images which do have frames and converted from DICOM to b8 data. | ptrblck | Just for the sake of debugging, could you copy the file into your current working directory, where your python script is located, and try:
path = './ImgUS.dcm'
pydicom.read_file(path) |
barakb | Hi, I’m trying to use softamx2d and I can’t see what I’m doing wrong.I will show my problem using something that will be easier to understand.I have this 2d matrix of values and I want to make her to a probabilities matrix:image1096×892 155 KBso I’m using this code:self.softmax=nn.Softmax2d()
result = self.softmax... | ptrblck | Ah sorry, I misunderstood your use case.
My first code should work then:
y = nn.Softmax(2)(x.view(*x.size()[:2], -1)).view_as(x)
print(y[0, 1].sum())
Are you sure it’s not working? |
Neda | I am trying to show an image from MNIST dataset. I found in Keras is like the following. How can I do it in Pytorch?import matplotlib.pyplot as plt
%matplotlib inline # Only use this if using iPython
image_index = 7777 # You may select anything up to 60,000
print(y_train[image_index]) # The label is 8
plt.imshow(x_tra... | ptrblck | In case you didn’t use any transformations, you’ll get PIL.Images and can show them directly.
If you transformed the images into tensors, you could also use matplotlib to display the images.
Here are the two ways to show the images:
# As PIL.Image
dataset = datasets.MNIST(root='PATH')
x, _ = data… |
coyote | In pytorch, to update the model, should I use optimizer.step or model.step ? My question also valid for zero_grad() method?Here is a example snippet:import torch
import torch nn
class SomeNeuralNet(nn.Module):
def __init__(self,hs,es,dropout):
SomeNeuralNet(ClaimRecognizer, self).__init__()
# So... | ptrblck | nn.Module doesn’t have a step method, so you should call optimizer.step().
The model itself doesn’t know anything about the optimization of its parameters.
In case of calling zero_grad it depends on your use case.
If you pass all parameters to the optimizer, both calls will be identical and clear… |
l3r4nd | Hi, I have written a dataloader class to load my data but when I check their size the numbers differ when specified a batch_size.from torch.utils import data
class FlowerDataset(data.Dataset):
def __init__(self, root_dir, text_file, transform = None, target_transform = None):
self.root_dir = root_dir
... | ptrblck | The number of samples in your Dataset cannot be divided by the batch size without a remainder.
Therefore, your last batch will contain less samples then specified by batch_size.
If you want to get rid of this batch, use drop_last=True in your DataLoader. |
Neda | I am trying to use Adam optimiser, and after building the model and define optimiser as follows, I am getting an errorValueError: optimizer got an empty parameter listwhich I don’t know how to deal with it? Any comment would appreciate in advance.class NeuralNet(nn.Module):
def __int__(self):
super(NeuralNe... | ptrblck | You have a few typos in your model definition, e.g. __int__ instead of __init__, which is why your layers won’t be initialized and your parameters are empty.
Also, some layers have types, e.g. nn.maxpoo2d instead of nn.MaxPool2d.
After fixing these issue, you’ll get other errors, since self.hidden … |
Neda | Hi, I am new in CNN and Pytorch. I am wondering how in the first layer the input channel is 3 and the output is 6 (self.conv1 = nn.Conv2d(3, 6, 5) How the volume size of the output calculated?I know there is a formula W2=(W1−F+2P)/S+1 to calculate the output, and I read thishttp://cs231n.github.io/convolutional-network... | ptrblck | Conv kernels operate on the whole input channels as described in your link.
The out_channels give the number of different kernels used.
So in your first conv layer you are using 6 different kernels with a size of [3, 5, 5].
In other words, each kernel has a spatial size of 5 and a depth of 3, sin… |
Neda | I’m trying to convert CNN model code from Keras to Pytorch.here is the original keras model:input_shape = (28, 28, 1)
model = Sequential()
model.add(Conv2D(28, kernel_size=(3,3), input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten()) # Flattening the 2D arrays for fully connected layer... | ptrblck | The in_channels in Pytorch’s nn.Conv2d correspond to the number of channels in your input.
Based on the input shape, it looks like you have 1 channel and a spatial size of 28x28.
Your first conv layer expects 28 input channels, which won’t work, so you should change it to 1.
Also the Dense layers… |
HaziqRazali | I am having trouble trying to use thetransforms.Scale(size=(100,200))method as I keep getting the error message below. I have checked that using only the ToTensor() does not give me any error so I don’t think its an issue with the installation ? Also, I am aware that I have an older version of torchvision but I still c... | ptrblck | The error message is a bit strange, however the error might be thrown, since you are passing a numpy array instead of a PIL.Image.
The image transformations of torchvision.transforms usually work on PIL.Images, so try to load it as such.
Also, transforms.Scale is deprecated, you should use transfo… |
fermat97 | Hi, is there any Pytorch function to check which operation produces nan? | ptrblck | Yes! Have a look at theAnomaly Detectiondocs. |
Jean_Da_Rolt | Hi,I’m implementing a custom loss function in Pytorch 0.4. Reading the docs and the forums, it seems that there are two ways to define a custom loss function:Extending Function and implementing forward and backward methods.Extending Module and implementing only the forward method.With that in mind, my questions are:Can... | ptrblck | Sure, as long as you use PyTorch operations, you should be fine.
Here is a dummy implementation of nn.MSELoss using the mean:
def my_loss(output, target):
loss = torch.mean((output - target)**2)
return loss
model = nn.Linear(2, 2)
x = torch.randn(1, 2)
target = torch.randn(1, 2)
output = … |
beneyal | I’m getting the errorValueError: Expected input batch_size (1) to match target batch_size (10000).for the following code:class LogLinearLM(nn.Module):
def __init__(self, vocab_size):
super(LogLinearLM, self).__init__()
self.linear = nn.Linear(2*vocab_size, vocab_size)
self.softmax = nn.LogSo... | ptrblck | OK, in that case the second approach would be valid.
If you have one valid class for each sample, your target should have the shape [batch_size] storing the class index. E.g. if the current word would be class5, you shouldn’t store it as [[0, 0, 0, 0, 0, 1, 0, ...]], but rather just use the class i… |
isalirezag | I have a tensor of sizeBxCxHxWi want to mask the values in each channel as if they are larger than0.25*mean of that channelthe value be 1 and if they are lower than that the value be 0.How we can do it fast in pytorch?Thanks a lot in advance | ptrblck | Assuming you would like to create a mask of shape [B, C], would this work?
B, C, H, W = 10, 3, 4, 4
x = torch.randn(B, C, H, W)
y = torch.where(x > x.view(B, C, -1).mean(2)[:, :, None, None], torch.tensor([1.]), torch.tensor([0.])) |
Mona_Jalal | In the transfer learning tutorial, I have the following questions:How can I modify the code so that it also reports the test accuracy besides train and validation accuracy?How can I report per class accuracy?For academic papers, is it required to report all train, validation, and test accuracy or only train and validat... | ptrblck | I try to answer all questions, but take some of them with a grain of salt, as some of them are my personal opinion.
You would have to create a test dataset in the same manner as the train and val datasets were created.
Also, you could create a new transformation for the test Dataset or just use … |
nima_rafiee | Hi. I want to have one layer of Con2d with which theC_insize is defined after some processing in theforwardmethod and is not mentioned in advanced. How can I do this since I need to declare in my__init__method the fix size for C_in. is there any way like tensorflow which we can mentionNounwhich means the size can be m... | ptrblck | You could use the functional API to define your parameters in the forward method.
Here is a small example using a random number of kernels for the conv layer:
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.conv_weight = None
self.conv… |
Lewis | Hi. In the ResNet paper, the resnet output of a 224x224 image is 7x7, before the average pooling layer. However, PyTorch seems to give it as 8x8. Is there any different approach token? Attached is the image of demo.demo1853×547 33.7 KB | ptrblck | It seems your image shape is 254x254, which is probably a typo.
Could you try it again with 224x224? |
Moon_Lee | I am run my code on server that does not allow to upgrade to pytorch 0.4.1. It is still using version of 0.3.1. It has multiple GPU (4 GPUs)| 0 GeForce GTX TIT... Off | 0000:05:00.0 Off | N/A |
| 72% 86C P2 209W / 250W | 12065MiB / 12204MiB | 100% Default |
+------------------... | ptrblck | Make sure to set the visible devices before any other imports.
The easiest way would be to run your whole script using:
CUDA_VISIBLE_DEVICES=3 python script.py args
Also note, that setting the visible devices to a particular device masks all other devices.
That means you should only see the one … |
ZeratuuLL | Hello,I met a problem when using backward() to do backpropagation. The something strange came.I define a simple network with only 1 linear layernn.Linear(3,1)and usedload_state_dictto set the weights to be [1,1,1] and bias [0].Then I passedx = net(torch.tensor([1,2,3],dtype=torch.float))
L = x
L.backward()Then I usedop... | ptrblck | I guess you are observing the adaptive learning rates for different parameters of optim.Adam.
Try to use a simpler optimizer like optim.SGD and run it again. |
jan.olle | Hi everyone.So I’m trying to implement a deep neural network composed of a few linear layers. Every layer is composed of a 2x2 weight matrix and no biases. The peculiarity of my network is that I would only like to train one of the elements of each weight and leave the others untouched.To make things more concrete, eve... | ptrblck | You could use a hook to zero out all other gradients.
Here is a small example for a simple model:
model = nn.Sequential(
nn.Linear(2, 2),
nn.Sigmoid(),
nn.Linear(2, 2)
)
# Create Gradient mask
gradient_mask = torch.zeros(2, 2)
gradient_mask[0, 0] = 1.0
model[0].weight.register_hook(lam… |
spacemeerkat | As an update to this question:Does Pytorch have a method of sampling from a dataset (who’s objects are given weights based on their frequency of appearance in the dataset) such that for every draw you have a roughly balanced sample set for regression?For example: If you had a dataset who’s number of objects per label l... | ptrblck | I think it will still work. If I’m not misunderstanding your concern, that should be exactly how the WeightedRandomSampler works.
I’ve adapted an old example using two highly imbalanced classes:
numDataPoints = 1000
data_dim = 5
bs = 100
# Create dummy data with class imbalance 99 to 1
data = tor… |
Fractale | Is there two NN are identical from a practical point of view?Sequential(
(0): Linear(in_features=9328, out_features=100, bias=True)
(1): Sigmoid()
(2): Linear(in_features=100, out_features=16, bias=True)
(3): Softmax()
)
Sequential(
(0): Sequential(
(0): Linear(in_features=9328, out_features=100, bias=Tru... | ptrblck | Yes, they are identical.
The only difference between them are of course the values of the parameters due to random initialization.
If you want to use the same parameters, you could try the following:
modelA = nn.Sequential(
nn.Linear(9328, 100),
nn.Sigmoid(),
nn.Linear(100, 16),
n… |
DanielTakeshi | Hi all,I am hoping to confirm that what I did for data processing and visualizing images makes sense. I am doing a binary classification problem where images are (480,640,3)-sized depth images of blankets on a table-like surface.I have the following two gist codes here which one should be able to run in the same direct... | ptrblck | The calculation of the mean and std on your images looks good.
There is a small issue in your transformation.
As you said, the mean and std for the ImageNet data is smaller than yours, because it was calculated on the normalized tensors.
ToTensor will transform your PIL.Images to normalized tenso… |
XavierXiao | Hi, I am not sure if we call a layer define in the__init__for multiple times, do they share weights in the traning? For example, we have a function fc1 defined as:def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10,10)
...Then I called it multiple times:def forward(self, x1,x... | ptrblck | Yes, as you call the same layer, the same underlying parameters (weights and bias) will be used for the computation. |
Marina_Drygala | I am generating artifical data. I would like to filter out the rows of my input tensor that don’t satisfy a certain condition and then save the indices so that I can remove the corresponding rows from my output tensor. | ptrblck | Thanks for the example.
Let’s call the first tensor input, the second output and the last theta.
Would the following work:
threshold = 0.26
idx = theta > threshold
input_filt = input[idx]
output_filt = output[idx]
If you want to keep the negation, you could use:
input_filt = input[~idx]
output_… |
bonzogondo | Hi,I am new to PyTorch and I am currently working on an image classification project, in which I need to use ResNeXt-50 provided byFB.Firstly I had some problems loading the GPU-trained model on my CPU-only machine, but I used the built-in PyTorch ResNet-50 implementation and it works fine.However, I need to extract ch... | ptrblck | You could use forward hooks to get the desired activation.Hereis a small example for a dummy network. |
Grzegorz_Los | The question I’m about to ask is probably not PyTorch-specific, but I encountered it in context of PyTorch DataLoader.How do you properly add random perturbations when data is loaded and augmented by several processes?Let me show on a simple example that this is not a trivial question. I have two files:augmentations.py... | ptrblck | It’s a known issue, since you are using other libraries (numpy in your case) to generate random numbers.
Each worker will duplicate numpy’s PRNG, so that you’ll see the same numbers.
It’s described in theFAQa bit better.
You could sample random numbers using torch.randint or use worker_init_fn … |
Grzegorz_Los | I have been trying recently to fit a model for cat/dog recognition and noticed a strange behaviour. At the end of every training epoch I ran validation. Whenshuffleflag in my validationDataLoaderwas set to true, the loss on validation was close to the training loss. However, when I switchedshuffleto false, suddenly the... | ptrblck | You should set your model to evaluation using model.eval().
This will change the behavior of some layers, e.g. nn.Dropout won’t drop units anymore and nn.BatchNorm will use its running estimates instead of the batch statistics. |
Gautam_Venkatraman | Hi,I am trying to implement SGDR in my training but I am not sure how to implement it in PyTorch.I want the learning rate to reset every epoch.Here is my code:model = ConvolutionalAutoEncoder().to(device)
# model = nn.DataParallel(model)
# Loss and optimizer
learning_rate = 0.1
weight_decay = 0.005
momentum = 0.9
# cri... | ptrblck | Would you like to lower the learning rate to its minimum in each epoch and then restart from the base learning rate?
If so, you could try the following code:
model = nn.Linear(10, 2)
optimizer = optim.SGD(model.parameters(), lr=1.)
steps = 10
scheduler = optim.lr_scheduler.CosineAnnealingLR(optimi… |
andreiliphd | I will be really thankful to those who can explain me this. I know the formula for calculation but after some iterations, I haven’t got to the answer yet.The formula for output neuron:Output = ((I-K+2P)/S + 1), whereI - a size of input neuron,K - kernel size,P - padding,S - stride.Input tensor shape:torch.Size([36, 200... | ptrblck | Your input shape seems to be a bit wrong, as it looks like the channels are in the last dimension.
In PyTorch, image data is expected to have the shape [batch_size, channel, height, width].
Based on your shape, I guess 36 is the batch_size, while 3 seems to be the number channels.
However, as you… |
rasbt | I notice that I get different results when I use DataParallel compared to a single GPU run. When I execute the same code on 1 GPU, I get the same loss if I repeat that procedure (assuming a fixed random seed). For some reason though, the loss is ~5% different if I useDataParallel. Is that a bug or some design-workaroun... | ptrblck | I think the difference might come from the gradient reduction of all device gradients after the backward pass.Hereis an overview of the DataParallel algorithm.
Unfortunately, I can’t test it right now, but from my understanding after the parallel_apply of model’s backward pass, the gradients wil… |
jingjing | Dear all,I am trying to train my own Resnet model using .npy format files.I am wondering that are there any functions like torchvision.datasets.ImageFolder that can load .npy files in a folder and label these numpy array with their folder name? | ptrblck | Alternatively to@albanD’s solution, you could also useDatasetFolder, which basically is the underlying class of ImageFolder.
Using this class you can provide your own files extensions and loader to load the samples.
def npy_loader(path):
sample = torch.from_numpy(np.load(path))
return sa… |
michael_ben_ami | Hi, I’m new in pytorch…how can I save only part of the model?I train model that for training has 3 output but for inference, I just need one of the outputscan I load the model and save just the part I need?that would save time in the inferencehas some have an example?Thanks | ptrblck | I would save the whole model’s state_dict and just reimplement an “inference” model, which yields only one output. Here is a small example:
class MyModelA(nn.Module):
def __init__(self):
super(MyModelA, self).__init__()
self.fc1 = nn.Linear(10, 1)
self.fc2 = nn.Linear(1… |
Tudor_Berariu | Is it possible to perform backpropagation and accumulate gradients in just a subset of the leaf variables involved in the computational graph? My solution now is to callautograd.gradand then copy the result in the.gradtensors of those parameters. Is there a way to do this directly?import torch.nn as nn
import torch.nn.... | ptrblck | I’m not sure, how exactly your code works, but do you think you could play with the requires_grad attribute of your models?
E.g. in case you want to use loss1 to calculate the gradients for model1, but not model2, you could just disable gradients for model2:
for param in model2.parameters():
p… |
Mona_Jalal | How is PyTorch doing the transfer learning? Does it just take the last layer of resnet and pass it to a new neural network classifier for my categories or does it retrain all the way back to resnet?Also, apart from what is inthis link, are there other implementation of Transfer Learning in PyTorch? | ptrblck | It depends on you and your use case, which part of the model will be fine tuned.Andrej Karpathy explained in Stanford’s CS231you can use the size and similarity of your data as a baseline:
New dataset is small and similar to original dataset . Since the data is small, it is not a good idea to … |
snakeztc | I am computing a vector and matrix multiplication in two different ways. Mathematically they are equivalent, however, PyTorch gives different (slightly results for them).Can someone please explain to me why it happens and hopefully the slight difference can be ignored in practice.import torch
import numpy as np
x = tor... | ptrblck | A difference of approx 1e-6 is explainable due to the float32 precision.
In practice you can ignore it. If you need a higher precision, you could use float64 instead.
Note that your performance will suffer on the GPU.
Here is another example. Clearly the sums should yield the same number. However… |
arc144 | Hi there, I’m running some profiling on my training code and I realized that every 11 iterations (batches) the code freezes for a while when callingoptim.stepthen it resumes normally for the next 11 iterations. Does it have to do with gradient checking or maybe a bug in my code?The training loop is as follows:for i, (i... | ptrblck | The DataLoader uses multiprocessing to load the batches asynchronously while the training takes place.
However, if you have some heavy preprocessing in your Dataset or the data loading is IO bound, you might notice small freezes as the workers can’t keep up processing the data fast enough.
You cou… |
somnath | I am performing multi label image classification. I am using DataLoaders for this. How can I see the breakdown of the number of training and test images present for each class? | ptrblck | I assume your labels are saved in a one-hot encoded format for a multi label classification.
If that’s the case, you could iterate your Dataset once and just count all class occurrences:
class MyDataset(Dataset):
def __init__(self, num_classes):
self.data = torch.randn(100, 2)
… |
Ce_Jiang | I have some problems with how to use ‘Variable’.Which parameter should be ‘Variable’ when I achieve a network? | ptrblck | Since PyTorch 0.4.0 you don’t have to use Variables anymore.
You can use tensors now and set requires_grad=True, if you need the gradient for this tensor.
If you don’t need gradients at all, e.g. for validation, wrap your code in with torch.no_grad():. This was previously achieved by setting volat… |
Carl | Hey there!I’m trying out the PyTorch 1.0 C++ API, and I can’t find how to do a simple assignation, like in the following python snippet:my_tensor[0, 0] = 1I tried the following:my_tensor[0, 0] = 1.f;I was surprised to see that it compiles; but unfortunately it’s just equivalent to calling:my_tensor[0] = 1.f;(Only the f... | ptrblck | Not sure, if that’s the recommended way, but my_tensor[0][0] = 1.f; works for me. |
coyote | Hi everyone,I am new to Pytorch (and row major calculations). I would like to build a convolutional neural network for text based applications. My batch size is 64 (64 sentences in each batch), embedding size is 200 and each sentence contains 80 words. Inside the model (in init method) I initialize my embeddings as ... | ptrblck | I’ve created a small example here:
batch_size = 64
embedding_dim = 200
vocabulary_size = 100
sentence_len = 80
out_channel = 100
embedding = nn.Embedding(vocabulary_size, embedding_dim)
conv1 = nn.Conv1d(embedding_dim, out_channel, kernel_size=2)
x = torch.empty(batch_size, sentence_len, dtype=to… |
dem123456789 | I actually modify a little bit of your code and I can reproduce the error with nn.ModuelList().I also try SGD, and it has the same error.Can you help me verifying this?You can find the codehere | ptrblck | No, the manual seed is not the issue. I’ve just used it in my first example to show, that the optimizer does not have any problems optimizing a model with unused parameters.
Even if we copy all parameters between models, the optimizer works identically.
So back to your original question. The discr… |
farazk86 | Hi,I’m using the following two functions to find the accuracy of my semantic segmentation network, I found this code on github and they seem to work but I dont exactly know how. I am trying to understand what each line is doing.I have commented each line with what I think is going on, if I am wrong in my understanding ... | ptrblck | Let’s walk through the code using your explanations:
def get_predictions(output_batch):
bs, c, h, w = output_batch.size() # size returns [batchsize, channels, rows, columns]
# Get's the underlying data. I would prefer to use .detach(), but that shouldn't be a problem here.
ten… |
Paralysis | Suppose I have two networks A, B in sequence. Two different loss functions are applied on the resulting features, i.e. in forward pass I have:y = A(x)
z = B(y)
loss1 = loss_func1(z)
loss2 = loss_func2(z)loss1 only update network A, and loss2 update both network A and B.I have optimizer for both A and B independently. N... | ptrblck | I think your approach is alright. A small improvement might be to switch the order of updating the models.
You could first call loss2.backward(retain_graph=True) and update B as you need this gradient in A a bit later. Then call loss1.backward() and update A.
Here is a small example:
modelA = nn… |
tgeft | I’ve implemented a custom dataset which generates and then caches the data for reuse.If I use the DataLoader withnum_workers=0the first epoch is slow, as the data is generated during this time, but later the caching works and the training proceeds fast.With a higher number of workers, the first epoch runs faster but at... | ptrblck | Yeah, I understand the issue and stumbled myself a few times over it.
I think one possible approach would be to use shared memory in Python e.g. withmultiprocessing.Array.
You could initialize an array of your known size for the complete Dataset, fill it in the first iteration using all workers, … |
Dr_John | Assume that I create two datasets that differ by their “getitem” protocol (for example, “dataset1” in the code below gives a denoised version of every image in the original dataset and “dataset2” in the code below gives the original version of the image), and want to create a new dataset, which consists of the first 10... | ptrblck | I think you could create both Datasets and pass them to a custom Dataset, which concatenates the samples of both underlying Datasets.
I’ve created a small example using ImageFolder:
dataset1 = datasets.ImageFolder(
root='YOUR_PATH',
transform=transforms.ToTensor())
dataset2 = datasets.Ima… |
tejax | I’ve been scrolling down through PyTorch Cifar-10 convolutional neural network tutorial and I find it strange how the Softmax activation function wasn’t used in the output layer of the forward(self,x) function:class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv... | ptrblck | In a classification use case you can pass the raw logits (i.e. the model output without a non-linearity) to nn.CrossEntropyLoss. Internally F.log_softmax and nn.NLLLoss is called.
Alternatively you could add nn.LogSoftmax to out output layer and use nn.NLLLoss as the criterion.
The underscore is u… |
farazk86 | Hi,I’m trying to understand the process of semantic segmentation and I’m having trouble at the loss function. For simple classification networks the loss function is usually a 1 dimensional tenor having size equal to the number of classes, but for semantic segmentation the target is also an image.I have an input image ... | ptrblck | Based on the output shape it looks like you have 32 different classes.
Your target shape, i.e. the segmentation mask, should have the shape [batch_size, 224, 224], and should contain the class indices as its values.
The spatial size mismatch between the target mask and the model output does matter… |
alpapado | I am probably misunderstanding something but:In the docs of functional.normalize (https://pytorch.org/docs/stable/nn.html#torch.nn.functional.normalize) we can read:Performs Lp normalization of inputs over specified dimension.Does v=v / max(‖v‖p,ϵ)for each subtensor v over dimension dim of input. Each subtensor is flat... | ptrblck | The tensor is normalized over dimension dim, such that:
(x[:, 0, 0, 0])**2.sum() == 1
(x[:, 0, 0, 1])**2.sum() == 1
...
In your use case you could do the following:
x_ = F.normalize(x.view(x.size(0), -1), dim=1, p=2).view(x.size())
(x_[0]**2).sum() == 1 |
TechnicalTim | I’m at a loss at how to ensure that the data and the model are both on the GPU. I tried multiple approaches.This is the code:TODO: Display an image along with the top 5 classesGet and process a Test Imagetorch.set_default_tensor_type(‘torch.cuda.FloatTensor’)test_image_index = 28test_image = test_dir + “/” + str(test_i... | ptrblck | It looks like your input tensor is still on the CPU.
You should push your data as well as the model onto the device:
data = data.to('cuda')
target = target.to('cuda')
model = model.to('cuda') # assignment not really necessary here
If you want to check the current device of the tensor, just use pr… |
TechnicalTim | I noticed that other people are able to successfully avoid the “str’ object has no attribute ‘size’” error message, but I’m getting it for some reason. What is the reason for that and how can I correct that?Error message:AttributeError Traceback (most recent call last)in ()5 test_image_index ... | ptrblck | It seems you are passing the image path to process_image instead of an PIL.Image.
Try to load the image and pass it to the function:
from PIL import Image
test_image_path = ...
test_image = Image.open(test_image_path)
process_image(test_image) |
reverts | Building from source, and I can’t get Jetson TX2, an ARM64, to compile properly.I follow the reccommendations from nVidia’s forums here:gist.github.comhttps://gist.github.com/dusty-nv/ef2b372301c00c0a9d3203e42fd83426pytorch_jetson_install.sh#!/bin/bash
#
# pyTorch install script for NVIDIA Jetson TX1/TX2,
# from a fres... | ptrblck | It looks like ONNX has some problems with protobuf.
Did you pull from master before trying to rebuild PyTorch?
If so, could you call git submodule update --init --recursive and try to build again?
I ran into similar issues when some submodules weren’t properly updated. |
farazk86 | So I have been teaching myself PyTorch for semantic segmentation using FCN.I started with learing about Dataset class and DataLoaders and made a simple network that could classify the MNIST datadset.I moved to FCN and coded the network architecture from the paper and from the provided diagram and also from looking at s... | ptrblck | You could usethis codeto transform your color label images to label images containing class indices. |
barakb | Hi, I’m trying to load pretrained weights of 3d resnet34, the model is from here:https://github.com/kenshohara/3D-ResNets-PyTorch/blob/master/models/resnet.pythe weights are from here:https://drive.google.com/drive/folders/1zvl89AgFAApbH0At-gMuZSeQB_LpNP-MMy code is :def resnet34(feature_size, frame_size, frames_sequ... | ptrblck | You probably saved the model as a nn.DataParallel module. Have a look atthisthread. |
Santhoshnumberone | Here is my code# [Convolution] -> [Batch Normalization] -> [ReLU]
def Conv_block2d(in_channels,out_channels,*args,**kwargs):
return nn.Sequential(nn.Conv2d(in_channels,out_channels,*args,**kwargs,bias=False),nn.BatchNorm2d(out_channels,eps=0.001),nn.ReLU(inplace=True))
class MainBlock(nn.Module):
"""docstring for... | ptrblck | Try to append the pooling layer like this:
nn.Sequential(*Conv_block2d(3, 6, 3, 1, 1), nn.MaxPool2d(2)) |
arvindmohan | Here is an example using Pytorch 0.4.0In [1]: import torch
In [2]: import torch.utils.data
In [3]: ... | ptrblck | I just checked it in 0.4.0 and apparently the import just seems to fail.
Run the following:
from torch.utils.data import distributed
sampler = distributed.DistributedSampler() |
Poby | Hello. I encountered a confusing problem when I write a simple GRU demo, that is the GPU memory keep going up every iteration. I don’t know if there are some mistakes in my code.my code:import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.optim import Adam
from torch.utils.... | ptrblck | I’m no expert in RNN, but it seems you are keeping the complete history of your hidden states, which uses more memory for each epoch and also slows down the code after a while.
If you re-initialize your hidden states in each epoch with:
model.gru_hidden1 = model.init_gru_hidden(batch_size)
model.g… |
tao | Dear CommunityI would like to build a simple MLP that assigns class A or B to a given input.The input data are 128d feature representations extracted from FaceNet.Input data (X): shape=(23445, 128), dtype=float64The target data are the binary class labels 0 or 1 (denotes class A or B)Target data (y): shape=(23445, 1), ... | ptrblck | You have different options for a binary classification use case:
you could use 1 output neuron and [nn.Sigmoid + nn.BCELoss]
1 output neuron and [raw logits (no non-linearity for the last layer) + nn.BCEWithLogitsLoss]
2 output neurons and [nn.LogSoftmax + nn.NLLLoss]
2 output neurons and [raw log… |
farazk86 | Hi,Im trying to make my first CNN using pyTorch and am following online help and code already people wrote. i am trying to reproduce their results. I’m using the Kaggle Dogs Breed Dataset for this and below is the error I get. The trainloader does not return my images and labels and any attempt to get them leads in an ... | ptrblck | I guess your self.transform contains some image transformations other than ToTensor(), e.g. RandomCrop().
These transformations currently work on PIL.Images, so if you load your image with img = Image.open(this_img) it should work. |
jaeyung1001 | my model is like below:class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(4909, 1500)
self.relu1 = nn.ReLU()
self.dout = nn.Dropout(0.2)
self.fc2 = nn.Linear(1500, 300)
self.prelu = nn.PReLU(1)
self.out = nn.Linear(300, 1)
... | ptrblck | nn.Sigmoid and nn.BCEWithLogitsLoss don’t fit together.
Either remove the nn.Simgoid or use nn.BCELoss. |
anesh117 | I trained my model on two classes. I saved the model weights and I want to initialise my new model with the saved weights . How to do it ? | ptrblck | If you’ve saved the state_dict you can load it with model.load_state_dict(torch.load(PATH_TO_DICT)).
Have a look at theSerialization Tutorialfor more information. |
bgenchel | recently, i’ve been seeing warnings saying that you need to add a ‘dim’ argument to Softmax as the implicit dimension selection is being deprecated.I have a model that I found on github that uses a softmax layer (nn.LogSoftmax) in its forward function and an F.softmax() in its inference functions.The data i’m feeding i... | ptrblck | Could you print the shape of the tensor you are passing to F.softmax?
It seems dim2 is just missing. Are you adding the batch dimension to your data in the test case? This is often forgotten and yields these kind of errors.
You can call functions like softmax on “negative” dimensions to use revers… |
markroxor | Is there a way to specify our own custom kernel values for a convolution neural network in pytorch? Something likekernel_initialiserin tensorflow? Eg. I want a 3x3 kernel innn.Conv2dwith initialization so that it acts as a identity kernel -0 0 00 1 00 0 0(this will effectively return the same output as my input in the ... | ptrblck | You would need to set requires_grad=True for the weights and it would also work as nn.Conv2d internally just calls the functional API, seehere.However, if you prefer to use the module, you could try the following code:
weights = ...
conv = nn.Conv2d(nb_channels, 1, 3, bias=False)
with torch.no_… |
bgenchel | Running PyTorch 0.4.1 on Ubuntu 16.04Trying to run a network, and get the following warning message:UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.Add the dim argument to the function then get the following error:File "main.py", line 160, in main
... | ptrblck | Pass the dim argument to the constructor of the class: self.softmax = nn.Softmax(dim=1). |
ChangGao | Hi, I am using PyTorch to do a regression task.Mainly I am using the neural network to approximate some values given some inputs.But I found that the order of magnitude of approximation accuracy is about 10^-5.For a deeper neural network this stays the same.I am wondering if this could be the result of training with si... | ptrblck | This sounds like a float precision issue.
You’ll get the same for different orders of operator execution:
torch.set_printoptions(precision=10)
x = torch.randn(100, 10, 100)
x1 = x.sum()
x2 = x.sum(0).sum(0).sum(0)
print(torch.abs(x1-x2))
> tensor(0.0001220703) |
juhyung | Hi,I have 300G size h5 file that has images, texts.and I’m having trouble with dataloader. for example, in the code,class loader(Dataset):
def __init__():
self.file = load(my_300G_file)
def __getitem(self, index):
return self.file[index]Will I get memory error? because I load 300g file? (my ram ... | ptrblck | Yes, that’s the plan. You would need to use the method I’ve posted as you can’t directly index the h5 file. |
dajiahao | Hello Everybody,I’m new to PyTorch and I have a question about how to understand the layer object in the forward function. Here is an example:class Net(torch.nn.Module):
def __init__(self, n_feature, n_hidden, n_output):
super(Net, self).__init__()
self.hidden = torch.nn.Linear(n_feature, n_hidde... | ptrblck | nn.Linear is also an nn.Module just like your Net.
Internally when you call Net(x) or self.hidden(x) the __call__ method is called, which registers hooks etc., and finally calls forward. You can check it out in thesource file. |
dem123456789 | I got an error when I use dataloader to load CocoDetection dataset and set num_workers > 0.It appears to be a problem related to multiprocessing.Traceback (most recent call last):
File "<string>", line 1, in <module>
File "D:\Anaconda3\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
... | ptrblck | Did you try to add the main guard as suggested in the error message?
Python on Windows has some issues regarding multi-processing, so try to add:
if __name__=='__main__':
run() # your main code
to your code. |
rafaela00castro | Hello everyone! I’m trying to implement my Keras/TF model in PyTorch. The model is a simple conv3d. Both models are running on CPU. So what am I doing wrong? Because the loss at any step (training, validation, test) are totally different between Pytorch and Keras.[Keras]epochs = 10
used_samples = 100
batch_size=10
vali... | ptrblck | Skimming through your examples I could only see the difference in the parameter initialization. While Keras seems to use glorot/xavier_uniform for the weights and zeros for the bias, PyTorch uses kaiming_uniform for the weights and some other uniform init for the biassource.
Could you try to initi… |
TheShadow29 | If I use different weights for the same network, the forward pass speeds are very different. One takes around 0.017s the other takes 0.6s I am unsure why this is happening. Both the weights file have the same size (101M).The first one is provided by author of a repository, while the other is just retrained. So I am gue... | ptrblck | Sorry for the late reply. I’ve reproduced the timing issue, profiled your code using torch.utils.bottleneck, and it seems run with random weights just performs a lot more calls to layers/box_utils.py.
It’s a guess as I’m not familiar with the code, but I think the random weights just might create a… |
Wei_Chen | Hi, I have a training set which I want to divide into batches of variable sizes based on the index list (batch 1 would contain data with index 1 to 100, and batch 2 contains index 101 to 129, batch 3 contains index 130 to 135, …, for instance). I check dataloader but it seems to me that it only supports fixed-size bat... | ptrblck | Do you know these lengths beforehand?
If so, you could use these indices to slice your data, set batch_size=1 and view your data to fake your batch size:
class MyDataset(Dataset):
def __init__(self):
self.data = torch.randn(250, 1)
self.batch_indices = [0, 100, 129, 150, 200, 2… |
Krish | Iterating through the MNIST Dataset from torch vision throws error--> for i, data in enumerate(trainloader):This line causes the following error:TypeError: zip argument #2 must support iterationHow can I deal with this? | ptrblck | Thanks for the code.
The error is thrown, because Normalize internally iterates the tensor channels, mean and std.
Since you just have one value, you should pass it as:
transforms.Normalize((0.5,), (0.5,))
Also, have a look atthese mean and std estimates. They might work a bit better than 0.5, … |
blindelephants | If I have a tensor that is of shape[96, 16, 160]that is the output from a model I’m trying to train, and my targets are in a tensor of shape[96, 16, 1](where there are 160 different classes, hence the appearance of 160 in the first, and 1 in the second), what’s the proper method for putting these two tensors into a los... | ptrblck | features stands here for out class logits, i.e. you have 160 classes?
If so, you could view the seq_len and batch_size together, in case you want a prediction for each seq timestamp:
x = torch.randn(96, 16, 160)
y = torch.empty(96, 16, dtype=torch.long).random_(160)
criterion = nn.CrossEntropyLos… |
taiky | Hi All,I want to sample a small part of data from a massive, imbalance dataset, and then split it as training part and validation part.For the sample part, I know the WeightedRandomSampler is the best choice.For the split part, I use SubsetRandomSampler before.But I don’t know how to sample then split because the Weig... | ptrblck | For the SubsetRandomSampler you would need to provide indices, so we have to get the balanced indices from WeightedRandomSampler.
One way would be to create the sampler and instead of returning the data we could return the indices and store them somehow. This doesn’t really sound like a good approa… |
soulless | I am using pretrained Densenet121 from torch vision within my custom nn.module. However, the titled error happens even if I use .cuda(). I tried using .cuda within the init function of CustomNet but it still gives the same error. Please assume I would remove the last layer and replace the classifier of DenseNet with an... | ptrblck | Did you forget to assign the tensor back?
tensor = tensor.to('cuda') |
Krish | I am trying to implement one-hot encoding for MNIST imported from Kaggle. The shape of the encoding is [1, 10] but when the loss function runs, it throws the following error:ValueError: Expected input batch_size (10) to match target batch_size (256).My mini batch-size is 256.What should I do? | ptrblck | Sure, the model in the tutorial outputs 10 logits in its last linear layer. As you can see, no non-linearity was used on this layer, so that the values represent the raw logits for all 10 classes.
If you call softmax on them, you would get the probabilities for each class, but we don’t want to do t… |
halahup | Hey there, I have faced an issue with using theWeightedRandomSamplerwhere even with the assigned weights the majority class is being resampled more heavily than the remaining classes. Is there a capacity to the weighted random sampler beyond which resampling doesn’t reweight the samples any more? | ptrblck | I used 0.4.0 and tried to stay as close to your code as possible.
This code works on my machine:
data = torch.randn(1000, 1)
target = torch.cat((
torch.zeros(998),
torch.ones(1),
torch.ones(1)*2
)).long()
cls_weights = torch.from_numpy(
compute_class_weight('balanced', np.unique(t… |
sanayam | HelloHow can I calculate the SNR value of the image in python? | ptrblck | You could usescipy.stats.signaltonoise. |
Jiang | Hello everyone!I am new in PyTorch and I tried to implement randomly scaling the input images (e.g. from 0.5 to 1.5) during training which is mentioned in the Deeplab paper. Here is the code.class RandomScale(object):
def __init__(self, limit):
self.limit = limit
def __call__(self, sample):
img... | ptrblck | You could sample the random crop size once for the next batch and resample in each iteration of your DataLoader.
Maybe not the most elegant approach, but should do the job.
Here is a small dummy example:
class MyDataset(Dataset):
def __init__(self, limit):
self.data = [TF.to_pil_image… |
apytorch | How could one do both per-class weighting (probably CrossEntropyLoss) -and- per-sample weighting while training in pytorch?The use case is classification of individual sections of time series data (think 1000s of sections per recording). The classes are very imbalanced, but given the continuous nature of the signal, I ... | ptrblck | That sounds right!
I’m not sure, what S samples are in your example, but here is a small dummy code snippet showing, what I mean:
batch_size = 10
nb_classes = 2
model = nn.Linear(10, nb_classes)
weight = torch.empty(nb_classes).uniform_(0, 1)
criterion = nn.CrossEntropyLoss(weight=weight, reducti… |
redlcamille | Hi guys, I want to use aCNNas a feature extractor. When defining a neural net withnn.Sequential, for exampleself.features = nn.Sequential(OrderedDict({
'conv_1': nn.Conv2d(1, 10, kernel_size=5),
'conv_2': nn.Conv2d(10, 20, kernel_size=5),
'dropout': nn.Dropout2d(),
'linear_1': nn.Linear(... | ptrblck | Your get_index_by_name method could implement something like this small hack:
list(dict(features.named_children()).keys()).index('conv_2')
> 1 |
redlcamille | Hey guys, I’m a newbie topytorch. I want to ask how to check if amodule(when iterating overself.modules()) is in thestate_dictof a pretrainedmodelor not. I’m building up anautoencoderwith apretrainedencoder, so I want to efficiently init the network by only init weights and biais of layers not in the pretrained encoder... | ptrblck | I’m not sure you will gain that much from filtering out the other layers, as usually you just initialize the model once before the training.
Would it be possible to just initialize all layers and load the pretrained parameters after it or is your use case different?
If this would work, here is a s… |
fangyh | I expand data in getitem, how can I stack it in collatefn?from torch.utils.data import Dataset
import numpy as np
class BarDataset(Dataset):
def __init__(self):
self.data = list(np.random.rand(9))
pass
def __getitem__(self, idx):
# some ops
out = np.array([self.data[idx] * 2, s... | ptrblck | Ah OK.
I guess you want to use the same data in your Dataset?
If so, you could just fake a new length and use a modulo operation in index to avoid an out of range error:
class BarDataset(Dataset):
def __init__(self):
self.data = list(np.random.rand(9))
pass
def __getitem_… |
Hesdan | Hi,I’m a novice and am learning ML. I have loaded the pytorchvision dataset and trying to visualize the data through iterate method . How do I know that there are only parameters images and labels in the dataset? Where and how do I find this information? Any help is sincerely appreciated.Download and load the test data... | ptrblck | You could have a look at the __getitem__ method of your Dataset to see all returned values. |
zeal | Sometimes, I found that some source code of pytorch are not listed in pytorch document website:https://pytorch.org/docs/stable/index.htmlBut I found a Github repo of pytorch here:https://github.com/pytorchHowever, I think the source code in that repo is not the real source code or the latest version. Some attributes of... | ptrblck | You are probably looking into the master branch of torchvision, which might differ from your current installed version.
A few weeks ago there was a small refactoring, which added permanent data and target variables instead of train_data etc.
Have a look atthis diff. |
handesy | Hi,I was wondering what the equivalent function totf.unsorted_segment_sum(https://www.tensorflow.org/api_docs/python/tf/unsorted_segment_sum) is. I can come up with two alternatives:Use (sparse) matrix multiplication. SupposeYhas shape(M,D)andXhas shape(N, D), we can doY = I @ XwhereIis aMbyNsparse binary matrix. The i... | ptrblck | Would scatter_add with dim=1 work?
index = torch.tensor([[0, 0, 1, 1, 0, 1],
[1, 1, 0, 0, 1, 0]])
data = torch.tensor([[5., 1., 7., 2., 3., 4.],
[5., 1., 7., 2., 3., 4.]])
torch.zeros(2, 2).scatter_add(1, index, data)
> tensor([[ 9., 13.],
[ … |
btang | I am trying to come up with an efficient way of summing uneven chunks of a tensor. The answer has the same size as the inputs, which include a data tensor and an index tensor. For example,array = torch.Tensor([[0, 1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12, 13],
[14, 15, 16, 17,... | ptrblck | It looks like your index is missing a row or your array has one additional row (row2 based on the result).
A combination of scatter_add_ and gather would work:
array = torch.tensor([[0., 1, 2, 3, 4, 5, 6],
[7, 8, 9, 10, 11, 12, 13],
[21, 22, 23, 24, 25, … |
Naman-ntc | Why is track_running_stats set to True in eval. This may lead to performance degradation of pretrained model as well and in my opinion should be default behaviour.And what is recommended method to set track_running_stats False, currently I am just usingmodel.apply(fn)Infact if such a model with track_running_stats is d... | ptrblck | track_running_stats is used to initialize the running estimates as well as to check if they should be updated in training (line of code).
The running estimates won’t be updated in eval:
bn = nn.BatchNorm2d(3)
for _ in range(10):
x = torch.randn(10, 3, 24, 24)
out = bn(x)
print(bn.running_m… |
crack00ns | I have a model (nn.module) class and inside this class i create a random tensor using torch.randn(). When I create a model.to(device) where device is cuda, the random tensor doesn’t get moved to cuda. Is the behavior correct? how should i do it, without passing device to the model.Thanks | ptrblck | By default only Parameters will be recognized and pushed to the according device.
Try to wrap your random tensor into torch.nn.Parameter(torch.randn(1), requires_grad=False) and it should work.
Alternatively you could also store it in a nn.ModuleList. |
pjavia | In PyTorch 0.4 Variables are depreciated. Just to get more clarity. How to make sure that at certain point no new tensors would be retained?For example, to collect loss I use to follow this stepsrunning_loss += loss – this is incorrect in context of Variablerunning_loss += loss.dataAlso, what is significance of .data w... | ptrblck | .data has still the same semantics, but it’s recommended to use .detach() instead.
Have a look at theMigration Guide(“What about .data?” section).
To collect your loss, the recommended way is to use loss.item() instead of loss.data[0], since indexing into a scalar will give you a warning for now… |
zihaog | Hi,I got the following error when I do transfer learning using inception_v3.IndexError: index 1 is out of bounds for dimension 1 with size 1Here’s part of my code:for epoch in range(num_epochs):for i,(images,labels) in enumerate(train_loader):
outputs = model(images) ### error in this lineThe shape of my ... | ptrblck | inception_v3 expects a color image (3 channels).
The error message seems to be a bit strange and should be:
RuntimeError: Given groups=1, weight of size [32, 3, 3, 3], expected input[10, 1, 299, 299] to have 3 channels, but got 1 channels instead
Did you modify the architecture somehow?
Anyway, … |
isalirezag | can i set step size like step_size= [30,100,500] to specify in what epochs change the lr? | ptrblck | For multiple milestones you should use thelr_scheduler.MultiStepLR. |
hughperkins | Looks like nonzero on a 2d tensor will return the coordinates of the non-zero elements? Is there a function which can take these coordinates, and a list of values, and recreate the original tensor? | ptrblck | You could use the following code:
x = torch.empty(5, 5).random_(3)
idx = x.nonzero()
y = torch.zeros(5, 5)
y[idx[:,0], idx[:,1]] = x[idx[:, 0], idx[:, 1]]
print((x==y).all())
I’m not sure, ifthis issuewas already solved, as x[x.nonzero()] seems not to be supported at the moment. |
ptrblck | Let’s focus first on the training folder and use the same approach to test and eval, if possible.So in your training folder you have 6 different action folders, which represent different classes.For example, boxing would be class0, and jogging class1.In each of these “action (class) folders” you have 25 subfolders with... | ptrblck | Assuming your folder structure looks like this:
root/
- boxing/
-person0/
-image00.png
-image01.png
- ...
-person1
- image00.png
- image01.png
- ...
- jogging
-person0/
-image00.png
… |
thyr | This is probably a very basic question but i’m having a hard time finding a solution.Suppose I have a tensor of size 100 * 5 * 3 (batch_size * seq_len * distinct_class_probs)I need to index dim=2 (distinct_class_probs) with a tensor.So I want something like in each batch, for each token in a sequence, return the probab... | ptrblck | I think gather is what you are looking for:
x = torch.randn(10, 5, 3)
index = torch.empty(10, 5, 1, dtype=torch.long).random_(3)
x.gather(2, index) |
Wei_Chen | Hi, I am trying to do train-test split for the dataset. I find that there is a built-inSubsetRandomSamplerwhich does the job. Does anyone know what is the difference between this one with the train-test split functionsklearn.model_selection.train_test_splitprovided in sklearn?Thanks! | ptrblck | The SubsetRandomSampler samples randomly from a list of indices.
As it won’t create these indices internally, you might want to use something like train_test_split to create the training, eval and test indices and then pass them to the SubsetRandomSampler. |
NAVEEN_PALURU | How can I load rotated mnist dataset (https://github.com/ChaitanyaBaweja/RotNIST/tree/master/data) using pytorch ? | ptrblck | Themain.pyseems to show how to load the data. Probably you could adapt the code to load the data first and then wrap it in a Dataset. TheData Loading tutorialmight help you to implement an own Dataset.
Note that in a vanilla classification use case PyTorch expects a target filled with class ind… |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.