instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Add sum of squares of model parameters to loss function
Adding sum of squares of model weights is known to be a regularization method that prevents overfitting of the deep learning models. Currently I have this loss function for my model which is implemented in pytorch: lossfunc = nn.NLLLoss(ignore_index=0) Then, I compute the loss during training as follows: ... loss = lossfunc(out_perm, dec_pp[:,1:]) I want the regularized loss to look like: loss = lossfunc(out_perm, dec_pp[:,1:])+sum_square_wights(enc)+sum_square_wights(dec) But don't know how to implement sum_square_wights function. Any help will be appreciated.
I believe you are referring to L2 regularization. If that is indeed the case, L2 regularization is already added to optimizer in torch (SGD, Adam etc) and you can control it using a non-zero value for weight_decay in optimizer's parameter. As for as L1 regularization is concerned, something like this should do the job: l1_criterion = nn.L1Loss(size_average=False) l1_reg_loss = 0 for param in model.parameters(): l1_reg_loss += l1_criterion (param) lambda = 0.0005 loss += lambda * l1_reg_loss
https://stackoverflow.com/questions/57457437/
Faster-RCNN Pytorch problem at prediction time with image dimensions
I am finetuning Faster-RCNN using PyTorch according to this tutorial: https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html The results are pretty good but making predictions only work when feeding a single tensor to the model. For example: # This works well >>> img, _ = dataset_test[3] >>> img.shape torch.Size([3, 1200, 1600]) >>> model.eval() >>> with torch.no_grad(): .. preds = model([img.to(device)]) But when I feed multiple tensors at once I get that error: >>> random_idx = torch.randint(high=50, size=(4,)) >>> images = torch.stack([dataset_test[idx][0] for idx in random_idx]) >>> images.shape torch.Size([4, 3, 1200, 1600]) >>> with torch.no_grad(): .. preds = model(images.to(device)) RuntimeError Traceback (most recent call last) <ipython-input-101-52caf8fee7a4> in <module>() 5 model.eval() 6 with torch.no_grad(): ----> 7 prediction = model(images.to(device)) ... RuntimeError: The expanded size of the tensor (1600) must match the existing size (1066) at non-singleton dimension 2. Target sizes: [3, 1200, 1600]. Tensor sizes: [3, 800, 1066] Edit Works when feeding a list of 3D tensors (IMO this behaviour is a bit weird, I cannot understand why it is not working with a 4D tensor): >>> random_idx = torch.randint(high=50, size=(4,)) >>> images = [dataset_test[idx][0].to(device) for idx in random_idx] >>> images.shape torch.Size([4, 3, 1200, 1600]) >>> with torch.no_grad(): .. preds = model(images)
MaskRCNN expects a list of tensors as 'input images' and a list of dictionaries as 'target' during training mode. This particular design choice is due to the fact that each image can have variable number of objects, i.e. target tensor of each image will be of variable dimensions, hence we are forced to use a list instead of a batch tensor of targets. However, it is still not entirely necessary to use a list of image tensors instead of using a batch tensor. My guess is that they have gone with a list of tensors for images as well, for the sake of consistency. Also, this gives an added advantage of being able able to use images of variable sizes as input rather than a fixed size. Due to this particular design choice, the model expects a list of tensors as input during evaluation mode as well. As for as the speed performance of the model is concerned, this design choice might have some negative impact during evaluation, but I can not say with hundred percent conviction. However, during training, since we have variable dimension of target tensors for each image, we are forced to iterate over all images one by one for loss calculation. So, there would be no speed gain of using a batch tensor of images over a list of image tensors during training.
https://stackoverflow.com/questions/57457631/
Adding batch normalization decreases the performance
I'm using PyTorch to implement a classification network for skeleton-based action recognition. The model consists of three convolutional layers and two fully connected layers. This base model gave me an accuracy of around 70% in the NTU-RGB+D dataset. I wanted to learn more about batch normalization, so I added a batch normalization for all the layers except for the last one. To my surprise, the evaluation accuracy dropped to 60% rather than increasing But the training accuracy has increased from 80% to 90%. Can anyone say what am I doing wrong? or Adding batch normalization need not increase the accuracy? The model with batch normalization class BaseModelV0p2(nn.Module): def __init__(self, num_person, num_joint, num_class, num_coords): super().__init__() self.name = 'BaseModelV0p2' self.num_person = num_person self.num_joint = num_joint self.num_class = num_class self.channels = num_coords self.out_channel = [32, 64, 128] self.loss = loss self.metric = metric self.bn_momentum = 0.01 self.bn_cv1 = nn.BatchNorm2d(self.out_channel[0], momentum=self.bn_momentum) self.conv1 = nn.Sequential(nn.Conv2d(in_channels=self.channels, out_channels=self.out_channel[0], kernel_size=3, stride=1, padding=1), self.bn_cv1, nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2)) self.bn_cv2 = nn.BatchNorm2d(self.out_channel[1], momentum=self.bn_momentum) self.conv2 = nn.Sequential(nn.Conv2d(in_channels=self.out_channel[0], out_channels=self.out_channel[1], kernel_size=3, stride=1, padding=1), self.bn_cv2, nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2)) self.bn_cv3 = nn.BatchNorm2d(self.out_channel[2], momentum=self.bn_momentum) self.conv3 = nn.Sequential(nn.Conv2d(in_channels=self.out_channel[1], out_channels=self.out_channel[2], kernel_size=3, stride=1, padding=1), self.bn_cv3, nn.ReLU(), nn.MaxPool2d(kernel_size=2, stride=2)) self.bn_fc1 = nn.BatchNorm1d(256 * 2, momentum=self.bn_momentum) self.fc1 = nn.Sequential(nn.Linear(self.out_channel[2]*8*3, 256*2), self.bn_fc1, nn.ReLU(), nn.Dropout2d(p=0.5)) # TO check self.fc2 = nn.Sequential(nn.Linear(256*2, self.num_class)) def forward(self, input): list_bn_layers = [self.bn_fc1, self.bn_cv3, self.bn_cv2, self.bn_cv1] # set the momentum of the batch norm layers to given momentum value during trianing and 0 during evaluation # ref: https://discuss.pytorch.org/t/model-eval-gives-incorrect-loss-for-model-with-batchnorm-layers/7561 # ref: https://github.com/pytorch/pytorch/issues/4741 for bn_layer in list_bn_layers: if self.training: bn_layer.momentum = self.bn_momentum else: bn_layer.momentum = 0 logits = [] for i in range(self.num_person): out = self.conv1(input[:, :, :, :, i]) out = self.conv2(out) out = self.conv3(out) logits.append(out) out = torch.max(logits[0], logits[1]) out = out.view(out.size(0), -1) out = self.fc1(out) out = self.fc2(out) t = out assert not ((t != t).any()) # find out nan in tensor assert not (t.abs().sum() == 0) # find out 0 tensor return out
My interpretation of the phenomenon you are observing,, is that instead of reducing the covariance shift, which is what the Batch Normalization is meant for, you are increasing it. In other words, instead of decrease the distribution differences between train and test, you are increasing it and that's what it is causing you to have a bigger difference in the accuracies between train and test. Batch Normalization does not assure better performance always, but for some problems it doesn't work well. I have several ideas that could lead to an improvement: Increase the batch size if it is small, what would help the mean and std calculated in the Batch Norm layers to be more robust estimates of the population parameters. Decrease the bn_momentum parameter a bit, to see if that also stabilizes the Batch Norm parameters. I am not sure you should set bn_momentum to zero when test, I think you should just call model.train() when you want to train and model.eval() when you want to use your trained model to perform inference. You could alternatively try Layer Normalization instead of Batch Normalization, cause it does not require accumulating any statistic and usually works well Try regularizing a bit your model using dropout Make sure you shuffle your training set in every epoch. Not shuffling the data set may lead to correlated batches that make the statistics in batch normalization cycle. That may impact your generalization I hope any of these ideas work for you
https://stackoverflow.com/questions/57457817/
Backward algorithm Hidden Markov Model, 0th index (termination step) yields wrong result
I'm implementing a backward HMM algorithm in PyTorch. I used this link as reference. This link contains the results of the numerical example used (I am attempting to implement that and compare my generated results to it). Page 3, section 2. Backward probability, there is a table containing the calculated results. Here is my code: # Initial Transition matrix as shown in page 2 of above link A = np.array([[0.6, 0.4], [0.3, 0.7]]) A = torch.from_numpy(A) # Initial State Probability (page 2) pi = np.array([0.8, 0.2]) pi = torch.from_numpy(pi) # Output probabilities (page 2) emission_matrix = np.array([[0.3, 0.4, 0.3, 0.3], [0.4, 0.3, 0.3, 0.3]]) emission_matrix = torch.from_numpy(emission_matrix) # Initialize empty 2x4 matrix (dimensions of emission matrix) backward = torch.zeros(emission_matrix.shape, dtype=torch.float64) # Backward algorithm def _backward(emission_matrix): # Initialization: A(i, j) * B(T, i) * B(Ot+1, j) , where B(Ot+1, j) = 1 backward[:, -1] = torch.matmul(A, emission_matrix[:, -1]) # I reversed the emission matrix so as to start from the last column rev_emission_mat = torch.flip(emission_matrix[:, :-1], [1]) # I transposed the reversed emission matrix such that each iterable in the for # loop is the observation sequence probability T_rev_emission_mat = torch.transpose(rev_emission_mat, 1, 0) # This step is so that I assign a reverse index enumeration to each iterable in the # emission matrix starts from time T to 0, rather than the opposite zipped_cols = list(zip(range(len(T_rev_emission_mat)-1, -1, -1), T_rev_emission_mat)) for i, obs_prob in zipped_cols: # Induction: Σ A(i, j) * B(j)(Ot+1) * β(t+1, j) if i != 0: backward[:, i] = torch.matmul(A * obs_prob, backward[:, i+1]) # Termination: Σ π(i) * bi * β(1, i) backward[:, 0] = torch.matmul(pi * obs_prob, backward[:, 1]) # run backward algorithm _backward(emission_matrix) # check results, backward is an all zero matrix that was initialized above print(backward) >>> tensor([[0.0102, 0.0324, 0.0900, 0.3000], [0.0102, 0.0297, 0.0900, 0.3000]], dtype=torch.float64) As you can see, the 0-th index does not match the result in page 3 of the previous link. What did I do wrong? If there is anything I can clarify, please let me know. Thanks in advance!
backward[:, 0] = pi * obs_prob * backward[:, 1]
https://stackoverflow.com/questions/57466547/
Reshaping Image for PyTorch
I used to use keras and the image format it followed is [Height x Width x Channels x Samples]. i decided to switch to PyTorch. But i didn’t switch out my data loading schemes. So now i have numpy arrays of shape HxWxCxS, instead of SxCxHxW which is required for PyTorch. Does anyone have any idea to convert this ?
First, Keras format is (samples, height, width, channels). All you need to do is a moved = numpy.moveaxis(data, -1,1) If by luck you were using the non-default config "channels_first", then the config is identical to that of PyTorch, which is (samples, channels, height, width). And when transforming to torch: data = torch.from_numpy(moved)
https://stackoverflow.com/questions/57467707/
Could I use BERT to Cluster phrases with pre-trained model
I found it was a failure that I had used Gensim with GoogleNews pre-trained model to cluster phrases like: knitting knit loom loom knitting weaving loom rainbow loom home decoration accessories loom knit/knitting loom ... I am advised that GoogleNews model does't have the phrases in it. The phrases I have are a little specific to GoogleNews model while I don't have corpus to train a new model. I have only the phrases. And now I am considering to turn to BERT. But could BERT do that as I expected as above? Thank you.
You can feed a phrase into the pretrained BERT model and get an embedding, i.e. a fixed-dimension vector. So BERT can embed your phrases in a space. Then you can use a clustering algorithm (such as k-means) to cluster the phrases. The phrases do not need to occur in the training corpus of BERT, as long as the words they consist of are in the vocabulary. You will have to try to see if the embeddings give you relevant results.
https://stackoverflow.com/questions/57475889/
Model() got multiple values for argument 'nr_class' - SpaCy multi-classification model (BERT integration)
Hi I am working on implementing a multi-classification model (5 classes) with the new SpaCy Model en_pytt_bertbaseuncased_lg. The code for the new pipe is here: nlp = spacy.load('en_pytt_bertbaseuncased_lg') textcat = nlp.create_pipe( 'pytt_textcat', config={ "nr_class":5, "exclusive_classes": True, } ) nlp.add_pipe(textcat, last = True) textcat.add_label("class1") textcat.add_label("class2") textcat.add_label("class3") textcat.add_label("class4") textcat.add_label("class5") The code for the training is as follows and is based on the example from here(https://pypi.org/project/spacy-pytorch-transformers/): def extract_cat(x): for key in x.keys(): if x[key]: return key # get names of other pipes to disable them during training n_iter = 250 # number of epochs train_data = list(zip(train_texts, [{"cats": cats} for cats in train_cats])) dev_cats_single = [extract_cat(x) for x in dev_cats] train_cats_single = [extract_cat(x) for x in train_cats] cats = list(set(train_cats_single)) recall = {} for c in cats: if c is not None: recall['dev_'+c] = [] recall['train_'+c] = [] optimizer = nlp.resume_training() batch_sizes = compounding(1.0, round(len(train_texts)/2), 1.001) for i in range(n_iter): random.shuffle(train_data) losses = {} batches = minibatch(train_data, size=batch_sizes) for batch in batches: texts, annotations = zip(*batch) nlp.update(texts, annotations, sgd=optimizer, drop=0.2, losses=losses) print(i, losses) So the structure of my data looks like this: [('TEXT TEXT TEXT', {'cats': {'class1': False, 'class2': False, 'class3': False, 'class4': True, 'class5': False}}), ... ] I am not sure why I get the following error: TypeError Traceback (most recent call last) <ipython-input-32-1588a4eadc8d> in <module> 21 22 ---> 23 optimizer = nlp.resume_training() 24 batch_sizes = compounding(1.0, round(len(train_texts)/2), 1.001) 25 TypeError: Model() got multiple values for argument 'nr_class' EDIT: if I take out the nr_class argument, I get this error here: ValueError: operands could not be broadcast together with shapes (1,2) (1,5) I actually thought this would happen because I didn't specify the nr_class argument. Is that correct?
This is a regression in the most recent version we released of spacy-pytorch-transformers. Sorry about this! The root cause is, this is another case of the evils of **kwargs. I'm looking forward to refining the spaCy API to prevent these issues in future. You can see the offending line here: https://github.com/explosion/spacy-pytorch-transformers/blob/c1def95e1df783c69bff9bc8b40b5461800e9231/spacy_pytorch_transformers/pipeline/textcat.py#L71 . We provide the nr_class positional argument, which overlaps with the explicit argument you passed in during the config. In order to workaround the problem, you can simply remove the nr_class key from your the config dict you're passing into spacy.create_pipe().
https://stackoverflow.com/questions/57476279/
SpaCy - ValueError: operands could not be broadcast together with shapes (1,2) (1,5)
In relation to the previous post on stackoverflow Model() got multiple values for argument 'nr_class' - SpaCy multi-classification model (BERT integration) in which my problem partialy have beed resolved I wanted to share the issue which comes up after implementing the solution. if I take out the nr_class argument, I get this error here: ValueError: operands could not be broadcast together with shapes (1,2) (1,5) I actually thought this would happen because I didn't specify the nr_class argument. Is this correct? one more time my code for the multi-class model: nlp = spacy.load('en_pytt_bertbaseuncased_lg') textcat = nlp.create_pipe( 'pytt_textcat', config={ "nr_class":5, "exclusive_classes": True, } ) nlp.add_pipe(textcat, last = True) textcat.add_label("class1") textcat.add_label("class2") textcat.add_label("class3") textcat.add_label("class4") textcat.add_label("class5") The code for the training is as follows and is based on the example from here(https://pypi.org/project/spacy-pytorch-transformers/): def extract_cat(x): for key in x.keys(): if x[key]: return key # get names of other pipes to disable them during training n_iter = 250 # number of epochs train_data = list(zip(train_texts, [{"cats": cats} for cats in train_cats])) dev_cats_single = [extract_cat(x) for x in dev_cats] train_cats_single = [extract_cat(x) for x in train_cats] cats = list(set(train_cats_single)) recall = {} for c in cats: if c is not None: recall['dev_'+c] = [] recall['train_'+c] = [] optimizer = nlp.resume_training() batch_sizes = compounding(1.0, round(len(train_texts)/2), 1.001) for i in range(n_iter): random.shuffle(train_data) losses = {} batches = minibatch(train_data, size=batch_sizes) for batch in batches: texts, annotations = zip(*batch) nlp.update(texts, annotations, sgd=optimizer, drop=0.2, losses=losses) print(i, losses) So the structure of my data looks like this: [('TEXT TEXT TEXT', {'cats': {'class1': False, 'class2': False, 'class3': False, 'class4': True, 'class5': False}}), ... ]
As @Milla Well already commented the answer can be found here (the bug fix on github from @syllogism_)
https://stackoverflow.com/questions/57490832/
Pytorch Train & Eval Different Sample Sizes
I am learning pytorch, and have the following (abbreviated) code to setup for modeling: # define the model class for a neural net with 1 hidden layer class myNN(nn.Module): def __init__(self, D_in, H, D_out): super(myNN, self).__init__() self.lin1 = nn.Linear(D_in,H) self.lin2 = nn.Linear(H,D_out) def forward(self,X): return torch.sigmoid(self.lin2(torch.sigmoid(self.lin1(x)))) # now make the datasets & dataloaders batchSize = 5 # Create the data class class Data(Dataset): def __init__(self, x, y): self.x = torch.FloatTensor(x) self.y = torch.Tensor(y.astype(int)) self.len = self.x.shape[0] self.p = self.x.shape[1] def __getitem__(self, index): return self.x[index], self.y[index] def __len__(self): return self.len trainData = Data(trnX, trnY) trainLoad = DataLoader(dataset = trainData, batch_size = batchSize) testData = Data(tstX, tstY) testLoad = DataLoader(dataset = testData, batch_size = len(testData)) # define the modeling objects hiddenLayers = 30 learningRate = 0.1 model = myNN(p,hiddenLayers,1) print(model) optimizer = torch.optim.SGD(model.parameters(), lr = learningRate) loss = nn.BCELoss() with trnX.shape=(70, 2), trnY.shape=(70,), tstX.shape=(30,2), and tstY.shape=(30,). The code for training is: # train! epochs = 1000 talkFreq = 0.2 trnLoss = [np.inf]*epochs tstLoss = [np.inf]*epochs for i in range(epochs): # train with minibatch gradient descent for x, y in trainLoad: # forward step yhat = model(x) # compute loss (not storing for now, will do after minibatching) l = loss(yhat, y) # backward step optimizer.zero_grad() l.backward() optimizer.step() # evaluate loss on training set yhat = model(trainData.x) trnLoss[i] = loss(yhat, trainData.y) # evaluate loss on testing set yhat = model(testData.x) tstLoss[i] = loss(yhat, testData.y) The datasets trainData and testData have 70 and 30 observations, respectively. This is probably just a newbie problem, but when I run the training cell, it errors on the trnLoss[i] = loss(yhat, trainData.y) line with the error ValueError: Target and input must have the same number of elements. target nelement (70) != input nelement (5) When I inspect the output of the yhat=model(trainData.x) line, I see that yhat is a tensor with batchSize elements, despite the fact that trainData.x.shape = torch.Size([70, 2]). How can I iteratively train the model with the minibatch gradient descent, then use the model to compute the loss & accuracy on the full training & testing sets? I tried setting model.train() just before the mini batch iteration, then model.eval() just before the evaluation code, to no avail.
In myNN.forward(), you are passing lower case x as input to self.lin1 while input parameter to the function is named as capital case X. Small case x is kind of global variable defined at for loop for trainload hence you are not getting any syntax error, but the value that you intend to pass is not being passed to self.lin1. Might I also suggest that you should consider using model.eval() and with torch.no_grad() for your testing code. It is not absolutely necessary here but it will make more sense.
https://stackoverflow.com/questions/57490945/
Can't install pytorch with pip on Windows
I'm trying to install Pytorch with Windows and I'm using the commands of the official site https://pytorch.org/get-started/locally/ pip3 install torch==1.2.0 torchvision==0.4.0 -f https://download.pytorch.org/whl/torch_stable.html This is the command if I choose Windows, Cuda 10.0, and Python 3.7 But if I run this I get the error message: ERROR: Could not find a version that satisfies the requirement torch==1.2.0 (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2) ERROR: No matching distribution found for torch==1.2.0 So why does this happen? My pip is version 19.2 and I am in a newly installed python 3.7 environment
The most likely reason for Your issue is a 32-bit installation of python, while the torch libraries rely on having a 64-bit version. I had exactly the same issue. Just start python from command line and observe C:\Users\marci>python Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32 My installation now shows 64 bits. If Yours shows 32, then install 64-bit python. I used this link: Official python 64-bit Windows installer
https://stackoverflow.com/questions/57499002/
Getting error while trying to plot ROC for multiclass classification
I am trying to plot ROC Curve for multiclass classification.I followed https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html. I used the below code to calculate y_test,and y_score def test_epoch(net,test_loader): y_test =[] y_score =[] with torch.no_grad(): for batch in test_loader: images, labels = batch['image'], batch['grade'] images =Variable(images) labels= Variable(labels) target =F.one_hot(labels,5) outputs = net(images) _, predicted = torch.max(outputs.data, 1) c = (predicted == labels).squeeze().numpy() y_score.append(outputs.numpy()) y_test.append(labels.numpy()) return y_test,y_score I seen that my y_test is array like below y_test data>> [array([[0, 0, 1, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 0, 0, 1, 0], [0, 0, 1, 0, 0], [1, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 1, 0, 0, 0] And y_score is like [array([[ 0.30480504, -0.12213976, 0.09632117, -0.16465648, -0.44081157],[ 0.21797988, -0.09650452, 0.07616544, -0.12001953, -0.34972644],[ 0.3230184 , -0.13098559, 0.10277118, -0.17656785, -0.45888817],[ 0.38143447, -0.15880316, 0.12123139, -0.21719441, -0.5281661 ],[ 0.3427343 , -0.13945231, 0.11076729, -0.19657779, -0.4913683 ] Whenever I called the function for plotting ROC curve def plot_roc(y_test, y_score, N_classes): """ compute ROC curve and ROC area for each class in each fold """ fpr = dict() tpr = dict() roc_auc = dict() for i in range(N_classes): fpr[i], tpr[i], _ = roc_curve(np.array(y_test[:, i]),np.array(y_score[:, i])) roc_auc[i] = auc(fpr[i], tpr[i]) # Compute micro-average ROC curve and ROC area fpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel()) roc_auc["micro"] = auc(fpr["micro"], tpr["micro"]) # Compute macro-average ROC curve and ROC area # First aggregate all false positive rates all_fpr = np.unique(np.concatenate([fpr[i] for i in range(N_classes)])) # Then interpolate all ROC curves at this points mean_tpr = np.zeros_like(all_fpr) for i in range(N_classes): mean_tpr += interp(all_fpr, fpr[i], tpr[i]) # Finally average it and compute AUC mean_tpr /= N_classes fpr["macro"] = all_fpr tpr["macro"] = mean_tpr roc_auc["macro"] = auc(fpr["macro"], tpr["macro"]) # Plot all ROC curves plt.figure() plt.plot(fpr["micro"], tpr["micro"], label='micro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["micro"]), color='deeppink', linestyle=':', linewidth=4) plt.plot(fpr["macro"], tpr["macro"], label='macro-average ROC curve (area = {0:0.2f})' ''.format(roc_auc["macro"]), color='navy', linestyle=':', linewidth=4) colors = cycle(['aqua', 'darkorange', 'cornflowerblue']) for i, color in zip(range(N_classes), colors): plt.plot(fpr[i], tpr[i], color=color, lw=2, label='ROC curve of class {0} (area = {1:0.2f})' ''.format(i, roc_auc[i])) plt.plot([0, 1], [0, 1], 'k--', lw=2) plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Some extension of Receiver operating characteristic to multi-class') plt.legend(loc="lower right") plt.show() I am getting this error massages, Traceback (most recent call last): File "/home/Downloads/demo 3.py", line 405, in <module> plot_roc(y_test, y_score, 5) File "/home/Downloads/demo 3.py", line 225, in plot_roc fpr[i], tpr[i], _ = roc_curve(np.array(y_test[:, i]),np.array(y_score[:, i])) TypeError: list indices must be integers or slices, not tuple I could not understand how I will solve this problem. I am highly appreciate any kind of help regarding this issue.
In your code you have a previously defined variable (a list) called roc_curve, and this shadows the scikit-learn function sklearn.metrics.roc_curve in your code, you should prefer not to name variables the same as a well known function, in order to prevent problems like these.
https://stackoverflow.com/questions/57499867/
How to get sentence embeddings from encoder in Fastai learner language model
I was able to fine tune a language model using fast ai. I would like to extract sentence embeddings from the fine-tuned model for sentence similarity. How do I get the encoder model embeddings? Also can embeddings be compared with dot product like other embeddings from other models such as USE? data_lm = TextLMDataBunch.from_df(train_df = se1, valid_df = se2, path = "",text_cols='text') learn = language_model_learner(data_lm,drop_mult=0.7,pretrained=True,arch=AWD_LSTM) learn.fit_one_cycle(3, 1e-01) My code is above how can I get encodings from learn?
This should give you the encoder(Which is an embedding layer) : learn.model[0].encoder
https://stackoverflow.com/questions/57500159/
Unable to figure out inplace operation in the pytorch code?
I have the following implementation in PyTorch for learning using LSTM: https://gist.github.com/rahulbhadani/f1d64042cc5a80280755cac262aa48aa However, the code is experiencing in-place operation error where my error output is: /home/ivory/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:10: UserWarning: To copy construct from a tensor, it is recommended to use sourceTensor.clone().detach() or sourceTensor.clone().detach().requires_grad_(True), rather than torch.tensor(sourceTensor). # Remove the CWD from sys.path while we load stuff. --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-86-560ec78f2b64> in <module> 27 linear = torch.nn.Linear(hidden_nums, output_dim) 28 ---> 29 global_loss_list = global_training(lstm2) <ipython-input-84-152890a3028c> in global_training(optimizee) 3 adam_global_optimizer = torch.optim.Adam([{'params': optimizee.parameters()}, 4 {'params':linear.parameters()}], lr = 0.0001) ----> 5 _, global_loss_1 = learn2(LSTM_Optimizee, training_steps, retain_graph_flag=True, reset_theta=True) 6 7 print(global_loss_1) <ipython-input-83-0357a528b94d> in learn2(optimizee, unroll_train_steps, retain_graph_flag, reset_theta) 43 # requires_grad=True. These are accumulated into x.grad for every 44 # parameter x. In pseudo-code: x.grad += dloss/dx ---> 45 loss.backward(retain_graph = retain_graph_flag) #The default is False, when the optimized LSTM is set to True 46 47 print('x.grad: {}'.format(x.grad)) ~/anaconda3/lib/python3.7/site-packages/torch/tensor.py in backward(self, gradient, retain_graph, create_graph) 116 products. Defaults to ``False``. 117 """ --> 118 torch.autograd.backward(self, gradient, retain_graph, create_graph) 119 120 def register_hook(self, hook): ~/anaconda3/lib/python3.7/site-packages/torch/autograd/__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables) 91 Variable._execution_engine.run_backward( 92 tensors, grad_tensors, retain_graph, create_graph, ---> 93 allow_unreachable=True) # allow_unreachable flag 94 95 RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [1, 10]] is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True). I have tried to trace the error but didn't succeed. Any help in this regard will be appreciated. Thanks.
I think the issue is with the following line: global_loss_list.append(global_loss.detach_()) The convention in PyTorch for in-place operations is using _ at the end of the function name (as in detach_). I believe you shouldn't be detaching in-place. In other words, change detach_ to detach
https://stackoverflow.com/questions/57500582/
How to take a transpose for each matrix in a batch in Pytorch?
Say I have a 4 batch of 5x3 matrixes. So the dimensions of these tensor are 4x5x3. How do I take the transpose of each matrix within each batch. So converting it to 4x3x5?
I will drop some benchmarks here for the sake of performance. Using the same tensor proposed in the OP's answer. In[2]: import torch In[3]: x = torch.randn(2, 3, 5) In[4]: x.size() Out[4]: torch.Size([2, 3, 5]) In[5]: %timeit x.permute(1, 0, 2) 1.03 µs ± 41.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In[6]: %timeit torch.transpose(x, 0, 1) 892 ns ± 9.61 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) In[7]: torch.transpose(x, 0, 1).equal(x.permute(1, 0, 2)) Out[7]: True It is clear that torch.transpose is faster, so It is advised to use it when possible.
https://stackoverflow.com/questions/57512113/
Can the coordinates of a 2 dimensional pytorch tensor be remapped?
I'm trying to remap a 2d image to new coordinates. Previously I was using OpenCV's cv.remap method. I'd like to use CUDA with compiling C directly. Is there a Pytorch version of remap that will interpolate values?
Are you looking for grid_sample? Look for make_grid function for additional information
https://stackoverflow.com/questions/57515064/
Does pytorch apply softmax automatically in nn.Linear
In pytorch a classification network model is defined as this, 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_hidden) # hidden layer self.out = torch.nn.Linear(n_hidden, n_output) # output layer def forward(self, x): x = F.relu(self.hidden(x)) # activation function for hidden layer x = self.out(x) return x Is softmax applied here? In my understanding, things should be like, 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_hidden) # hidden layer self.relu = torch.nn.ReLu(inplace=True) self.out = torch.nn.Linear(n_hidden, n_output) # output layer self.softmax = torch.nn.Softmax(dim=n_output) def forward(self, x): x = self.hidden(x) # activation function for hidden layer x = self.relu(x) x = self.out(x) x = self.softmax(x) return x I understand that F.relu(self.relu(x)) is also applying relu, but the first block of code doesn't apply softmax, right?
Latching on to what @jodag was already saying in his comment, and extending it a bit to form a full answer: No, PyTorch does not automatically apply softmax, and you can at any point apply torch.nn.Softmax() as you want. But, softmax has some issues with numerical stability, which we want to avoid as much as we can. One solution is to use log-softmax, but this tends to be slower than a direct computation. Especially when we are using Negative Log Likelihood as a loss function (in PyTorch, this is torch.nn.NLLLoss, we can utilize the fact that the derivative of (log-)softmax+NLLL is actually mathematically quite nice and simple, which is why it makes sense to combine the both into a single function/element. The result is then torch.nn.CrossEntropyLoss. Again, note that this only applies directly to the last layer of your network, any other computation is not affected by any of this.
https://stackoverflow.com/questions/57516027/
How can I do the centercrop of 3D volumes inside the network model with pytorch
In keras, there is Cropping3D layer for centercropping tensors of 3D volumnes inside the neural network. However, I failed to find out anything similar in pytorch, though they have torchvision.transforms.CenterCrop(size) for 2D images. How can I do the cropping inside the network? Otherwise I need to do it in preprocessing which is the last thing I want to do for specific reasons. Do I need to write a custom layer like slicing the input tensors along each axices? Hope to get some inspiration for this
In PyTorch you don't necessarily need to write layers for everything, often you can just do what you want directly during the forward pass. The basic rules you need to keep in mind when operating on torch tensors for which you will need to compute gradients are Don't convert torch tensors to other types for computation (e.g. use torch.sum instead of converting to numpy and using numpy.sum). Don't perform in-place operations (e.g. changing one element of a tensor or using inplace operators, so use x = x + ... instead of x += ...). That said, you can just use slicing, maybe it would look something like this def forward(self, x): ... x = self.conv3(x) x = x[:, :, 5:20, 5:20] # crop out part of the feature map x = self.relu3(x) ...
https://stackoverflow.com/questions/57517121/
How to perform element-wise product in PyTorch?
I have two torch tensors a and b. Tensor a has the shape of [batch_size, emb_size] and Tensor b has the shape of [num_of_words, emb_size]. I want to do the element-wise product on these two tensors instead of dot product. I noticed that "*" can perform element-wise product but it doesn't fit my case. For example, batch_size = 3, emb_size = 2, num_of_words = 5. a = torch.rand((3,2)) b = torch.rand((5,2)) I want to get something like: torch.cat([a[0]*b, a[1]*b, a[2]*b]).view(3, 5, 2) but I want to do this in an efficient and elegant way.
You can use a.unsqueeze(1) * b PyTorch supports broadcasting semantics but you need to make sure the singleton dimensions are in the correct locations.
https://stackoverflow.com/questions/57518866/
Libtorch: cannot load traced lstm scriptmodel
I save a pytorch ScriptModule and load it using libtorch. However I encountered the following problem I use linux subsystem under win10 and I use pytorch 1.2. To reproduce my problem, you could run this piece of python code to save a pt model import torch import torch.nn as nn # TODO: https://github.com/pytorch/pytorch/issues/23930 class test(torch.jit.ScriptModule): def __init__(self, vocab_size=10, rnn_dims=512): super().__init__() self.word_embeds = nn.Embedding(vocab_size, rnn_dims) self.emb_drop = nn.Dropout(0.1) self.rnn = nn.LSTM(input_size=rnn_dims, hidden_size=rnn_dims, batch_first=True, num_layers=2, dropout=0.1) # delattr(self.rnn, 'forward_packed') @torch.jit.script_method def forward(self, x): h1 = (torch.zeros(2, 1, 512), torch.zeros(2, 1, 512)) embeds = self.emb_drop(self.word_embeds(x)) out, h1 = self.rnn(embeds, h1) return h1 model = test() input = torch.ones((1,3)).long() output = model(input) print('output', output) # torch.onnx.export(model, # model being run # input, # 'test.onnx', # example_outputs=output) #torch.jit.trace(model, (torch.ones((1,3)).long(), torch.ones((3,1))), check_trace=False) model.save('lstm_test.pt') Then load the model in libtorch. I don't know why I have this error. I don't use PackedSequence at all. Hope some could help me out.
I know what's wrong now. The libtorch version is of wrong version on the official website. It's ok now when I use the correct libtorch 1.2. Refer to issue https://github.com/pytorch/pytorch/issues/24382
https://stackoverflow.com/questions/57525456/
Concatenation step of U-Net for unequal number of channels
I am trying to implement the U-NET architecture for image segmentation while implementing the crop and concatenation step in the expansive path, I am unable to understand how the unequal number of channels are concatenated. According to the architecture, the input from the first upsampling step has to be concatenated from the corresponding output from contracting path but the problem is number of channels in contracting path is 512 while after upsampling step they are 1024, how they are supposed to be concatenated.My code for the crop and concatenate is - def crop_and_concat(self, upsampled, bypass, crop=False): if crop: c = (bypass.size()[2] - upsampled.size()[2]) // 2 bypass = F.pad(bypass, (-c, -c, -c, -c)) return torch.cat((upsampled, bypass), 1) The error I am receiving- RuntimeError: Given groups=1, weight of size 128 256 5 5, expected input[4, 384, 64, 64] to have 256 channels, but got 384 channels instead Where I am doing wrong?
First of all, you don't have to be so strict when it comes to U-Net like architectures, there were many derivatives afterwards (see for example fastai variation with PixelShuffle). In the case of encoder, in the basic version, your channels go (per block): 1 - 64 - 128 - 256 - 512 Standard convolutional encoder. After that is a shared layer of 1024. In decoder, it goes downwards, but has more channels as you are concatenating encoder states from each block. It would be: 1024 -> 512 -> 512 (decoder) + 512 (encoder), 1024 total -> 512 512 -> 256 -> 256 (decoder) + 256 (encoder), 512 total -> 256 and so on. You were at the case where 256 from decoder was taken in the account, but 128 added from encoder wasn't. Just up your channels to 256 + 128 and follow the above scheme for each block of your UNet.
https://stackoverflow.com/questions/57530038/
How do they know mean and std, the input value of transforms.Normalize
The question is about the data loading tutorial from the PyTorch website. I don't know how they write the value of mean_pix and std_pix of the in transforms.Normalize without calculation I'm unable to find any explanation relevant to this question on StackOverflow. import torch from torchvision import transforms, datasets data_transform = transforms.Compose([ transforms.RandomSizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) hymenoptera_dataset = datasets.ImageFolder(root='hymenoptera_data/train', transform=data_transform) dataset_loader = torch.utils.data.DataLoader(hymenoptera_dataset, batch_size=4, shuffle=True, num_workers=4) The value mean=[0.485,0.456, 0.406] and std=[0.229, 0.224, 0.225] is not obvious to me. How do they get them? And why are they equal to these?
For normalization input[channel] = (input[channel] - mean[channel]) / std[channel], the mean and standard deviation values are to be taken from the training dataset. Here, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] are the mean and std of Imagenet dataset. On Imagenet, we’ve done a pass on the dataset and calculated per-channel mean/std. check here The pre-trained models available in torchvision for transfer learning were pretrained on Imagenet, so using its mean and std deviation would be fine for fine-tuning your model. If you're trying to train your model from scratch, it would be better to use the mean and std deviation of your training dataset (face dataset in this case). Other than that, in most of the cases, the mean and std of Imagenet suffice for your problem.
https://stackoverflow.com/questions/57532661/
How To Fix: RuntimeError: size mismatch in pyTorch
I am new to pyTorch and getting following Size Mismatch error: RuntimeError: size mismatch, m1: [7 x 2092500], m2: [180 x 120] at ..\aten\src\TH/generic/THTensorMath.cpp:961 Model: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 200, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(200, 180, 5) self.fc1 = nn.Linear(180, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84,5) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x How ever I tried changing x = x.view(x.shape[0], -1) to x = x.view(x.size(0), -1) but that also did'nt work. Dimension of images is 512x384. and have used following transformation: def load_dataset(): data_path = './dataset/training' transform = transforms.Compose( [transforms.Resize((512,384)), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) train_dataset = torchvision.datasets.ImageFolder(root=data_path,transform=transform) train_loader = torch.utils.data.DataLoader(train_dataset,batch_size=7,num_workers=0,shuffle=True) return train_loader
The problem is that the dimensions of the output of your last max pooling layer don't match the input of the first fully connected layer. This is the network structure until the last max pool layer for input shape (3, 512, 384): ---------------------------------------------------------------- Layer (type) Output Shape Param # ================================================================ Conv2d-1 [-1, 200, 508, 380] 15,200 MaxPool2d-2 [-1, 200, 254, 190] 0 Conv2d-3 [-1, 180, 250, 186] 900,180 MaxPool2d-4 [-1, 180, 125, 93] 0 ================================================================ The last row of the table means that MaxPool2d-4 outputs 180 channels (filter outputs) of 125 width and 93 height. So you need your first fully connected layer to have 180 * 125 * 93 = 2092500 input size. This is a lot, so I'd advise you to refine your architecture. In any case, if you change the input size of the first fully connected layer to 2092500, it works: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(3, 200, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(200, 180, 5) #self.fc1 = nn.Linear(180, 120) self.fc1 = nn.Linear(2092500, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84,5) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(x.shape[0], -1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x Giving the following architecture: ---------------------------------------------------------------- Layer (type) Output Shape Param # ================================================================ Conv2d-1 [-1, 200, 508, 380] 15,200 MaxPool2d-2 [-1, 200, 254, 190] 0 Conv2d-3 [-1, 180, 250, 186] 900,180 MaxPool2d-4 [-1, 180, 125, 93] 0 Linear-5 [-1, 120] 251,100,120 Linear-6 [-1, 84] 10,164 Linear-7 [-1, 5] 425 ================================================================ Total params: 252,026,089 Trainable params: 252,026,089 Non-trainable params: 0 (You can use the torchsummary package to generate these tables.)
https://stackoverflow.com/questions/57534072/
Augmenting only the training set in K-folds cross validation
I am trying to create a binary CNN classifier for an unbalanced dataset (class 0 = 4000 images, class 1 = around 250 images), which I want to perform 5-fold cross validation on. Currently I am loading my training set into an ImageLoader that applies my transformations/augmentations(?) and loads it into a DataLoader. However, this results in both my training splits and validation splits containing the augmented data. I originally applied transformations offline (offline augmentation?) to balance my dataset, but from this thread (https://stats.stackexchange.com/questions/175504/how-to-do-data-augmentation-and-train-validate-split), it seems it would be ideal to only augment the training set. I would also prefer to train my model on solely augmented training data and then validate it on non-augmented data in a 5-fold cross validation My data is organized as root/label/images, where there are 2 label folders (0 and 1) and images sorted into the respective labels. My Code So Far total_set = datasets.ImageFolder(ROOT, transform = data_transforms['my_transforms']) //Eventually I plan to run cross-validation as such: splits = KFold(cv = 5, shuffle = True, random_state = 42) for train_idx, valid_idx in splits.split(total_set): train_sampler = SubsetRandomSampler(train_idx) valid_sampler = SubsetRandomSampler(valid_idx) train_loader = torch.utils.data.DataLoader(total_set, batch_size=32, sampler=train_sampler) val_loader = torch.utils.data.DataLoader(total_set, batch_size=32, sampler=valid_sampler) model.train() //Model train/eval works but may be overpredict I'm sure I'm doing something sub-optimally or wrong in this code, but I can't seem to find any documentation on specifically augmenting only the training splits in cross-validation! Any help would be appreciated!
One approach is to implement a wrapper Dataset class that applies transforms to the output of your ImageFolder dataset. For example class WrapperDataset: def __init__(self, dataset, transform=None, target_transform=None): self.dataset = dataset self.transform = transform self.target_transform = target_transform def __getitem__(self, index): image, label = self.dataset[index] if self.transform is not None: image = self.transform(image) if self.target_transform is not None: label = self.target_transform(label) return image, label def __len__(self): return len(self.dataset) Then you could use this in your code by wrapping the larger dataset with different transforms. total_set = datasets.ImageFolder(ROOT) # Eventually I plan to run cross-validation as such: splits = KFold(cv = 5, shuffle = True, random_state = 42) for train_idx, valid_idx in splits.split(total_set): train_sampler = SubsetRandomSampler(train_idx) valid_sampler = SubsetRandomSampler(valid_idx) train_loader = torch.utils.data.DataLoader( WrapperDataset(total_set, transform=data_transforms['train_transforms']), batch_size=32, sampler=train_sampler) valid_loader = torch.utils.data.DataLoader( WrapperDataset(total_set, transform=data_transforms['valid_transforms']), batch_size=32, sampler=valid_sampler) # train/validate now I haven't tested this code since I don't have your full code/models but the concept should be clear.
https://stackoverflow.com/questions/57539567/
RuntimeError: Expected object of backend CUDA but got backend CPU for argument #3 'index'
I'm working with the project 'lda2vec-pytorch' on Google CoLab, runnin pytorch 1.1.0 https://github.com/TropComplique/lda2vec-pytorch device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") cuda:0 I'm getting an exception in the forward method adding 'noise' in my class negative_sampling_loss(nn.Module): noise = self.multinomial.draw(batch_size*window_size*self.num_sampled) noise = Variable(noise).view(batch_size, window_size*self.num_sampled) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") self.embedding = self.embedding.to(device) #print("negative_sampling_loss::forward() self.embedding", self.embedding.is_cuda) This line get's an error. # shape: [batch_size, window_size*num_sampled, embedding_dim] noise = self.embedding(noise) # Exception HERE Here's the stack trace: Traceback (most recent call last): File "train.py", line 36, in <module> main() File "train.py", line 32, in main save_every=20, grad_clip=5.0 File "../utils/training.py", line 138, in train neg_loss, dirichlet_loss = model(doc_indices, pivot_words, target_words) File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 493, in __call__ result = self.forward(*input, **kwargs) File "../utils/lda2vec_loss.py", line 82, in forward neg_loss = self.neg(pivot_words, target_words, doc_vectors, w) File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 493, in __call__ result = self.forward(*input, **kwargs) File "../utils/lda2vec_loss.py", line 167, in forward noise = self.embedding(noise) File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py", line 493, in __call__ result = self.forward(*input, **kwargs) File "/usr/local/lib/python3.6/dist-packages/torch/nn/modules/sparse.py", line 117, in forward self.norm_type, self.scale_grad_by_freq, self.sparse) File "/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py", line 1506, in embedding return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) RuntimeError: Expected object of backend CUDA but got backend CPU for argument #3 'index' Any ideas?
Variable noise is available on CPU while self.embedding is on GPU. We can send noise to GPU as well: noise = noise.to(device)
https://stackoverflow.com/questions/57539872/
Plotting predicted values causes error: 'Tensor' object has no attribute 'ndim'
How do I properly write the code to plot the predicted values in this linear regression model? I am using this tutorial to learn Linear regression:https://www.deeplearningwizard.com/deep_learning/practical_pytorch/pytorch_linear_regression/ I was able to successfully implement GPU. My issue is plotting the predicted values. I tried searching for solutions to learn how to keep the values as a tensor, but it seems that I don't have the syntactical knowledge to do this. Here is where I'll start epochs = 100 for epoch in range(epochs): epoch += 1 # Convert numpy array to torch Variable if torch.cuda.is_available(): inputs = (torch.from_numpy(x_train).cuda()) labels = (torch.from_numpy(y_train).cuda()) else: inputs = (torch.from_numpy(x_train)) labels = (torch.from_numpy(y_train)) # Clear gradients w.r.t. parameters optimizer.zero_grad() # Forward to get output outputs = model(inputs) # Calculate Loss loss = criterion(outputs, labels) # Getting gradients w.r.t. parameters loss.backward() # Updating parameters optimizer.step() # Logging print('epoch {}, loss {}'.format(epoch, loss.item())) Prediction is made here and I choose to use cuda predicted = model(Variable(torch.from_numpy(x_train).requires_grad_().cuda())) print("Predicted") print(predicted) print("Output") print(y_train) plt.clf() # Get predictions #predicted = model(Variable(torch.from_numpy(x_train).requires_grad_().cuda())) # Plot true data plt.plot(x_train, y_train, 'go', label='True data', alpha=0.5) The error is called here after it is unable to plot # Plot predictions plt.plot(x_train, predicted, '--', label='Predictions', alpha=0.5) # Legend and plot plt.legend(loc='best') plt.show() Error Given: Traceback (most recent call last): File "D:/Test with GPU/Linear regression.py", line 101, in <module> plt.plot(x_train, predicted, '--', label='Predictions', alpha=0.5) File "D:\Anaconda3\envs\gputest\lib\site-packages\matplotlib\pyplot.py", line 2795, in plot is not None else {}), **kwargs) File "D:\Anaconda3\envs\gputest\lib\site-packages\matplotlib\axes\_axes.py", line 1666, in plot lines = [*self._get_lines(*args, data=data, **kwargs)] File "D:\Anaconda3\envs\gputest\lib\site-packages\matplotlib\axes\_base.py", line 225, in __call__ yield from self._plot_args(this, kwargs) File "D:\Anaconda3\envs\gputest\lib\site-packages\matplotlib\axes\_base.py", line 391, in _plot_args x, y = self._xy_from_xy(x, y) File "D:\Anaconda3\envs\gputest\lib\site-packages\matplotlib\axes\_base.py", line 271, in _xy_from_xy if x.ndim > 2 or y.ndim > 2: AttributeError: 'Tensor' object has no attribute 'ndim'
plt.plot function expects its inputs to be numpy arrays, rather than torch.tensor. You can use .numpy() to view the internal data of the tensor as a numpy array. Try with torch.no_grad(): plt.plot(x_train, predicted.cpu().numpy(), '--', label='Predictions', alpha=0.5)
https://stackoverflow.com/questions/57541091/
Does torch.utils.tensorboard need installation of Tensorflow?
I'm new to pytorch and I wonder if using tensorboard on pytorch needs tensorflow as a dependency. Moreover, except for tensorboard, what are other options for training curve visualization?
Indeed tensorboard is part of tensorflow, but it does not depend on it. You can safely install only tensorboard (e.g, pip install tensorboard) or conda install -c conda-forge tensorboard) and use torch.utils.tensorboard.
https://stackoverflow.com/questions/57547471/
Filling torch tensor with zeros after certain index
Given a 3d tenzor, say: batch x sentence length x embedding dim a = torch.rand((10, 1000, 96)) and an array(or tensor) of actual lengths for each sentence lengths = torch .randint(1000,(10,)) outputs tensor([ 370., 502., 652., 859., 545., 964., 566., 576.,1000., 803.]) How to fill tensor ‘a’ with zeros after certain index along dimension 1 (sentence length) according to tensor ‘lengths’ ? I want smth like that : a[ : , lengths : , : ] = 0 One way of doing it (slow if batch size is big enough): for i_batch in range(10): a[ i_batch , lengths[i_batch ] : , : ] = 0
You can do it using a binary mask. Using lengths as column-indices to mask we indicate where each sequence ends (note that we make mask longer than a.size(1) to allow for sequences with full length). Using cumsum() we set all entries in mask after the seq len to 1. mask = torch.zeros(a.shape[0], a.shape[1] + 1, dtype=a.dtype, device=a.device) mask[(torch.arange(a.shape[0]), lengths)] = 1 mask = mask.cumsum(dim=1)[:, :-1] # remove the superfluous column a = a * (1. - mask[..., None]) # use mask to zero after each column For a.shape = (10, 5, 96), and lengths = [1, 2, 1, 1, 3, 0, 4, 4, 1, 3]. Assigning 1 to respective lengths at each row, mask looks like: mask = tensor([[0., 1., 0., 0., 0., 0.], [0., 0., 1., 0., 0., 0.], [0., 1., 0., 0., 0., 0.], [0., 1., 0., 0., 0., 0.], [0., 0., 0., 1., 0., 0.], [1., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 1., 0.], [0., 0., 0., 0., 1., 0.], [0., 1., 0., 0., 0., 0.], [0., 0., 0., 1., 0., 0.]]) After cumsum you get mask = tensor([[0., 1., 1., 1., 1.], [0., 0., 1., 1., 1.], [0., 1., 1., 1., 1.], [0., 1., 1., 1., 1.], [0., 0., 0., 1., 1.], [1., 1., 1., 1., 1.], [0., 0., 0., 0., 1.], [0., 0., 0., 0., 1.], [0., 1., 1., 1., 1.], [0., 0., 0., 1., 1.]]) Note that it exactly has zeros where the valid sequence entries are and ones beyond the lengths of the sequences. Taking 1 - mask gives you exactly what you want. Enjoy ;)
https://stackoverflow.com/questions/57548180/
Pytorch gradients has not calculated
I create a NN. I'm having a problem with recounting gradients. The problem is that I scalarly multiply 2 tensors u @ v and normalize one of them. It is important that gradients cannot be calculated for h. Therefore, I use detach(). In addition, during the recalculation of gradients, normalization should not be taken into account (I do not know how to do this). import torch from torch import nn class Nn(nn.Module): def __init__(self): super(Nn, self).__init__() self.ln = nn.Linear(5, 5) def forward(self, x): v = self.ln(x) u = v.clone() h = v.clone() u /= u.norm() h = h.detach() h /= h.norm() res = torch.stack([torch.stack([u @ h, u @ h])]) return res def patches_generator(): while True: decoder = torch.rand((5, )) target = torch.randint(2, (1,)) yield decoder, target net = Nn() criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(net.parameters()) net.train() torch.autograd.set_detect_anomaly(True) for decoder, targets in patches_generator(): optimizer.zero_grad() outputs = net(decoder) loss = criterion(outputs, targets) loss.backward() optimizer.step() As a result, I get the following error: RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [9, 512, 1, 1]], which is output 0 of ReluBackward1, is at version 3; expected version 2 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck!
The problem is the in-place division operator applied to u in this line: u /= u.norm() changing it to u = u / u.norm() makes the code run. The reason is that the in-place operator overwrites the intermediate result from this line u = v.clone() which makes it impossible for Pytorch to compute the gradient. (The error message in the question contains a reference to a ReluBackward1 layer which is not in the reduced code example. Pytorch ReLU layers have an optional in_place argument which makes the operation in place while supporting backprop. This often works, because in a sequential network there is no need to distinguish between the output of the ReLU activation and the output of the weights to compute the gradient, but in more complex architectures it might be necessary to retain the output of the weights.)
https://stackoverflow.com/questions/57551783/
Pytorch batch matrix-matrix outer product
Similarly to the question in Pytorch batch matrix vector outer product I have two matrices and would like to compute their outer product, or in other words the pairwise elementwise product. Shape example: If we have X1 and X2 of shapes of torch.Size([32, 300, 8]) The result should be of size torch.Size([32, 300, 300, 8])
You can add singleton dimensions: X1[:, None, ...] * X1[..., None, :] But Usman Ali's comment is also a good idea. Use torch.einsum: torch.einsum('bik,bjk->bijk', X1, X2)
https://stackoverflow.com/questions/57555134/
ImportError: No module named nibabel in python 2.7
I am using python 2.7 and I used pip install nibabel but I constantly get the error ImportError: No module named nibabel. when I type pip show nibabel I get this result so it seems that it is installed but still get the aforementioned error when using import nibabel as nib Name: nibabel Version: 2.5.0 Summary: Access a multitude of neuroimaging data formats Home-page: https://nipy.org/nibabel Author: nibabel developers Author-email: [email protected] License: MIT License Location: /usr/local/lib/python3.5/dist-packages Requires: six, numpy Required-by: Here the address shows it is installed in python3 path! How can I address this problem?
Install it using pip2: pip2 install nibabel Or explicitly call the pip module for Python 2.7: python2.7 -m pip install nibabel for example.
https://stackoverflow.com/questions/57559858/
Why my tensor defined in forward function can not be transformed in to cuda variable autonomously?
In PyTorch, in the forward function of a model class my_model(torch.nn.module): ...... def forward(): self.a=torch.zeros(1) #blabla After model.cuda(), why self.a is still a cpu variable?
This is so by design. Only the tensors which are a part of the model will move with model.cuda() or model.to("cuda"). These tensors are registered with register_parameter or register_buffer. This also includes child modules, parameters and buffers registered with the aforementioned functions. Even though self.a=torch.zeros(1) is actually a part of the class itself, by design it will not be moved to CUDA, instead you would need to do a.to("cuda"), if you haven't used the register* methods.
https://stackoverflow.com/questions/57570793/
What's the purpose of torch.autograd.Variable?
I load features and labels from my training dataset. Both of them are originally numpy arrays, but I change them to the torch tensor using torch.from _numpy(features.copy()) and torch.tensor(labels.astype(np.bool)). And I notice that torch.autograd.Variable is something like placeholder in tensorflow. When I train my network, first I tried features = features.cuda() labels = labels.cuda() outputs = Config.MODEL(features) loss = Config.LOSS(outputs, labels) Then I tried features = features.cuda() labels = labels.cuda() input_var = Variable(features) target_var = Variable(labels) outputs = Config.MODEL(input_var) loss = Config.LOSS(outputs, target_var) Both blocks succeed in activating training, but I worried that there might be trivial difference.
According to this question you no longer need variables to use Pytorch Autograd. Thanks to @skytree, we can make this even more explizit: Variables have been deprecated, i.e. you're not supposed to use them anymore. Autograd automatically supports Tensors with requires_grad set to True. And more importantly Variable(tensor) and Variable(tensor, requires_grad) still work as expected, but they return Tensors instead of Variables. This means that if your features and labels are tensors already (which they seem to be in your example) your Variable(features) and Variable(labels) does only return a tensor again. The original purpose of Variables was to be able to use automatic differentiation (Source): Variables are just wrappers for the tensors so you can now easily auto compute the gradients.
https://stackoverflow.com/questions/57580202/
pytorch "log_softmax_lastdim_kernel_impl" not implemented for 'torch.LongTensor'
I am trying to use my own dataset to classify text according to https://github.com/bentrevett/pytorch-sentiment-analysis/blob/master/5%20-%20Multi-class%20Sentiment%20Analysis.ipynb. My dataset is a csv of sentences and a class associated with it. there are 6 different classes: sent class 'the fox is brown' animal 'the house is big' object 'one water is drinkable' water ... When running: N_EPOCHS = 5 best_valid_loss = float('inf') for epoch in range(N_EPOCHS): start_time = time.time() print(start_time) train_loss, train_acc = train(model, train_iterator, optimizer, criterion) print(train_loss.type()) print(train_acc.type()) valid_loss, valid_acc = evaluate(model, valid_iterator, criterion) end_time = time.time() epoch_mins, epoch_secs = epoch_time(start_time, end_time) if valid_loss < best_valid_loss: best_valid_loss = valid_loss torch.save(model.state_dict(), 'tut5-model.pt') print(f'Epoch: {epoch+1:02} | Epoch Time: {epoch_mins}m {epoch_secs}s') print(f'\tTrain Loss: {train_loss:.3f} | Train Acc: {train_acc*100:.2f}%') print(f'\t Val. Loss: {valid_loss:.3f} | Val. Acc: {valid_acc*100:.2f}%') , I receive the following error RuntimeError: "log_softmax_lastdim_kernel_impl" not implemented for 'torch.LongTensor' pointing to: <ipython-input-38-9c6cff70d2aa> in train(model, iterator, optimizer, criterion) 14 print('pred'+ predictions.type()) 15 #batch.label = batch.label.type(torch.LongTensor) ---> 16 loss = criterion(predictions.long(), batch.label)** The solution posted here https://github.com/pytorch/pytorch/issues/14224 suggests I need to use long/int. I had to add .long() at line ** in order to fix this earlier error: RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target' The specific lines of code are: def train(model, iterator, optimizer, criterion): epoch_loss = 0 epoch_acc = 0 model.train() for batch in iterator: optimizer.zero_grad() predictions = model(batch.text) print('pred'+ predictions.type()) #batch.label = batch.label.type(torch.LongTensor) loss = criterion(predictions.long(), batch.label)** acc = categorical_accuracy(predictions, batch.label) loss.backward() optimizer.step() epoch_loss += loss.item() epoch_acc += acc.item() return epoch_loss / len(iterator), epoch_acc / len(iterator) Note, the ** was originally loss = criterion(predictions, batch.label) Any other suggestions to fix this issue?
criterion is defined as torch.nn.CrossEntropyLoss() in your notebook. As mentioned in documentation of CrossEntropyLoss, it expects probability values returned by model for each of the 'K' classes and corresponding value for ground-truth label as input. Now, probability values are float tensors, while ground-truth label should be a long tensor representing a class (class can not be a float, e.g. 2.3 can not represent a class). hence: loss = criterion(predictions, batch.label.long()) should work.
https://stackoverflow.com/questions/57590697/
The training loss of vgg16 implemented in pytorch does not decrease
I want to try some toy examples in pytorch, but the training loss does not decrease in the training. Some info is provided here: The model is vgg16, consisted of 13 conv layers and 3 dense layers. The data is cifar100 in pytorch. I choose cross entropy as the loss function. The code is as follows # encoding: utf-8 import torch import torch.optim as optim import torch.nn as nn import torch.nn.functional as F import torchvision.transforms as transforms import torchvision import numpy as np class VGG16(torch.nn.Module): def __init__(self, n_classes): super(VGG16, self).__init__() # construct model self.conv1_1 = nn.Conv2d(3, 64, 3, padding=1) self.conv1_2 = nn.Conv2d(64, 64, 3, padding=1) self.conv2_1 = nn.Conv2d(64, 128, 3, padding=1) self.conv2_2 = nn.Conv2d(128, 128, 3, padding=1) self.conv3_1 = nn.Conv2d(128, 256, 3, padding=1) self.conv3_2 = nn.Conv2d(256, 256, 3, padding=1) self.conv3_3 = nn.Conv2d(256, 256, 3, padding=1) self.conv4_1 = nn.Conv2d(256, 512, 3, padding=1) self.conv4_2 = nn.Conv2d(512, 512, 3, padding=1) self.conv4_3 = nn.Conv2d(512, 512, 3, padding=1) self.conv5_1 = nn.Conv2d(512, 512, 3, padding=1) self.conv5_2 = nn.Conv2d(512, 512, 3, padding=1) self.conv5_3 = nn.Conv2d(512, 512, 3, padding=1) self.fc6 = nn.Linear(512, 512) self.fc7 = nn.Linear(512, 512) self.fc8 = nn.Linear(512, n_classes) def forward(self, x): x = F.relu(self.conv1_1(x)) x = F.relu(self.conv1_2(x)) x = F.max_pool2d(x, (2, 2)) x = F.relu(self.conv2_1(x)) x = F.relu(self.conv2_2(x)) x = F.max_pool2d(x, (2, 2)) x = F.relu(self.conv3_1(x)) x = F.relu(self.conv3_2(x)) x = F.relu(self.conv3_3(x)) x = F.max_pool2d(x, (2, 2)) x = F.relu(self.conv4_1(x)) x = F.relu(self.conv4_2(x)) x = F.relu(self.conv4_3(x)) x = F.max_pool2d(x, (2, 2)) x = F.relu(self.conv5_1(x)) x = F.relu(self.conv5_2(x)) x = F.relu(self.conv5_3(x)) x = F.max_pool2d(x, (2, 2)) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc6(x)) x = F.relu(self.fc7(x)) x = self.fc8(x) return x def num_flat_features(self, x): size = x.size()[1:] num_features = 1 for s in size: num_features *= s return num_features if __name__ == '__main__': BATCH_SIZE = 128 LOG_INTERVAL = 5 # data transform = transforms.Compose([ transforms.ToTensor() ]) trainset = torchvision.datasets.CIFAR100( root='./data', train=True, download=True, transform=transform ) testset = torchvision.datasets.CIFAR100( root='./data', train=False, download=True, transform=transform ) trainloader = torch.utils.data.DataLoader(trainset, batch_size=BATCH_SIZE, shuffle=True) testloader = torch.utils.data.DataLoader(testset, batch_size=BATCH_SIZE, shuffle=False) # model vgg16 = VGG16(100) vgg16.cuda() # optimizer optimizer = optim.SGD(vgg16.parameters(), lr=0.01) # loss criterion = nn.CrossEntropyLoss() print('———— Train Start —————') for epoch in range(20): running_loss = 0. for step, (batch_x, batch_y) in enumerate(trainloader): batch_x, batch_y = batch_x.cuda(), batch_y.cuda() # optimizer.zero_grad() output = vgg16(batch_x) loss = criterion(output, batch_y) loss.backward() optimizer.step() running_loss += loss.item() if step % LOG_INTERVAL == 0: print('[%d, %4d] loss: %.4f' % (epoch, step, running_loss / LOG_INTERVAL)) running_loss = 0. def test(): print('———— Test Start ————') correct = 0 total = 0 # with torch.no_grad(): for test_x, test_y in testloader: images, labels = test_x.cuda(), test_y.cuda() output = vgg16(images) _, predicted = torch.max(output.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() accuracy = 100 * correct / total print('Accuracy of the network is: %.4f %%' % accuracy) print('———— Test Finish ————') test() print('———— Train Finish —————') The loss stays around 4.6060 and never decrease. I have tried different learning rate but does not work.
I have noticed that you are not using Batch normalization in between your convolution layers. I have added batch normalization layers and it seems to work. Following is the modified code: class VGG16(torch.nn.Module): def __init__(self, n_classes): super(VGG16, self).__init__() # construct model self.conv1_1 = nn.Conv2d(3, 64, 3, padding=1) self.conv11_bn = nn.BatchNorm2d(64) self.conv1_2 = nn.Conv2d(64, 64, 3, padding=1) self.conv12_bn = nn.BatchNorm2d(64) self.conv2_1 = nn.Conv2d(64, 128, 3, padding=1) self.conv21_bn = nn.BatchNorm2d(128) self.conv2_2 = nn.Conv2d(128, 128, 3, padding=1) self.conv22_bn = nn.BatchNorm2d(128) self.conv3_1 = nn.Conv2d(128, 256, 3, padding=1) self.conv31_bn = nn.BatchNorm2d(256) self.conv3_2 = nn.Conv2d(256, 256, 3, padding=1) self.conv32_bn = nn.BatchNorm2d(256) self.conv3_3 = nn.Conv2d(256, 256, 3, padding=1) self.conv33_bn = nn.BatchNorm2d(256) self.conv4_1 = nn.Conv2d(256, 512, 3, padding=1) self.conv41_bn = nn.BatchNorm2d(512) self.conv4_2 = nn.Conv2d(512, 512, 3, padding=1) self.conv42_bn = nn.BatchNorm2d(512) self.conv4_3 = nn.Conv2d(512, 512, 3, padding=1) self.conv43_bn = nn.BatchNorm2d(512) self.conv5_1 = nn.Conv2d(512, 512, 3, padding=1) self.conv51_bn = nn.BatchNorm2d(512) self.conv5_2 = nn.Conv2d(512, 512, 3, padding=1) self.conv52_bn = nn.BatchNorm2d(512) self.conv5_3 = nn.Conv2d(512, 512, 3, padding=1) self.conv53_bn = nn.BatchNorm2d(512) self.fc6 = nn.Linear(512, 512) self.fc7 = nn.Linear(512, 512) self.fc8 = nn.Linear(512, n_classes) def forward(self, x): x = F.relu(self.conv11_bn(self.conv1_1(x))) x = F.relu(self.conv12_bn(self.conv1_2(x))) x = F.max_pool2d(x, (2, 2)) x = F.relu(self.conv22_bn(self.conv2_1(x))) x = F.relu(self.conv21_bn(self.conv2_2(x))) x = F.max_pool2d(x, (2, 2)) x = F.relu(self.conv31_bn(self.conv3_1(x))) x = F.relu(self.conv32_bn(self.conv3_2(x))) x = F.relu(self.conv33_bn(self.conv3_3(x))) x = F.max_pool2d(x, (2, 2)) x = F.relu(self.conv41_bn(self.conv4_1(x))) x = F.relu(self.conv42_bn(self.conv4_2(x))) x = F.relu(self.conv43_bn(self.conv4_3(x))) x = F.max_pool2d(x, (2, 2)) x = F.relu(self.conv51_bn(self.conv5_1(x))) x = F.relu(self.conv52_bn(self.conv5_2(x))) x = F.relu(self.conv53_bn(self.conv5_3(x))) x = F.max_pool2d(x, (2, 2)) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc6(x)) x = F.relu(self.fc7(x)) x = self.fc8(x) return x However, a more elegant version of the same could be found here
https://stackoverflow.com/questions/57605094/
Prevent GPU usage in SLURM when --gpus is not set
We're using SLURM to manage a small on-premise cluster. A key resource we are managing is GPUs. When a user requests GPUs via --gpus=2 the CUDA_VISIBLE_DEVICES environment variable is set with the GPUs SLURM allocates to the user. $ srun --gpus=2 bash -c 'echo $CUDA_VISIBLE_DEVICES' 0,1 We have a small team and can trust our users to not abuse the system (they could easily overwrite the environment variable) so this works great. However, it's a bit too easy to bypass this accidentally because when --gpus isn't specified $CUDA_VISIBLE_DEVICES is left unset so the user can use any GPU (we're typically using PyTorch). In other words, the following command works fine (so long as it lands on a GPU node) but I would prefer that it fails (because no GPU was requested). srun sudo docker run -e CUDA_VISIBLE_DEVICES --runtime=nvidia pytorch/pytorch:1.1.0-cuda10.0-cudnn7.5-runtime python -c 'import torch; print(torch.tensor([1., 2.], device=torch.device("cuda:0")))' It would fail if $CUDA_VISIBLE_DEVICES were set to -1. $ CUDA_VISIBLE_DEVICES=-1 sudo docker run -e CUDA_VISIBLE_DEVICES --runtime=nvidia pytorch/pytorch:1.1.0-cuda10.0-cudnn7.5-runtime python -c 'import torch; print(torch.tensor([1., 2.], device=torch.device("cuda:0")))' THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1556653099582/work/aten/src/THC/THCGeneral.cpp line=51 error=38 : no CUDA-capable device is detected Traceback (most recent call last): File "<string>", line 1, in <module> File "/opt/conda/lib/python3.6/site-packages/torch/cuda/__init__.py", line 163, in _lazy_init torch._C._cuda_init() RuntimeError: cuda runtime error (38) : no CUDA-capable device is detected at /opt/conda/conda-bld/pytorch_1556653099582/work/aten/src/THC/THCGeneral.cpp:51 How can I configure SLURM to set CUDA_VISIBLE_DEVICES to -1 when --gpus is not specified?
You can use the TaskProlog script to set the $CUDA_VISIBLE_DEVICES variable to -1 if it was not set by Slurm. In slurm.conf, configure TaskProlog=/path/to/prolog.sh and set the following content for prolog.sh. #! /bin/bash if [[ -z $CUDA_VISIBLE_DEVICES]]; then echo export CUDA_VISIBLE_DEVICES=-1 fi The echo export ... part will inject CUDA_VISIBLE_DEVICES=-1 in the job environment. Make sure /path/to is visible from all compute nodes. But this will not prevent a user from playing the system and redefining the variable from within the Python script. Really preventing access would require configuring cgroups.
https://stackoverflow.com/questions/57615258/
fastai error predicting with exported/reloaded model: "Input type and weight type should be the same"
Whenever I export a fastai model and reload it, I get this error (or a very similar one) when I try and use the reloaded model to generate predictions on a new test set: RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.cuda.HalfTensor) should be the same Minimal reprodudeable code example below, you just need to update your FILES_DIR variable to where the MNIST data gets deposited on your system: from fastai import * from fastai.vision import * # download data for reproduceable example untar_data(URLs.MNIST_SAMPLE) FILES_DIR = '/home/mepstein/.fastai/data/mnist_sample' # this is where command above deposits the MNIST data for me # Create FastAI databunch for model training tfms = get_transforms() tr_val_databunch = ImageDataBunch.from_folder(path=FILES_DIR, # location of downloaded data shown in log of prev command train = 'train', valid_pct = 0.2, ds_tfms = tfms).normalize() # Create Model conv_learner = cnn_learner(tr_val_databunch, models.resnet34, metrics=[error_rate]).to_fp16() # Train Model conv_learner.fit_one_cycle(4) # Export Model conv_learner.export() # saves model as 'export.pkl' in path associated with the learner # Reload Model and use it for inference on new hold-out set reloaded_model = load_learner(path = FILES_DIR, test = ImageList.from_folder(path = f'{FILES_DIR}/valid')) preds = reloaded_model.get_preds(ds_type=DatasetType.Test) Output: "RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.cuda.HalfTensor) should be the same" Stepping through the code statement by statement, everything works fine until the last line pred = ... which is where the torch error above pops up. Relevant software versions: Python 3.7.3 fastai 1.0.57 torch 1.2.0 torchvision 0.4.0
So the answer to this ended up being relatively simple: 1) As noted in my comment, training in mixed precision mode (setting conv_learner to_fp16()) caused the error with the exported/reloaded model 2) To train in mixed precision mode (which is faster than regular training) and enable export/reload of the model without errors, simply set the model back to default precision before exporting. ...In code, simply changing the example above: # Export Model conv_learner.export() to: # Export Model (after converting back to default precision for safe export/reload conv_learner = conv_learner.to_fp32() conv_learner.export() ...and now the full (reproduceable) code example above runs without errors, including the prediction after model reload.
https://stackoverflow.com/questions/57618507/
How to fix 'RuntimeError: Address already in use' in PyTorch?
I am trying to run a distributive application with PyTorch distributive trainer. I thought I would first try the example they have, found here. I set up two AWS EC2 instances and configured them according to the description in the link, but when I try to run the code I get two different errors: in the first terminal window for node0 I get the error message: RuntimeError: Address already in use Under the other three windows I get the same error message: RuntimeError: NCCL error in: /pytorch/torch/lib/c10d/ProcessGroupNCCL.cpp:272, unhandled system error I followed the code in the link, and terminated the instances an redid but it didn't help/ This is using python 3.6 with the nightly build Cuda 9.0. I tried changing the MASTER_ADDR to the ip for node0 on both nodes, as well as using the same MASTER_PORT (which is an available, unused port). However I still get the same error message. After running this, my goal is to the adjust this StyleGan implementation so that I can train it across multiple GPUs in two different nodes.
So after a lot of failed attempts I found out what the problem is. Note that this solution applies to using ASW deep learning instances. After creating two instances I had to adjust the security group. Add two rules: The first rule should be ALL_TCP, and set the source to the Private IPs of the leader. The second rule should be the same (ALL_TCP), but with the source as the Private IPs of the slave node. Previously, I had the setting security rule set as: Type SSH, which only had a single available port (22). For some reason I was not able to use this port to allow the nodes to communicate. After changing these settings the code worked fine. I was also able to run this with the above mentioned settings.
https://stackoverflow.com/questions/57624739/
How to use autograd.gradcheck in PyTorch?
The documentation does not include any example use case of gradcheck, where would it be useful?
There's an example use case provided in the documentation here: https://pytorch.org/docs/master/notes/extending.html You probably want to check if the backward method you implemented actually computes the derivatives of your function. It is possible by comparing with numerical approximations using small finite differences: from torch.autograd import gradcheck # gradcheck takes a tuple of tensors as input, check if your gradient # evaluated with these tensors are close enough to numerical # approximations and returns True if they all verify this condition. input = (torch.randn(20,20,dtype=torch.double,requires_grad=True), torch.randn(30,20,dtype=torch.double,requires_grad=True)) test = gradcheck(linear, input, eps=1e-6, atol=1e-4) print(test) As the quote above suggests, the purpose of the gradcheck function is to verify that a custom backward function agrees with a numerical approximation of the gradient. The primary use case is when you're implementing a custom backward operation. In very few cases should you be implementing your own backward function in PyTorch. This is because PyTorch's autograd functionality takes care of computing gradients for the vast majority of operations. The most obvious exceptions are You have a function which can't be expressed as a finite combination of other differentiable functions (for example, if you needed the incomplete gamma function, you might want to write your own forward and backward which used numpy and/or lookup tables). You're looking to speed up the computation of a particularly complicated expression for which the gradient could be drastically simplified after applying the chain rule.
https://stackoverflow.com/questions/57627406/
Invalid multinomial distribution (encountering probability entry < 0) at /pytorch/aten/src/TH/generic/THTensorRandom.cpp:325
I have a PyTorch tensor called out_probs which is produced like this: out_probs=F.softmax(out_dec[:,0],dim=0) Also, the shape of out_probs is [128,20004] out_probs is the result of a softmax operation and it's not supposed to contain any negative value so naturally the result of out_probs[out_probs&lt;0 is going to be an empty tensor(actually I checked and it was empty) But when I'm running torch.multinomial(out_probs, 1) I'm getting : RuntimeError: invalid argument 2: invalid multinomial distribution (encountering probability entry &lt; 0) at /pytorch/aten/src/TH/generic/THTensorRandom.cpp:325 That implies my tensor has a negative entry and I don't know why this is happening?
I believe you've found a bug in the error reporting for torch.multinomial. For example x = torch.ones(128, 1) x[0] *= 1e100 out_probs = F.softmax(x, dim=0) print('Negative values:', torch.sum(out_probs &lt; 0).item()) y = torch.multinomial(out_probs, 1) results in the following output Negative values: 0 RuntimeError: invalid argument 2: invalid multinomial distribution (encountering probability entry &lt; 0) at /pytorch/aten/src/TH/generic/THTensorRandom.cpp:298 It turns out this is getting triggered because out_probs contains nan entries. print('nan values:', torch.sum(torch.isnan(out_probs)).item()) gives nan values: 128 Which are caused by mathematical instabilities in softmax. Strangely, when the values in out_probs are infinite you get the proper error message RuntimeError: invalid argument 2: invalid multinomial distribution (encountering probability entry = infinity or NaN) at /pytorch/aten/src/TH/generic/THTensorRandom.cpp:302 This bug should probably be reported at https://github.com/pytorch/pytorch/issues if it hasn't been fixed in the most recent version. By the way I'm using PyTorch 1.0.1.post2
https://stackoverflow.com/questions/57627943/
padding a list of torch tensors (or numpy arrays)
Let's say I have a list as the following: l = [torch.randn(2,3), torch.randn(2,4),torch.randn(2,5)] I want to zero pad all of them in the second dimension, so they will extend as far as 5 elements (5 being the max number between the three of the elements in the second dimension). How can I do this. I tried this but failed: from torch.nn.utils.rnn import pad_sequence pad_sequence(l, batch_first=True, padding_value=0) which caused the following error: RuntimeError: The expanded size of the tensor (3) must match the existing size (4) at non-singleton dimension 1. Target sizes: [2, 3]. Tensor sizes: [2, 4] The equivalent answer in Numpy would also be appreciated.
One option is to use np.pad. Example: import numpy as np a = np.random.randn(2, 3) b = np.pad(a, [(0, 0), (0, 2)], mode='constant') Print a gives [[ 1.22721163 1.23456672 0.51948003] [ 0.16545496 0.06609003 -0.32071653]] Print b gives [[ 1.22721163 1.23456672 0.51948003 0. 0. ] [ 0.16545496 0.06609003 -0.32071653 0. 0. ]] The second argument of pad is pad_width which is a list of before/after paddings for each dimension. So in this example no padding in the first dimension and two paddings at the end of the second dimension. There are lots of other mode options you can use so check out the docs. For your particular problem you'll need to add an extra step to work out the padding for each array. Edit For pytorch I think you want torch.nn.functional.pad e.g. import torch t = torch.randn(2, 3) torch.nn.functional.pad(t, (0, 2)) Edit 2 The torch.nn.utils.rnn.pad_sequence requires the trailing dimensions of all the tensors in the list to be the same so you need to some transposing for it to work nicely import torch # l = [torch.randn(2,3), torch.randn(2,4),torch.randn(2,5)] # l = [i.transpose(0, 1) for i in l] # or simply make you tensors with switched dimensions l = [torch.randn(3,2), torch.randn(4,2),torch.randn(5,2)] out = torch.nn.utils.rnn.pad_sequence(l, batch_first=True) # out will now be a tensor with shape (3, 5, 2) # You can transpose it back to (3, 2, 5) with out = out.transpose(1, 2)
https://stackoverflow.com/questions/57628457/
Unable to load data Google Colab
I am trying to load data after downloading it through kaggle cli. This exercise is from this course on Udacity. !kaggle competitions download -c dogs-vs-cats !unzip {content}/competitions/dogs-vs-cats/train.zip -d {content}/competitions/dogs-vs-cats/ !unzip {content}/competitions/dogs-vs-cats/test1.zip -d {content}/competitions/dogs-vs-cats/ Counting the number of images !ls '{content}/competitions/dogs-vs-cats/train/' | wc -l # 25000 Then I try to load the data data_dir = '{content}/competitions/dogs-vs-cats/train/' transform = transforms.Compose([transforms.Resize(255), transforms.CenterCrop(224), transforms.ToTensor()]) # TODO: compose transforms here dataset = datasets.ImageFolder(data_dir, transform=transform) # TODO: create the ImageFolder dataloader = torch.utils.data.DataLoader(dataset,batch_size=32,shuffle=True) # TODO: use the ImageFolder dataset to create the DataLoader Error --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-70-9c49d0bdcdb0&gt; in &lt;module&gt;() 4 transforms.CenterCrop(224), 5 transforms.ToTensor()]) # TODO: compose transforms here ----&gt; 6 dataset = datasets.ImageFolder(data_dir, transform=transform) # TODO: create the ImageFolder 7 dataloader = torch.utils.data.DataLoader(dataset,batch_size=32,shuffle=True) # TODO: use the ImageFolder dataset to create the DataLoader 1 frames /usr/local/lib/python3.6/dist-packages/torchvision/datasets/folder.py in __init__(self, root, transform, target_transform, loader, is_valid_file) 207 transform=transform, 208 target_transform=target_transform, --&gt; 209 is_valid_file=is_valid_file) 210 self.imgs = self.samples /usr/local/lib/python3.6/dist-packages/torchvision/datasets/folder.py in __init__(self, root, loader, extensions, transform, target_transform, is_valid_file) 95 if len(samples) == 0: 96 raise (RuntimeError("Found 0 files in subfolders of: " + self.root + "\n" ---&gt; 97 "Supported extensions are: " + ",".join(extensions))) 98 99 self.loader = loader RuntimeError: Found 0 files in subfolders of: {content}/competitions/dogs-vs-cats/train/ Supported extensions are: .jpg,.jpeg,.png,.ppm,.bmp,.pgm,.tif,.tiff,.webp
Looks like you are using f-strings in a wrong way. Simply add f here: data_dir = f'{content}/competitions/dogs-vs-cats/train/' to include content value to the path; without f you are just using {content}/competitions... string as a path, as you can see in your error message.
https://stackoverflow.com/questions/57630424/
RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
In a pytorch model training process I get this error: RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.cuda.LongTensor [128, 1]] is at version 8; expected version 7 instead. Hint: the backtrace further above shows the operation that failed to compute its gradient. The variable in question was changed in there or anywhere later. Good luck! with stack trace sys:1: RuntimeWarning: Traceback of forward call that caused the error: File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/runpy.py", line 174, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/ipykernel_launcher.py", line 16, in &lt;module&gt; app.launch_new_instance() File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/traitlets/config/application.py", line 658, in launch_instance app.start() File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/ipykernel/kernelapp.py", line 499, in start self.io_loop.start() File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/tornado/ioloop.py", line 1073, in start handler_func(fd_obj, events) File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/tornado/stack_context.py", line 300, in null_wrapper return fn(*args, **kwargs) File "/home/arash/.local/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 456, in _handle_events self._handle_recv() File "/home/arash/.local/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 486, in _handle_recv self._run_callback(callback, msg) File "/home/arash/.local/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 438, in _run_callback callback(*args, **kwargs) File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/tornado/stack_context.py", line 300, in null_wrapper return fn(*args, **kwargs) File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 283, in dispatcher return self.dispatch_shell(stream, msg) File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 233, in dispatch_shell handler(stream, idents, msg) File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 399, in execute_request user_expressions, allow_stdin) File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/ipykernel/ipkernel.py", line 208, in do_execute res = shell.run_cell(code, store_history=store_history, silent=silent) File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/ipykernel/zmqshell.py", line 537, in run_cell return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs) File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2714, in run_cell interactivity=interactivity, compiler=compiler, result=result) File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2818, in run_ast_nodes if self.run_code(code, result): File "/home/arash/anaconda2/envs/mzh27/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2878, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "&lt;ipython-input-71-a5b255596e11&gt;", line 33, in &lt;module&gt; sampled_captions, sampled_log_probs=predict_captions(out_enc,hid_enc,enc_pp,'sample') File "&lt;ipython-input-70-a6ea511f0678&gt;", line 18, in predict_captions out_dec, hid_dec, word_logits = dec.forward(r, last_enc, img_features) File "&lt;ipython-input-21-0601dad4805f&gt;", line 21, in forward emb = self.embedding(input) File "/home/arash/.local/lib/python2.7/site-packages/torch/nn/modules/module.py", line 493, in __call__ result = self.forward(*input, **kwargs) File "/home/arash/.local/lib/python2.7/site-packages/torch/nn/modules/sparse.py", line 117, in forward self.norm_type, self.scale_grad_by_freq, self.sparse) File "/home/arash/.local/lib/python2.7/site-packages/torch/nn/functional.py", line 1506, in embedding return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse) --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-71-a5b255596e11&gt; in &lt;module&gt;() 54 torch.stack(sampled_log_probs).reshape(-1)).mean() 55 torch.autograd.set_detect_anomaly(True) ---&gt; 56 loss.backward() 57 clip_grad_value_(enc_optim.param_groups[0]['params'], 5.0) 58 clip_grad_value_(dec_optim.param_groups[0]['params'], 5.0) /home/arash/.local/lib/python2.7/site-packages/torch/tensor.pyc in backward(self, gradient, retain_graph, create_graph) 105 products. Defaults to ``False``. 106 """ --&gt; 107 torch.autograd.backward(self, gradient, retain_graph, create_graph) 108 109 def register_hook(self, hook): /home/arash/.local/lib/python2.7/site-packages/torch/autograd/__init__.pyc in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables) 91 Variable._execution_engine.run_backward( 92 tensors, grad_tensors, retain_graph, create_graph, ---&gt; 93 allow_unreachable=True) # allow_unreachable flag 94 95 But I'm unable to locate in-place operation that causes the error. Here is my code: for epoch in xrange(0, 13): print ("Starting New Epoch: %d" % epoch) rewards = { 'sample_cider': [], 'sample_context': [], 'sample_reward': [], # actual reward, controlled by beta 'greedy_cider': [], 'greedy_context': [], 'greedy_reward': [] } order = np.arange(enc_padded_text.shape[0]) np.random.shuffle(order) enc_padded_text = enc_padded_text[order] input_text=[input_text[i] for i in order] dec_text_tensor.data = dec_text_tensor.data[order] for i in xrange(num_batches): s = i * BATCH_SIZE e = (i+1) * BATCH_SIZE _, enc_pp, dec_pp, enc_lengths = make_packpadded_s2s(s, e, enc_padded_text, dec_text_tensor) enc.zero_grad() dec.zero_grad() hid = enc.initHidden(BATCH_SIZE) out_enc, hid_enc = enc.forward(enc_pp, hid, enc_lengths) hid_enc = torch.cat([hid_enc[0,:, :], hid_enc[1,:,:]], dim=1).unsqueeze(0) gt_dict = dict(zip(_,input_text[s:e])) sampled_captions, sampled_log_probs=predict_captions(out_enc,hid_enc,enc_pp,'sample') sampled_dict = dict(zip(_, sampled_captions)) with torch.no_grad(): greedy_captions = predict_captions(out_enc,hid_enc,enc_pp, 'greedy') greedy_dict = dict(zip(_, greedy_captions)) sample_cider_score, sample_context_score, sample_reward = get_scores( dec_pp[:,1:], sampled_captions, gt_dict, sampled_dict) greedy_cider_score, greedy_context_score, greedy_reward = get_scores( dec_pp[:,1:], greedy_captions, gt_dict, greedy_dict) # self-critical: score from sampling - score from test time advantages = torch.Tensor((sample_cider_score - greedy_cider_score).reshape(-1)) # normalize advantages advantages = ((advantages - advantages.mean()) / advantages.std() + 1e-9) if cuda: advantages = advantages.cuda() loss = -(advantages * torch.stack(sampled_log_probs).reshape(-1)).mean() torch.autograd.set_detect_anomaly(True) loss.backward() clip_grad_value_(enc_optim.param_groups[0]['params'], 5.0) clip_grad_value_(dec_optim.param_groups[0]['params'], 5.0) enc_optim.step() dec_optim.step() rewards['sample_cider'].extend(sample_cider_score) rewards['sample_context'].extend(sample_context_score) rewards['sample_reward'].extend(sample_reward) rewards['greedy_cider'].extend(greedy_cider_score) rewards['greedy_context'].extend(greedy_context_score) rewards['greedy_reward'].extend(greedy_reward) if (b + 1) % 100 == 0: print('\t[Batch {} running metrics] - R train {:.2f} - R train (greedy): {:.2f}'.format( b + 1, np.mean(rewards['sample_reward']), np.mean(rewards['greedy_reward']))) predict_captions function: def predict_captions(img_features,hid_enc,enc_pp, mode='sample', constrain=False,L=22): dec_tensor = torch.ones((enc_pp.shape[0]), L+1, dtype=torch.long) * Toks.SOS global cuda if cuda: dec_tensor = dec_tensor.cuda(device=device) last_enc = hid_enc if mode == 'beam_search': return self.beam_search(img_features, state, lstm_states) predictions = [] log_probs = [] # this should store the index of the first occurrence of &lt;EOS&gt; # for each sample in the batch EOS_tracker = np.full(img_features.shape[0], None) for i in range(L): r=dec_tensor[:,i].unsqueeze(1) out_dec, hid_dec, word_logits = dec.forward(r, last_enc, img_features) out_dec[:, 0, Toks.UNK] = -np.inf # ignore unknowns l=out_dec[:,0] chosen = torch.argmax(l,dim=1) dec_tensor[:, i+1] = chosen last_enc = hid_dec # decoding stuff probs = F.softmax(word_logits, dim=2) probs=probs.reshape(128,20004) if constrain: # enforce constraint that the same word can't be predicted # twice in a row. zero-out the probability of previous words for p, prev_idx in zip(probs, state['prev_word_indeces']): p[prev_idx] = 0 if mode == 'sample': idxs = torch.multinomial(probs, 1) else: idxs = torch.argmax(probs, dim=1) if cuda: idxs = idxs.cpu() words = [dec_idx_to_word[index] for index in idxs] predictions.append(np.array(words).reshape(-1)) # get the respective log probability of chosen word # for each sample in the batch log_probs.append([lp[i] for (lp, i) in zip(torch.log(probs), idxs)]) # inefficient but this should be fast enough anyway... ? :( eos_idxs = (np.array(words)==dec_idx_to_word[2]).nonzero()[0] for idx in eos_idxs: if EOS_tracker[idx] is None: EOS_tracker[idx] = i + 1 # finish loop if they're all done if len(EOS_tracker[EOS_tracker == None])==0: break # build the actual sentences, up until the first occurrence of &lt;EOS&gt; captions = [ [' '.join(w[:eos_idx])] for (w, eos_idx) in zip(np.array(predictions).T, EOS_tracker) ] print captions # do this only when training. not needed otherwise. if mode == 'sample': log_probs = [lp[:eos_idx].sum() for (lp, eos_idx) in zip(np.array(log_probs).T, EOS_tracker)] return captions, log_probs return captions models: class Encoder_s2s(nn.Module): def __init__(self, input_size, hidden_size): super(Encoder_s2s, self).__init__() assert hidden_size % 2 == 0 self.hidden_size = hidden_size self.input_size = input_size self.hidden_init_tensor = torch.zeros(2, 1, self.hidden_size/2, requires_grad=True) nn.init.normal_(self.hidden_init_tensor, mean=0, std=0.05) self.hidden_init = torch.nn.Parameter(self.hidden_init_tensor, requires_grad=True) self.embedding = nn.Embedding(input_size, hidden_size) self.emb_drop = nn.Dropout(0.2) self.gru = nn.GRU(hidden_size, hidden_size/2, batch_first=True, bidirectional=True) self.gru_out_drop = nn.Dropout(0.2) self.gru_hid_drop = nn.Dropout(0.3) def forward(self, input, hidden, lengths): emb = self.emb_drop(self.embedding(input)) #emb = embedded_dropout(self.embedding, input, dropout=0.2 if self.training else 0) pp = torch.nn.utils.rnn.pack_padded_sequence(emb, lengths, batch_first=True) out, hidden = self.gru(pp, hidden) out = torch.nn.utils.rnn.pad_packed_sequence(out, batch_first=True)[0] out = self.gru_out_drop(out) hidden = self.gru_hid_drop(hidden) return out, hidden def initHidden(self, bs): return self.hidden_init.expand(2, bs, self.hidden_size/2).contiguous() class DecoderAttn(nn.Module): def __init__(self, input_size, hidden_size, output_size, out_bias): super(DecoderAttn, self).__init__() self.hidden_size = hidden_size self.input_size = input_size self.embedding = nn.Embedding(input_size, hidden_size) self.emb_drop = nn.Dropout(0.2) self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True) self.gru_drop = nn.Dropout(0.2) self.mlp = nn.Linear(hidden_size*2, output_size) if out_bias is not None: out_bias_tensor = torch.tensor(out_bias, requires_grad=False) self.mlp.bias.data[:] = out_bias_tensor self.logsoftmax = nn.LogSoftmax(dim=2) self.att_mlp = nn.Linear(hidden_size, hidden_size, bias=False) self.attn_softmax = nn.Softmax(dim=2) def forward(self, input, hidden, encoder_outs): emb = self.embedding(input) emb=self.emb_drop(emb) out, hidden = self.gru(emb, hidden) out_proj = self.att_mlp(out) enc_out_perm = encoder_outs.permute(0, 2, 1) e_exp = torch.bmm(out_proj, enc_out_perm) attn = self.attn_softmax(e_exp) ctx = torch.bmm(attn, encoder_outs) full_ctx = torch.cat([self.gru_drop(out), ctx], dim=2) out = self.mlp(full_ctx) out1 = self.logsoftmax(out) return out1, hidden, out
A tensor matching this description torch.cuda.LongTensor [128, 1], should narrow down your search. A quick google search revealed that, LongTensors are most commonly returned by min , max, sort. so the lines l=out_dec[:,0] chosen = torch.argmax(l,dim=1) dec_tensor[:, i+1] = chosen Most probably the line dec_tensor[:, i+1] = chosen seems problematic.
https://stackoverflow.com/questions/57631705/
What is the correct way to use OHE lookup table for a pytorch RNN?
I am currently trying to build a LSTM RNN using pytorch. One input vector is represented as an array of 50 integers corresponding to a sequence of at most 50 tokens with padding where each integer corresponds to an element from my vocabulary and the index of the 1 in the OHE vector. I want to have an embedding layer that just uses a lookup table to One-hot encode the integer-- kind of like tensorflow's OHE layer. Something like this "kind of" works import torch import numpy as np import torch.nn as nn # vocab_size is the number of words in your train, val and test set # vector_size is the dimension of the word vectors you are using vocab_size, vector_size = 5, 5 embed = nn.Embedding(vocab_size, vector_size) # intialize the word vectors, pretrained_weights is a # numpy array of size (vocab_size, vector_size) and # pretrained_weights[i] retrieves the word vector of # i-th word in the vocabulary pretrained_weights = np.zeros((vocab_size, vector_size)) np.fill_diagonal(pretrained_weights, 1) tmp =torch.from_numpy(pretrained_weights) embed.weight = nn.Parameter(tmp,requires_grad=False ) # Then turn the word index into actual word vector vocab = {"some": 0, "words": 1} word_indexes = torch.from_numpy(np.array([vocab[w] for w in ["some", "words"]])) word_vectors = embed(word_indexes) word_vectors.data.numpy() &gt;&gt;&gt;output array([[1., 0., 0., 0., 0.], [0., 1., 0., 0., 0.]]) but it is very hacky, and doesn't play nicely with batches of input vectors. What is the correct way to declare a OHE embedding layer at the begining of an RNN?
The method you are looking for is torch.nn.functional.one_hot. It was added to PyTorch later, so it's hard to find when you Google for it. &gt;&gt;&gt; import torch &gt;&gt;&gt; x = torch.arange(0,5) &gt;&gt;&gt; x tensor([0, 1, 2, 3, 4]) &gt;&gt;&gt; torch.nn.functional.one_hot(x) tensor([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]])
https://stackoverflow.com/questions/57632084/
Why does my tensorboard say: 'No scalar data was found' when using SummaryWriter.add_scalar?
I am attempting to visualize a loss vs. epoch graph using tensorboard (by calling .addscalar()) so that I can appropriately tune my neural network model. However, after training the model, I check my tensorboard in the web browser and it reads: 'No scalar data was found.' I've tried checking my events statistics and it seems like there are scalars: Event statistics for runs/tf_druggability/classification_ffnn_1: audio - graph - histograms - images - scalars first_step 0 last_step 90 max_step 90 min_step 0 num_steps 10 outoforder_steps [(90L, 0L), (90L, 0L)] sessionlog:checkpoint - sessionlog:start - sessionlog:stop - tensor - Here's my code: from torch.utils.tensorboard import SummaryWriter sess = tensorflow.Session() writer = SummaryWriter('runs/tf_druggability/classification_ffnn_1', sess.graph) for epoch in range(100): # Wrap input data and labels in Variable to can gradient descent (in place of DataLoader) inputs = Variable(traindf_to_tensor) labels = Variable(trainlabels_to_tensor) optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() if(epoch%10 == 0): # HERE I WRITE to the LOG FILE for TENSORBOARD: writer.add_scalar('training loss', loss.item(), epoch) print('epoch {}, loss {}'.format(epoch, loss.item())) writer.close() print('Finished training! :)') When I try to open the events file in Jupyter Notebooks it has this in it (... means I've omitted the middle part): 1800 0000 0000 0000 a37f 4b22 09f2 3d6b a51e 58d7 411a 0d62 7261 696e 2e45 7665 6e74 3a32 ac51 0a16 2100 0000 0000 0000 ... f723 0000 0000 0000 00b0 9f77 4309 d00a 0ea7 1e58 d741 105a 2a16 0a14 0a0d 7472 6169 6e69 6e67 5f6c 6f73 7315 c193 403f
I discovered that the graphs only displayed if I was in the exact same directory as the program I'm running. Being in a higher directory than that of the program seems to have caused this inability to display graphs.
https://stackoverflow.com/questions/57634231/
Implementation of Focal loss for multi label classification
trying to write focal loss for multi-label classification class FocalLoss(nn.Module): def __init__(self, gamma=2, alpha=0.25): self._gamma = gamma self._alpha = alpha def forward(self, y_true, y_pred): cross_entropy_loss = torch.nn.BCELoss(y_true, y_pred) p_t = ((y_true * y_pred) + ((1 - y_true) * (1 - y_pred))) modulating_factor = 1.0 if self._gamma: modulating_factor = torch.pow(1.0 - p_t, self._gamma) alpha_weight_factor = 1.0 if self._alpha is not None: alpha_weight_factor = (y_true * self._alpha + (1 - y_true) * (1 - self._alpha)) focal_cross_entropy_loss = (modulating_factor * alpha_weight_factor * cross_entropy_loss) return focal_cross_entropy_loss.mean() But when i run this i get File "train.py", line 82, in &lt;module&gt; loss = loss_fn(output, target) File "/home/bubbles/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 538, in __call__ for hook in self._forward_pre_hooks.values(): File "/home/bubbles/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 591, in __getattr__ type(self).__name__, name)) AttributeError: 'FocalLoss' object has no attribute '_forward_pre_hooks' Any suggestions would be really helpful, Thanks in advance.
You shouldn't inherit from torch.nn.Module as it's designed for modules with learnable parameters (e.g. neural networks). Just create normal functor or function and you should be fine. BTW. If you inherit from it, you should call super().__init__() somewhere in your __init__(). EDIT Actually inheriting from nn.Module might be a good idea, it allows you to use the loss as part of neural network and is common in PyTorch implementations/PyTorch Lightning.
https://stackoverflow.com/questions/57635169/
Use PyTorch to adjust Tensor matrix values based on numbers I calculate from the Tensors?
I have two tensors (matrices) that I've initialized: sm=Var(torch.randn(20,1),requires_grad=True) sm = torch.mm(sm,sm.t()) freq_m=Var(torch.randn(12,20),requires_grad=True) I am creating two lists from the data inside these 2 matrices, and I am using spearmanr to get a correlation value between these 2 lists. How I am creating the lists is not important, but the goal is to adjust the values inside the matrices so that the calculated correlation value is as close to 1 as possible. If I were to solve this problem manually, I would tweak values in the matrices by .01 (or some small number) each time and recalculate the lists and correlation score. If the new correlation value is higher than the previous one, I would save the 2 matrices and tweak a different value until I get the 2 matrices that give me the highest correlation score possible. Is PyTorch capable of doing this automatically? I know PyTorch can adjust based on an equation but the way I want to adjust the matrix values is not against an equation, it's against a correlation value that I calculate. Any guidance with this is greatly appreciated!
Pytorch has an autograd package, that means if you have variable and you pass them through differentiable functions and get a scalar result, you can perform a gradient descent to update the variable to lower or augment the scalar result. So what you need to do is to define a function f that works on tensor level such that f(sm, freq_m) will give you the desired correlation. Then, you should do something like: lr = 1e-3 for i in range(100): # 100 updates loss = 1 - f(sm, freq_m) print(loss) loss.backward() with torch.no_grad(): sm -= lr * sm.grad freq_m -= lr * freq_m.grad # Manually zero the gradients after updating weights sm.grad.zero_() freq_m.grad.zero_() The learning rate is basically the size of the step you do, a learning rate too high will cause the loss to explode, and a learning rate too little will cause a slow convergence, I suggest you experiment. Edit : To answer the comment on loss.backward : for any differentiable function f, f is a function of multiple tensors t1, ..., tn with requires_grad=True as a result, you can calculate the gradient of the loss with respect to each of those tensors. When you do loss.backward, it calculates those gradients and store those in t1.grad, ..., tn.grad. Then you update t1, ..., tn using gradient descent in order to lower the value of f. This update doesn't need a computational graph, so this is why you use with torch.no_grad(). At the end of the loop, you zero the gradients because .backward doesn't overwrite the gradients but rather add the new gradients to them. More on that here : https://discuss.pytorch.org/t/why-do-we-need-to-set-the-gradients-manually-to-zero-in-pytorch/4903
https://stackoverflow.com/questions/57639434/
PyTorch: wrapping multiple records in one file?
Is there a standard way of encoding multiple records (in this case, data from multiple .png or .jpeg images) in one file that PyTorch can read? Something similar to TensorFlow's "TFRecord" or MXNet's "RecordIO", but for PyTorch. I need to download image data from S3 for inference, and it's much slower if my image data is in many small .jpg files rather than fewer files. Thanks.
One thing is to store batches of images together in a single npz file. Numpy's np.savez lets you save multiple arrays compressed into a single file. Then load the file as np arrays and use torch.from_numpy to convert to tensors.
https://stackoverflow.com/questions/57643066/
Loading custom dataset of images using PyTorch
I'm using the coil-100 dataset which has images of 100 objects, 72 images per object taken from a fixed camera by turning the object 5 degrees per image. Following is the folder structure I'm using: data/train/obj1/obj01_0.png, obj01_5.png ... obj01_355.png . . data/train/obj85/obj85_0.png, obj85_5.png ... obj85_355.png . . data/test/obj86/obj86_0.ong, obj86_5.png ... obj86_355.png . . data/test/obj100/obj100_0.ong, obj100_5.png ... obj100_355.png I have used the imageloader and dataloader classes. The train and test datasets loaded properly and I can print the class names. train_path = 'data/train/' test_path = 'data/test/' data_transforms = { transforms.Compose([ transforms.Resize(224, 224), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)) ]) } train_data = torchvision.datasets.ImageFolder( root=train_path, transform= data_transforms ) test_data = torchvision.datasets.ImageFolder( root = test_path, transform = data_transforms ) train_loader = torch.utils.data.DataLoader( train_data, batch_size=None, num_workers=1, shuffle=False ) test_loader = torch.utils.data.DataLoader( test_data, batch_size=None, num_workers=1, shuffle=False ) print(len(train_data)) print(len(test_data)) classes = train_data.class_to_idx print("detected classes: ", classes) In my model I wish to pass every image through pretrained resnet and make a dataset from the output of resnet to feed into a biderectional LSTM. For which I need to access the images by classname and index. for ex. pre_resnet_train_data['obj01'][0] should be obj01_0.png and post_resnet_train_data['obj01'][0] should be the resnet output of obj01_0.png and so on. I'm a beginner in Pytorch and for the past 2 days, I have read many tutorials and stackoverflow questions about creating a custom dataset class but couldn't figure out how to achieve what I want. please help!
Assuming you only plan on running resent on the images once and save the output for later use, I suggest you write your own data set, derived from ImageFolder. Save each resnet output at the same location as the image file with .pth extension. class MyDataset(torchvision.datasets.ImageFolder): def __init__(self, root, transform): super(MyDataset, self).__init__(root, transform) def __getitem__(self, index): # override ImageFolder's method """ Args: index (int): Index Returns: tuple: (sample, resnet, target) where target is class_index of the target class. """ path, target = self.samples[index] sample = self.loader(path) if self.transform is not None: sample = self.transform(sample) if self.target_transform is not None: target = self.target_transform(target) # this is where you load your resnet data resnet_path = os.path.join(os.path.splitext(path)[0], '.pth') # replace image extension with .pth resnet = torch.load(resnet_path) # load the stored features return sample, resnet, target
https://stackoverflow.com/questions/57648945/
Finetune PyTorch model after training fc layers
I am trying to do Transfer Learning using PyTorch. I wan to train fc layers first and then to finetune the whole network. Unfortunately after training fc layers and then passing my network to finetune, I am losing the accuracy that was acquired in the first training. Is this an expected behaviour or am I doing something wrong here? Here is the code: model = torchvision.models.resnet50(pretrained=True) for param in model.parameters(): param.requires_grad = False num_ftrs = model.fc.in_features model.fc = nn.Linear(num_ftrs, 4) model = model.to(device) criterion = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=0.001) model = trainer.fit_model(dataloader, model, criterion, optimizer, num_epochs=10) # fit model is basic PyTorch training function found here: https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html#convnet-as-fixed-feature-extractor The only difference is that scheduler is an optional param. for param in model.parameters(): param.requires_grad = True torch.cuda.empty_cache() exp_lr_scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1) # Here I am finetuning the model model_ft = trainer.fit_model( dataloader, model, criterion, optimizer, scheduler=exp_lr_scheduler, num_epochs=10 ) Am I missing something here or should I just train the model once?
That is something that can happen when performing transfer learning called catastrophic forgetting. Basically, you update your pretrained weights too much and you 'forget' what was previously learned. This can happen notably if your learning rate is too high. I would suggest trying at first a lower learning rate, or using diffentiable learning rate (different learning rate for the head of the network and the pretrained part, so that you can have a higher learning rate on the fc layers than for the rest of the network).
https://stackoverflow.com/questions/57655007/
Implementing Batch for Image Segmentation
I wrote a Python 3.5 script for doing street segmentation. Since I'm new in Image Segementation, I did not use predefined dataloaders from pytorch, instead I wrote them by my self (for better understanding). Until now I only use a batch size of 1. Now I want to generalize this for arbitrary batch sizes. This is a snippet of my Dataloader: def augment_data(batch_size): # [...] defining some paths and data transformation (including ToTensor() function) # The images are named by numbers (Frame numbers), this allows me to find the correct label image for a given input image. all_input_image_paths = {int(elem.split('\\')[-1].split('.')[0]) : elem for idx, elem in enumerate(glob.glob(input_dir + "*"))} all_label_image_paths = {int(elem.split('\\')[-1].split('.')[0]) : elem for idx, elem in enumerate(glob.glob(label_dir + "*"))} dataloader = {"train":[], "val":[]} all_samples = [] img_counter = 0 for key, value in all_input_image_paths.items(): input_img = Image.open(all_input_image_paths[key]) label_img = Image.open(all_label_image_paths[key]) # Here I use my own augmentation function which crops the input and label on the same position and do other things. # We get a list of new augmented data augmented_images = generate_augmented_images(input_img, label_img) for elem in augmented_images: input_as_tensor = data_transforms['norm'](elem[0]) label_as_tensor = data_transforms['val'](elem[1]) input_as_tensor.unsqueeze_(0) label_as_tensor.unsqueeze_(0) is_training_data = random.uniform(0.0, 1.0) if is_training_data &lt;= 0.7: dataloader["train"].append([input_as_tensor, label_as_tensor]) else: dataloader["val"].append([input_as_tensor, label_as_tensor]) img_counter += 1 shuffle(dataloader["train"]) shuffle(dataloader["val"]) dataloader_batched = {"train":[], "val":[]} # Here I group my data to a given batch size for elem in dataloader["train"]: batch = [] for i in range(batch_size): batch.append(elem) dataloader_batched["train"].append(batch) for elem in dataloader["val"]: batch = [] for i in range(batch_size): batch.append(elem) dataloader_batched["val"].append(batch) return dataloader_batched This is a snippet of my training method with batch size 1: while epoch &lt;= num_epochs: # Each epoch has a training and validation phase for phase in ['train', 'val']: if phase == 'train': scheduler.step(3) model.train() # Set model to training mode else: model.eval() # Set model to evaluate mode running_loss = 0.0 counter = 0 # Iterate over data. for inputs, labels in dataloaders[phase]: counter += 1 max_num = len(dataloaders[phase]) inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward # track history if only in train with torch.set_grad_enabled(phase == 'train'): outputs = model(inputs) loss = criterion(outputs, labels) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() # statistics running_loss += loss.item() * inputs.size(0) epoch_loss = running_loss / dataset_sizes[phase] If I execute this, I get of course the error: for inputs, labels in dataloaders[phase]: ValueError: not enough values to unpack (expected 2, got 1) I understand why, because now I have a list of images and not only an input and label image as before. So guessed I need a second for loop which iterates over these batches. So I tried this: # Iterate over data. for elem in dataloaders[phase]: for inputs, labels in elem: counter += 1 max_num = len(dataloaders[phase]) inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients optimizer.zero_grad() # forward # track history if only in train with torch.set_grad_enabled(phase == 'train'): outputs = model(inputs) # _, preds = torch.max(outputs, 1) loss = criterion(outputs, labels) # backward + optimize only if in training phase if phase == 'train': loss.backward() optimizer.step() But for me it looks like the optimization step (back-prop) is only applied on the last image of the batch. Is that true? And if so, how can I fix this? I guess if I indent the with-Block, then I get again a batch size 1 optimization. Thanks in advance
But for me it looks like the optimization step (back-prop) is only applied on the last image of the batch. It should not apply only based on the last image. It should apply based on the batch size. If you set bs=2 and it should apply to the batch of two images. Optimization step actually will update the params of your network. Backprop is a fancy name for PyTorch autograd system that computes the first order gradients.
https://stackoverflow.com/questions/57657950/
How can I combine and overlap two tensors?
I have two tensors that should together overlap each other to form a larger tensor. To illustrate: a = torch.Tensor([[1, 2, 3], [1, 2, 3]]) b = torch.Tensor([[5, 6, 7], [5, 6, 7]]) a = [[1 2 3] b = [[5 6 7] [1 2 3]] [5 6 7]] I want to combine the two tensors and have them partially overlap by a single column, with the average being taken for those elements that overlap. e.g. result = [[1 2 4 6 7] [1 2 4 6 7]] The first two columns are the first two columns of 'a'. The last two columns are the last two columns of 'b'. The middle column is the average of 'a's last column and 'b's first column. I know how to merge two tensors side by side or in a new dimension. But doing this eludes me. Can anyone help?
This is not a trivial operation, and this solution is not very trivial or intuitive either. Looking at result with shape=(2, 5), you can think of a and b as two 2x3 patches of result taken with stride=2. Like this illustration: We can use pytorch's unfold to "recover" the green (a) and blue (b) patches from result ("recover" up to the averaged values): from torch.nn import functional as nnf recovered = nnf.unfold(result, kernel_size=(2,3), stride=2) The result is: tensor([[[1., 4.], [2., 6.], [4., 7.], [1., 4.], [2., 6.], [4., 7.]]]) The patches were recovered (as column vectors). Now that we understand how to get a and b from result, we can use fold to perform the "inverse" operation and go from b and b to result. First, we need to flatten concatenate a and b to the shape fold expects (mimicking the output of unfold, two "flatten" patches of 3x2 elements): uf = torch.cat((a.view(1, 6, 1), b.view(1, 6, 1)), dim=2) We can now "fold" the patches raw = nnf.fold(uf, (2,5), kernel_size=(2,3), stride=2) We are not there yet, when there are overlapping elements fold sums up the overlapping elements, resulting with tensor([[[[1., 2., 8., 6., 7.], [1., 2., 8., 6., 7.]]]]) To count how many elements were summed for each entry in result, we can simply "fold" an all ones tensor counter = nnf.fold(torch.ones_like(uf), (2, 5), kernel_size=(2, 3), stride=2) And finally, we can recover result: result = raw / counter tensor([[[[1., 2., 4., 6., 7.], [1., 2., 4., 6., 7.]]]]) Piece of cake.
https://stackoverflow.com/questions/57666249/
How to create torch.tensor object and to update only some of its elements?
Let's say I want to create torch.tensor object of size [2,3] filled with random elements, and I intend to use this matrix in the network and optimize it's values. However, I want to update only some of the the values in the matrix. I know that it can be done for a tensor by setting up parameter requires_grad To True or False. However, the following code z = torch.rand([2,3], requires_grad=True) z[-1][-1].requires_grad=False does not work as expected RuntimeError: you can only change requires_grad flags of leaf variables. If you want to use a computed variable in a subgraph that doesn't require differentiation use var_no_grad = var.detach(). How to fix this RuntimeError? How to initialize torch tensor and then define which elements there would have requires_grad =True? If I write code in a similar manner: z = torch.rand([2,3], requires_grad=False) z[-1][-1].requires_grad=True There will be no error, but no change of the requires_grad as well.
It does not really make much sense to have a single tensor which requires_grad for only part of its entries. Why not have two separate tensors one that us updated (requires_grad=True) and another one fixed (requires_grad=False)? You can then merge them for computational ease: fixed = torch.rand([2, 3], require_grad=False) upd = torch.rand([2, 3], require_grad=True) mask = torch.tensor([[0, 1, 0], [1, 0, 1]], require_grad=False) # how to combine the two # combine them using fixed "mask": z = mask * fixed + (1-mask) * upd You can obviously have other methods of combining fixed and upd other than using a binary mask. For example, if upd occupies the first two columns of z and fixed the rest, then: fixed = torch.rand([2, 1], require_grad=False) upd = torch.rand([2, 2], require_grad=True) # combine them using concatination z = torch.cat((upd, fixed),dim=1) Or, if you know the indices fidx = torch.tensor([0, 2], dtype=torch.long) uidx = torch.tensor([1, 3, 4, 5], dtype=torch.long) fixed = torch.rand([2,], require_grad=False) upd = torch.rand([4,], require_grad=True) z = torch.empty([2, 3]) z[fidx] = fixed z[uidx] = upd
https://stackoverflow.com/questions/57668368/
Trouble installing PyTorch for CUDA 9.0
I am trying to install PyTorch for CUDA 9.0 (Ubuntu 18.04 LTS). I followed instructions as per official documentation, which says Download the whl file with the desired version from the following html page: https://download.pytorch.org/whl/cu90/torch_stable.html $ pip install [downloaded file] But above link is broken, I am unable to open it.
It turns out https://download.pytorch.org/whl/cu90/torch_stable.html is a list of &lt;a href&gt; tags, which we can see by going into the source from the browser. We can then download the appropriate version and install via pip install [downloaded file].
https://stackoverflow.com/questions/57668538/
How to display more than 10 images in Tensorboard?
I noticed that it doesn't matter how many image I save to the tensorboard log file, tensorboard will only ever show 10 of them (per tag). How can we increase the number of images or at least select which ones are displayed? To reproduce what I mean run following MCVE: import torch from torch.utils.tensorboard import SummaryWriter tb = SummaryWriter(comment="test") for k in range(100): # create an image with some funny pattern b = [n for (n, c) in enumerate(bin(k)) if c == '1'] img = torch.zeros((1,10,10)) img[0, b, :] = 0.5 img =img + img.permute([0, 2, 1]) # add the image to the tensorboard file tb.add_image(tag="test", img_tensor=img, global_step=k) This creates a folder runs in which the data is saved. From the same folder execute tensorboard --logdir runs, open the browser and go to localhost:6006 (or replace 6006 with whatever port tensorboard happens to display after starting it). Then go to the tab called "images" and move the slider above the grayscale image. In my case it only displayed the images from steps k = 3, 20, 24, 32, 37, 49, 52, 53, 67, 78 which isn't even an nice even spacing, but looks pretty random. I'd prefer to have see more than just 10 of the images I saved, and have a more even spacing of number of steps between each image displayed. How can I achieve this? EDIT: I just found the option --samples_per_plugin and tried tensorboard --logdir runs --samples_per_plugin "images=100". This indeed increased the number of images, but it only showed the images from steps k = 0,1,2,3....,78, but none from above 78.
You probably have to wait a little bit longer to wait for all the data to be loaded, but this is indeed the correct solution, see --help: --samples_per_plugin: An optional comma separated list of plugin_name=num_samples pairs to explicitly specify how many samples to keep per tag for that plugin. For unspecified plugins, TensorBoard randomly downsamples logged summaries to reasonable values to prevent out-of-memory errors for long running jobs. This flag allows fine control over that downsampling. Note that 0 means keep all samples of that type. For instance, "scalars=500,images=0" keeps 500 scalars and all images. Most users should not need to set this flag. (default: '') Regarding the random samples: This is also true, there is some sort of randomness to it, from the the FAQ: Is my data being downsampled? Am I really seeing all the data? TensorBoard uses reservoir sampling to downsample your data so that it can be loaded into RAM. You can modify the number of elements it will keep per tag in tensorboard/backend/application.py.
https://stackoverflow.com/questions/57669234/
Neural network from scratch - predict single example
Here is a neural network I've modified from Coursera Deep Learning Specialization to train on a dataset containing a flattened array of training data : %reset -s -f import numpy as np import math def sigmoid(x): return 1 / (1 + np.exp(-x)) def initialize_with_zeros(dim): w = np.zeros(shape=(dim, 1)) b = 0 return w, b X = np.array([[1,1,1,1],[1,0,1,0] , [1,1,1,0], [0,0,0,0], [0,1,0,0], [0,1,0,1]]) Y = np.array([[1,0,1,1,1,1]]) X = X.reshape(X.shape[0], -1).T Y = Y.reshape(Y.shape[0], -1).T print('X shape' , X.shape) print('Y shape' , Y.shape) b = 1 w, b = initialize_with_zeros(4) def propagate(w, b, X, Y) : m = X.shape[1] A = sigmoid(np.dot(w.T, X) + b) # compute activation cost = (- 1 / m) * np.sum(Y * np.log(A) + (1 - Y) * (np.log(1 - A))) # compute cost dw = (1./m)*np.dot(X,((A-Y).T)) db = (1./m)*np.sum(A-Y, axis=1) cost = np.squeeze(cost) grads = {"dw": dw, "db": db} return grads, cost propagate(w , b , X , Y) learning_rate = .001 costs = [] def optimize(w , b, X , Y) : for i in range(2): grads, cost = propagate(w=w, b=b, X=X, Y=Y) dw = grads["dw"] db = grads["db"] w = w - learning_rate*dw b = b - learning_rate*db if i % 100 == 0: costs.append(cost) return w , b w , b = optimize(w , b , X , Y) def predict(w, b, X): m = 6 Y_prediction = np.zeros((1,m)) # w = w.reshape(X.shape[0], 1) A = sigmoid(np.dot(w.T, X) + b) for i in range(A.shape[1]): if A[0, i] &gt;= 0.5: Y_prediction[0, i] = 1 else: Y_prediction[0, i] = 0 return Y_prediction predict(w , b, X) This works as expected but I'm struggling to predict a single example. If I use : predict(w , b, X[0]) returns error : ValueError: shapes (6,4) and (6,) not aligned: 4 (dim 1) != 6 (dim 0) How to re-arrange matrix operation in order to predict a single instance ?
Try predict(w, b, X[:1]) It seems like you predict function expects X to be 2-d, when passing only one X it should have a singleton second dimension (i.e., shape=(6,1)) rather than being a single dimension (i.e., shape=(6,)).
https://stackoverflow.com/questions/57688191/
Ground Truth Image to One Hot Encoded Array (Semantic Segmentation)
I'm creating my own Dataset for People and Street Segmentation. Below, you see a labled Ground Truth (GT) Image. In the past I did a simple Regression between the model output and the GT Image (in the past I only used Streets). Now I read, Cross Entropy Loss is more common in that case. Since, my GT and also the model output Image has the same width w and height h as the input image, I have to create an array of size h x w x c, where c is the number of classes (in my case 3, background, street, people). I think, this is called One-Hot-Encoded Array. I solved this as follows: for height in range(len(img_as_np_array)): for width in range(len(img_as_np_array[0])): temp = np.zeros(classes) if get_class(img_as_np_array[height,width]) == 1: temp[1] = 1 one_hot_label[height,width] = temp if get_class(img_as_np_array[height,width]) == 2: temp[2] = 1 one_hot_label[height,width] = temp where the method get_class(channels) decides the pixel class by the color of the pixel. def get_class(channels): threshold = 40 # Class 1 corresponds to streets, roads if channels[0] in np.arange(243-threshold,243+threshold,1) and \ channels[1] in np.arange(169-threshold,169+threshold,1) and \ channels[2] in np.arange(0,threshold,1): return 1 # Class 2 corresponds to people if channels[0] in np.arange(0,threshold,1) and \ channels[1] in np.arange(163-threshold,163+threshold,1) and \ channels[2] in np.arange(232-threshold,232+threshold,1): return 2 # Class 0 corresponds to background respectively other things return 0 I have two questions: My approach is very slow (about 3 minutes for a Full HD Image), is there a way to speed this up? I noticed that the colors differ in the sense of channel values. For example, orange should be [243,169,0] (RGB), but I found entries like this [206,172,8] or even this [207,176,24] could that happen, because I store my labels as jpg? Is there a better way to find the orange and blue pixels than my idea above with the threshold? EDIT: I solved the first question by my self. This takes 2 or 3 seconds for an Full HD Image: threshold = 40 class_1_shape_cond_1 = (img_as_array[:, :, 0] &gt;= 243 - threshold) * (img_as_array[:, :, 0] &lt;= 243 + threshold) class_1_shape_cond_2 = (img_as_array[:, :, 1] &gt;= 171 - threshold) * (img_as_array[:, :, 1] &lt;= 171 + threshold) class_1_shape_cond_3 = (img_as_array[:, :, 2] &gt;= 0) * (img_as_array[:, :, 2] &lt;= threshold) class_1_shape = (class_1_shape_cond_1 * class_1_shape_cond_2 * class_1_shape_cond_3) Then I do the same for class 2 and for class 3 (everything else) I can do: class_3_shape = 1 - (class_1_shape + class_2_shape) After that I have to adjust the type with: class_1_shape = class_1_shape.astype(np.uint8) class_2_shape = class_2_shape.astype(np.uint8) class_3_shape = class_3_shape.astype(np.uint8) Question 2 is still an open.
Do NOT save labels as JPEG images! jpeg is a lossy compression method - that is, it is designed to save images using fewer bits even if it changes a bit the pixel values as long as it &quot;looks good&quot; to a human observer. This is NOT the case for training labels stored as images! You cannot afford inaccuracies in the labels. You must use a lossless compression method, e.g., png. Better still, store your labels as indexed RGB images to begin with and save you all the trouble of inferring the discrete labels from the RGB values.
https://stackoverflow.com/questions/57699309/
Being confused about tensor dimensions in pytorch
I'm new to pytorch and machine learning in general and I'm trying to create a simple convolutional neural net that classifies the MNIST handwritten digits. Unfortunately when I'm trying to train it, I get the following error: ValueError: Expected input batch_size (288) to match target batch_size (64). Here is the neural network code. from torch import nn from torch.nn.functional import relu, log_softmax class MNIST_SimpleConv(nn.Module): def __init__(self): super(MNIST_SimpleConv, self).__init__() self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1) self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=1) self.pool1 = nn.MaxPool2d(2, 2) self.dense1 = nn.Linear(4*4*64, 100) self.dense2 = nn.Linear(100, 10) def forward(self, x): x = relu(self.conv1(x)) x = relu(self.conv2(x)) x = self.pool1(x) x = x.view(-1, 4*4*64) x = relu(self.dense1(x)) return log_softmax(self.dense2(x), dim=1) And the training code is as follows: from nets.conv import MNIST_SimpleConv from torchvision import datasets, transforms from torch.utils.data import DataLoader from torch.nn.functional import nll_loss import torch.optim as optim import torch from torch import nn MNIST_ROOT = "data/MNIST" #prepare dataset mnist_train_ds = datasets.ImageFolder(root=MNIST_ROOT+"/train", transform=transforms.Compose([ transforms.ToTensor()])) mnist_test_ds = datasets.ImageFolder(root=MNIST_ROOT+"/test", transform=transforms.Compose([ transforms.ToTensor()])) mnist_train = DataLoader(mnist_train_ds, batch_size=64, shuffle=True, num_workers=6) mnist_test = DataLoader(mnist_test_ds, batch_size=64, shuffle=True, num_workers=6) criterion = nn.CrossEntropyLoss() def train(model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader, 0): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = MNIST_SimpleConv().to(device) optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5) for epoch in range(1, 10): train(model, device, mnist_train , optimizer, epoch) So far I have investigated how the dimensions of 'x' change while x is forwarded through the network. Input: torch.Size([64, 3, 28, 28]) After x = relu(self.conv1(x)): torch.Size([64, 32, 26, 26]) After x = relu(self.conv2(x)): torch.Size([64, 64, 24, 24]) After x = self.pool1(x): torch.Size([64, 64, 12, 12]) After x = x.view(-1, 4*4*64) torch.Size([576, 1024]) After x = relu(self.dense1(x)) torch.Size([576, 100]) After x = log_softmax(self.dense2(x), dim=1) torch.Size([576, 10]) The error is probably caused by x = x.view(-1, 4*4*64) for some reason producing a tensor with the shape [576, 1024] instead of [64, 1024]. (If I understand this correctly the first dimension should be equal to the batch size which in my case is 64.) What am I doing wrong?
Passing a value of -1 to any dimension in view means that value of that particular dimension will be determined by other dimensions. for example: x = torch.rand(1,10) # x.shape = [1,10] x = x.view(-1, 5) # x.shape = [2, 5] In your case, if you want to merge all dimensions of output of pool1, then it should be something like this: x = x.view(-1, 64*12,*12) # x.shape = [64, 9216] Also, we have to update the input channels for self.dense1 in this case: self.dense1 = nn.Linear(64*12*12, 100) However, one thing we need to make sure is that output dimensions of self.pool1 are always going to be batch_size x 64 x 12 x 12, specifically the last two dimensions should stay 12 for the whole process. This can be made sure by fixing the input image dimensions across dataset.
https://stackoverflow.com/questions/57700365/
How do I pass a keyword argument to the forward used by a pre-forward hook?
Given a torch's nn.Module with a pre-forward hook, e.g. import torch import torch.nn as nn class NeoEmbeddings(nn.Embedding): def __init__(self, num_embeddings:int, embedding_dim:int, padding_idx=-1): super().__init__(num_embeddings, embedding_dim, padding_idx) self.register_forward_pre_hook(self.neo_genesis) @staticmethod def neo_genesis(self, input, higgs_bosson=0): if higgs_bosson: input = input + higgs_bosson return input It's possible to let an input tensor go through some manipulation before going to the actual forward() function, e.g. &gt;&gt;&gt; x = NeoEmbeddings(10, 5, 1) &gt;&gt;&gt; x.forward(torch.tensor([0,2,5,8])) tensor([[-1.6449, 0.5832, -0.0165, -1.3329, 0.6878], [-0.3262, 0.5844, 0.6917, 0.1268, 2.1363], [ 1.0772, 0.1748, -0.7131, 0.7405, 1.5733], [ 0.7651, 0.4619, 0.4388, -0.2752, -0.3018]], grad_fn=&lt;EmbeddingBackward&gt;) &gt;&gt;&gt; print(x._forward_pre_hooks) OrderedDict([(25, &lt;function NeoEmbeddings.neo_genesis at 0x1208d10d0&gt;)]) How could we pass the arguments (*args or **kwargs) that the pre-forward hook needs but not accepted by the default forward() function? Without modification/overriding the forward() function, this is not possible: &gt;&gt;&gt; x = NeoEmbeddings(10, 5, 1) &gt;&gt;&gt; x.forward(torch.tensor([0,2,5,8]), higgs_bosson=2) ---------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-102-8705a40a3cc2&gt; in &lt;module&gt; 1 x = NeoEmbeddings(10, 5, 1) ----&gt; 2 x.forward(torch.tensor([0,2,5,8]), higgs_bosson=2) TypeError: forward() got an unexpected keyword argument 'higgs_bosson'
Torchscript incompatible (as of 1.2.0) First of all, your example torch.nn.Module has some minor mistakes (probably by an accident). Secondly, you can pass anything to forward and register_forward_pre_hook will just get the argument that will be passed your your torch.nn.Module (be it layer or model or anything) else. You indeed cannot do it without modifying forward call, but why would you want to avoid that? You could simply forward the arguments to base function as can be seen below: import torch class NeoEmbeddings(torch.nn.Embedding): def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx=-1): super().__init__(num_embeddings, embedding_dim, padding_idx) self.register_forward_pre_hook(NeoEmbeddings.neo_genesis) # First argument should be named something like module, as that's what # you are registering this hook to @staticmethod def neo_genesis(module, inputs): # No need for self as first argument net_input, higgs_bosson = inputs # Simply unpack tuple here return net_input def forward(self, inputs, higgs_bosson): # Do whatever you want here with both arguments, you can ignore # higgs_bosson if it's only needed in the hook as done here return super().forward(inputs) if __name__ == "__main__": x = NeoEmbeddings(10, 5, 1) # You should call () instead of forward so the hooks register appropriately print(x(torch.tensor([0, 2, 5, 8]), 1)) You can't do it in more succinct way, but the limitation is base's class forward method, not the hook itself (and tbh I wouldn't want it to be more succinct as it would become unreadable IMO). Torchscript compatible If you want to use torchscript (tested on 1.2.0) you could use composition instead of inheritance. All you have to change are merely two lines and your code may look something like this: import torch # Inherit from Module and register embedding as submodule class NeoEmbeddings(torch.nn.Module): def __init__(self, num_embeddings: int, embedding_dim: int, padding_idx=-1): super().__init__() # Just use it as a container inside your own class self._embedding = torch.nn.Embedding(num_embeddings, embedding_dim, padding_idx) self.register_forward_pre_hook(NeoEmbeddings.neo_genesis) @staticmethod def neo_genesis(module, inputs): net_input, higgs_bosson = inputs return net_input def forward(self, inputs: torch.Tensor, higgs_bosson: torch.Tensor): return self._embedding(inputs) if __name__ == "__main__": x = torch.jit.script(NeoEmbeddings(10, 5, 1)) # All arguments must be tensors in torchscript print(x(torch.tensor([0, 2, 5, 8]), torch.tensor([1])))
https://stackoverflow.com/questions/57703808/
plot function does not plot curves just plotted legend in PyCharm
I am doing some homework about image classification using PyTorch. For this purpose I have visited the following link: https://github.com/Bjarten/early-stopping-pytorch/blob/master/MNIST_Early_Stopping_example.ipynb and obtained some results like this related to training losses and validation losses [ 1/10] train_loss: 1.56952 valid_loss: 1.54557 Validation loss decreased (inf --&gt; 1.545571). Saving model ... [ 2/10] train_loss: 1.52198 valid_loss: 1.50932 Validation loss decreased (1.545571 --&gt; 1.509324). Saving model ... [ 3/10] train_loss: 1.48958 valid_loss: 1.48514 Validation loss decreased (1.509324 --&gt; 1.485136). Saving model ... [ 4/10] train_loss: 1.46960 valid_loss: 1.46938 Validation loss decreased (1.485136 --&gt; 1.469381). Saving model ... But the problem is that whenever I try to plot loss curves it does not show anything. my plotted figure I would expect my curve to be like the one in this picture. Here is the code that I used to draw this curve: # visualize the loss as the network trained fig = plt.figure(figsize=(10, 8)) plt.plot(range(1, len(train_loss) + 1), train_loss, label='Training Loss') plt.plot(range(1, len(valid_loss) + 1), valid_loss, label='Validation Loss') # find position of lowest validation loss minposs = valid_loss.index(min(valid_loss)) + 1 plt.axvline(minposs, linestyle='--', color='r', label='Early Stopping Checkpoint') plt.xlabel('epochs') plt.ylabel('loss') plt.ylim(0, 0.5) # consistent scale plt.xlim(0, len(train_loss) + 1) # consistent scale plt.grid(True) plt.legend() plt.tight_layout() plt.show() fig.savefig('loss_plot.png', bbox_inches='tight') Here is the value of length of the training loss and the testing loss len of train loss: 1 train loss :[1.6059992909431458]
Since len(train_loss) == 1 and train_loss = [1.6059992909431458], your plot is exactly the same as if you called plt.plot(range(1, 2), [1.6059992909431458]), which, as you can check, is empty (this is because plt.plot draws lines between data points, and as there is a single data point, there can be no line drawn). You can change plt.plot to plt.scatter in order to see that single data point. So this problem has nothing to do with plotting really, and you should rather figure out why your algorithm only runs for a single epoch and troubleshoot that, rather than plotting.
https://stackoverflow.com/questions/57707154/
using transforms.LinearTransformation to apply whitening in PyTorch
I need to apply ZCA whitening in PyTorch. I think I have found a way this can be done by using transforms.LinearTransformation and I have found a test in the PyTorch repo which gives some insight into how this is done (see final code block or link below) https://github.com/pytorch/vision/blob/master/test/test_transforms.py I am struggling to work out how I apply something like this myself. Currently I have transforms along the lines of: transform_test = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(np.array([125.3, 123.0, 113.9]) / 255.0, np.array([63.0, 62.1, 66.7]) / 255.0), ]) The documents say they way to use LinearTransformation is as follows: torchvision.transforms.LinearTransformation(transformation_matrix, mean_vector) whitening transformation: Suppose X is a column vector zero-centered data. Then compute the data covariance matrix [D x D] with torch.mm(X.t(), X), perform SVD on this matrix and pass it as transformation_matrix. I can see from the tests I linked above and copied below that they are using torch.mm to calculate what they call a principal_components: def test_linear_transformation(self): num_samples = 1000 x = torch.randn(num_samples, 3, 10, 10) flat_x = x.view(x.size(0), x.size(1) * x.size(2) * x.size(3)) # compute principal components sigma = torch.mm(flat_x.t(), flat_x) / flat_x.size(0) u, s, _ = np.linalg.svd(sigma.numpy()) zca_epsilon = 1e-10 # avoid division by 0 d = torch.Tensor(np.diag(1. / np.sqrt(s + zca_epsilon))) u = torch.Tensor(u) principal_components = torch.mm(torch.mm(u, d), u.t()) mean_vector = (torch.sum(flat_x, dim=0) / flat_x.size(0)) # initialize whitening matrix whitening = transforms.LinearTransformation(principal_components, mean_vector) # estimate covariance and mean using weak law of large number num_features = flat_x.size(1) cov = 0.0 mean = 0.0 for i in x: xwhite = whitening(i) xwhite = xwhite.view(1, -1).numpy() cov += np.dot(xwhite, xwhite.T) / num_features mean += np.sum(xwhite) / num_features # if rtol for std = 1e-3 then rtol for cov = 2e-3 as std**2 = cov assert np.allclose(cov / num_samples, np.identity(1), rtol=2e-3), "cov not close to 1" assert np.allclose(mean / num_samples, 0, rtol=1e-3), "mean not close to 0" # Checking if LinearTransformation can be printed as string whitening.__repr__() How do I apply something like this? do I use it where I define my transforms or apply it in my training loop where I am iterating over my training loop? Thanks in advance
ZCA whitening is typically a preprocessing step, like center-reduction, which basically aims at making your data more NN-friendly (additional info below). As such, it is supposed to be applied once, right before training. So right before you starts training your model with a given dataset X, compute the whitened dataset Z, which is simply the multiplication of X with the ZCA matrix W_zca that you can learn to compute here. Then train your model on the whitened dataset. Finally, you should have something that looks like this class MyModule(torch.nn.Module): def __init__(self): super(MyModule,self).__init__() # Feel free to use something more useful than a simple linear layer self._network = torch.nn.Linear(...) # Do your stuff ... def fit(self, inputs, labels): """ Trains the model to predict the right label for a given input """ # Compute the whitening matrix and inputs self._zca_mat = compute_zca(inputs) whitened_inputs = torch.mm(self._zca_mat, inputs) # Apply training on the whitened data outputs = self._network(whitened_inputs) loss = torch.nn.MSEloss()(outputs, labels) loss.backward() optimizer.step() def forward(self, input): # You always need to apply the zca transform before forwarding, # because your network has been trained with whitened data whitened_input = torch.mm(self._zca_mat, input) predicted_label = self._network.forward(whitened_input) return predicted_label Additional info Whitening your data means decorrelating its dimensions so that the correlation matrix of the whitened data is the identity matrix. It is a rotation-scaling operation (thus linear), and there are actually an infinity of possible ZCA transforms. To understand the maths behind ZCA, read this
https://stackoverflow.com/questions/57709758/
Understanding deep Markov model code on pyro
I am going through an a deep Markov model code given on pyro's website: https://pyro.ai/examples/dmm.html I am really confused about combiner module that they've implemented. You an find combiner module on line 104 on this GitHub page: https://github.com/pyro-ppl/pyro/blob/dev/examples/dmm/dmm.py The article they are following is: https://arxiv.org/abs/1609.09869 They explain combiner module in section 4 (Structured inference networks). I am really confused about why they are doing three linear transformations in the code starting from line 104 on GitHub. Aren't they just suppose to use RNN to produce the distribution or am I missing something? Insights would be appreciated.
The Combiner module implementation corresponds to the formulas described at the bottom of page 4, "Combiner Function for Structured Approximations (for DKS)". mu_t is loc and sigma_t**2 is scale. The RNN state is used to parameterize the distribution, but that distribution is parameterized by two variables. These variables are extracted from the RNN state via the transformations in question.
https://stackoverflow.com/questions/57710588/
Encounter the RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation
I'm getting the following error when calling .backward(): Encounter the RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation Here's the code: for i, j, k in zip(X, Y, Z): A[:, i, j] = A[:, i, j] + k I've tried .clone(), torch.add(), and so on. Please help!
After the comments I'm a bit confused about what you want to accomplish. The code you gave gives me an error using the dimensions you provided in the comments Traceback (most recent call last): A[:, i, j] = A[:, i, j] + k RuntimeError: The size of tensor a (32) must match the size of tensor b (200) at non-singleton dimension 0 But here's what I think you want to do, please correct me in the comments if this is wrong... Given tensors X, Y, and Z, each entry of X, Y, and Z correspond to a coordinate (x,y) and a value z. What you want is to add z to A at coordinate (x,y). For most cases the batch dimension is kept independent, although its not clear that's the case in the code you posted. For now that's what I'll assume you want to do. For example lets say A contains all zeros and has shape 3x4x5 and X,Y are shape 3x3 and Z is shape 3x3x1. For this example let's assume A contains all zeros to start, and X, Y, and Z have the following values X = tensor([[1, 2, 3], [1, 2, 3], [2, 2, 2]]) Y = tensor([[1, 2, 3], [1, 2, 3], [1, 1, 1]]) Z = tensor([[[0.1], [0.2], [0.3]], [[0.4], [0.5], [0.6]], [[0.7], [0.8], [0.9]]]) Then we would expect A to have the following values after the operation A = tensor([[[0, 0, 0, 0, 0], [0, 0.1, 0, 0, 0], [0, 0, 0.2, 0, 0], [0, 0, 0, 0.3, 0]], [[0, 0, 0, 0, 0], [0, 0.4, 0, 0, 0], [0, 0, 0.5, 0, 0], [0, 0, 0, 0.6, 0]], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 2.4, 0, 0, 0], [0, 0, 0, 0, 0]]]) In order to accomplish this we can make use to the index_add function which allows us to add to a list of indices. Since this only supports 1-dimensional operations we first need to convert X,Y to a linear index for flattened tensor A. Afterwards we can un-flatten to the original shape. layer_size = A.shape[1] * A.shape[2] index_offset = torch.arange(0, A.shape[0] * layer_size, layer_size).unsqueeze(1) indices = (X * A.shape[2] + Y) + index_offset A = A.view(-1).index_add(0, indices.view(-1), Z.view(-1)).view(A.shape)
https://stackoverflow.com/questions/57717362/
What is the PyTorch equivalent to Numpy's linalg.solve?
I have looked it up and there are some posts, for example this one, that suggest to use torch.gesv but I can't seem to find it in the PyTorch documentation.
Pytorch provides the function torch.solve, which behaves like numpy.linalg.solve. It will output the solution of the the linear system and the LU factorization that has been used to compute it. More information and example codes here.
https://stackoverflow.com/questions/57721451/
How to change input type(image) to list or array when using PyTorch tutorial code
I have searched the code that uses list or array input data for training DQN code. But I have could not find any code. Currently, I reference the reinforcement learning tutorial(DQN) of Pytorch. However, this code uses image input data. I want to know how to change the image input data to list or array input data. (I need help to resolve my research that uses list input data. List input data shape is 1 by 9. )
In PyTorch, we deal with tensors. Images, text, even sounds can be transformed to tensors and then PyTorch models can learn on the data. In PyTorch image classifier examples, you often see something like this, to transform images to tensors: train_transform = transforms.Compose([ transforms.Resize(x), ... transforms.ToTensor() ]) If your input is a numpy array x, you can convert it to a tensor like this: torch.from_numpy(x) You also have to pay attention to tensor dimensions, your input data needs to match what the model expects in the first layer.
https://stackoverflow.com/questions/57725029/
How do I get the value of a tensor in PyTorch?
Printing a tensor x gives: &gt;&gt;&gt; x = torch.tensor([3]) &gt;&gt;&gt; print(x) tensor([3]) Indexing x.data gives: &gt;&gt;&gt; x.data[0] tensor(3) How do I get just a regular non-tensor value 3?
You can use x.item() to get a Python number from a Tensor that has one element.
https://stackoverflow.com/questions/57727372/
Display result of convolution in PyTorch
PyTorch newbie here. I wrote a script (code below) that performs the following operations: load an image, perform a 2D convolution operation and then display the output and the input. At present I have the image below, which seems off. How can I plot the feature map correctly? import numpy as np import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import matplotlib.pyplot as plt import imageio import sys A = imageio.imread('LiT.png') # Define how the convolution operation works conv2 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3, stride=1, padding=1) image_d = torch.FloatTensor(np.asarray(A.reshape(1, 3, A.shape[0] , A.shape[1]))) fc = conv2(image_d) fc1 = fc.permute(0, 2, 3, 1).reshape([516, 780, 3]) plt.figure(figsize=(16,8)) plt.subplot(1,2,1) plt.imshow(A) plt.subplot(1,2,2) plt.imshow(fc1.data.numpy()) plt.show()
The issue with your code is this line image_d = torch.FloatTensor(np.asarray(A.reshape(1, 3, A.shape[0] , A.shape[1]))) You can't just reshape the image you need to transpose the channels. As a remark for the future, if you get a stripy result like you did it's most likely some permutation/transposition or reshaping operation that's not correct. Other than that I also scaled the input image to [0, 1] to show it properly. Below is the working code: import numpy as np import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import matplotlib.pyplot as plt import imageio import sys A = imageio.imread('LiT.png') # Define how the convolution operation works conv2 = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3, stride=1, padding=1) # from [H, W, C] to [C, H, W] transposed_image = A.transpose((2, 0, 1)) # add batch dim transposed_image = np.expand_dims(transposed_image, 0) image_d = torch.FloatTensor(transposed_image) fc = conv2(image_d) fc1 = fc.permute(0, 2, 3, 1)[0] result = fc1.data.numpy() max_ = np.max(result) min_ = np.min(result) result -= min_ result /= max_ plt.figure(figsize=(16,8)) plt.subplot(1,2,1) plt.imshow(A) plt.subplot(1,2,2) plt.imshow(result) plt.show()
https://stackoverflow.com/questions/57738890/
Check the number of parameters from state_dict in pytorch
SO has an answer about how to check the total # of params from the model: pytorch_total_params = sum(p.numel() for p in model.parameters()) However, how does one check the total # of params from the state_dict? state_dict = torch.load(model_path, map_location='cpu')?
You can count the number of saved entries in the state_dict: sum(p.numel() for p in state_dict.values()) However, there's a snag here: a state_dict stores both parameters and persistent buffers (e.g., BatchNorm's running mean and var). There's no way (AFAIK) to tell them apart from the state_dict itself, you'll need to load them into the model and use sum(p.numel() for p in model.parameters() to count only the parameters. For instance, if you checkout resnet50 from torchvision.models import resnet50 model = resnet50(pretrained=True) state_dict = torch.load('~/.torch/models/resnet50-19c8e357.pth') num_parameters = sum(p.numel() for p in model.parameters()) num_state_dict = sum(p.numel() for p in state_dict.values()) print('num parameters = {}, stored in state_dict = {}, diff = {}'.format(num_parameters, num_state_dict, num_state_dict - num_parameters)) Resulting with num parameters = 25557032, stored in state_dict = 25610152, diff = 53120 As you can see there can be quite a gap between the two values.
https://stackoverflow.com/questions/57743774/
Using imbalanced-learn with Pandas DataFrame
My dataset is quite imbalanced. The two minority classes each contain half of the sample in the majority class. My RNN model is not able to learn anything about the least populated class. I'm trying to use the imbalanced-learn library. For instance: sm = SMOTE(random_state=42, n_jobs=-1, k_neighbors=10) X_train, y_train = sm.fit_resample(train.drop(['label], axis=1), train['label']) works if train.drop(['label] contains just the values of the used features. The problem is that my DataFrame contains one additional columns containing strings as values: I cannot drop it since those strings are the input for my RNN. And if I drop it, I would not be able to tell to which row of the oversampled dataset those strings belong to. Is there a way to keep all the columns and tell the function which columns to use for oversampling?
For those who need to do something similar, a co-author of the library suggested me to use SMOTENC, which can handle also categorical variables (like strings).
https://stackoverflow.com/questions/57756173/
How to vectorize this pytorch code over (at least) the batch dimension?
I want to implement a code to build an adjacency matrix such that (for example): If X[0] : [0, 1, 2, 0, 1, 0], then, A[0, 1] = 1 A[1, 2] = 1 A[2, 0] = 1 A[0, 1] = 1 A[1, 0] = 1 The following code works fine, however, it's too slow! So, please help me to vectorize this code on the batch (first) dimension at least: A = torch.zeros((3, 3, 3), dtype = torch.float) X = torch.tensor([[0, 1, 2, 0, 1, 0], [1, 0, 0, 2, 1, 1], [0, 0, 2, 2, 1, 1]]) for a, x in zip(A, X): for i, j in zip(x, x[1:]): a[i, j] = 1 Thanks! :)
I am pretty sure that there is a much simpler way of doing this, but I tried to keep within the realm of torch function calls, to make sure that any gradient operation could be properly tracked. In case this is not required for backpropagation, I strongly suggest you look into solution that maybe utilize some numpy functions, because I think there is a stronger guarantee to find something suitable here. But, without further ado, here is the solution I came up with. It essentially transforms your X vector into a series of tuple entries that correspond to the position in A. For this, we need to align some of the indices (specifically, the first dimension is only implicitly given in X, since the first list in X corresponds to A[0,:,:], the second list to A[1,:,:], and so on. This is also probably where you can start optimizing the code, because I did not find a reasonable description of such a matrix, and therefore had to come up with my own way of creating it. # Start by "aligning" your shifted view of X # Essentially, take the all but the last element, # and put it on top of all but the first element. X_shift = torch.stack([X[:,:-1], X[:,1:]], dim=2) # X_shift.shape: (3,5,2) in your example # To assign this properly, we need to turn it into a "concatenated" list, # where each entry corresponds to a 2D tuple in the respective dimension of A. temp_tuples = X_shift.view(-1,2).transpose(0,1) # temp_tuples.shape: (2,15) in your example. Below are the values: tensor([[0, 1, 2, 0, 1, 1, 0, 0, 2, 1, 0, 0, 2, 2, 1], [1, 2, 0, 1, 0, 0, 0, 2, 1, 1, 0, 2, 2, 1, 1]]) # Now we have to create a matrix do indicate the proper "first dimension index" fix_dims = torch.repeat_interleave(torch.arange(0,3,1), len(X[0])-1, 0).unsqueeze(dim=0) # fix_dims.shape: (1,15) # Long story short, this creates the following vector. tensor([[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2]]) # Note that the unsqueeze is necessary to properly concatenate the two matrices: access_tuples = tuple(torch.cat([fix_dims, temp_tuples], dim=0)) A[access_tuples] = 1 This further assumes that every dimension in X has the same number of tuples changed. If that is not the case, then you have to manually create a fix_dims vector, where each increment is repeated the length of X[i] times. If it is equal as in your example, you can safely use the proposed solution.
https://stackoverflow.com/questions/57763066/
keras.preprocessing.text.Tokenizer equivalent in Pytorch?
Basically the title; is there any equivalent tokeras.preprocessing.text.Tokenizer in Pytorch? I have yet to find any that gives all the utilities without handcrafting things.
I find Torchtext more difficult to use for simple things. PyTorch-NLP can do this in a more straightforward way: from torchnlp.encoders.text import StaticTokenizerEncoder, stack_and_pad_tensors, pad_tensor loaded_data = ["now this ain't funny", "so don't you dare laugh"] encoder = StaticTokenizerEncoder(loaded_data, tokenize=lambda s: s.split()) encoded_data = [encoder.encode(example) for example in loaded_data] print(encoded_data) [tensor([5, 6, 7, 8]), tensor([ 9, 10, 11, 12, 13])] encoded_data = [pad_tensor(x, length=10) for x in encoded_data] print(stack_and_pad_tensors(encoded_data)) # alternatively, use encoder.batch_encode() BatchedSequences(tensor=tensor([[ 5, 6, 7, 8, 0, 0, 0, 0, 0, 0], [ 9, 10, 11, 12, 13, 0, 0, 0, 0, 0]]), lengths=tensor([10, 10])) ​ It comes with other types of encoders, such as spaCy's tokenizer, subword encoder, etc.
https://stackoverflow.com/questions/57767854/
How do I concatenate tensors along a given axis?
import torch a = torch.Tensor(2,2,2) b = myfunction(a) print(a) &gt;&gt;&gt; [[[1,2], [5,6]], [[7,8], [9,10]]] print(b) &gt;&gt;&gt; [[1,2,7,8], [5,6,9,10]] How do I code myfunction to get b from a? Is there some pytorch functions that transforms a in such way?
You can achieve this by using transpose to swap the first two axes (cf. e.g. np.swapaxes), and reshape to get your desired shape: In [12]: a Out[12]: tensor([[[ 1., 2.], [ 5., 6.]], [[ 7., 8.], [ 9., 10.]]]) In [13]: a.transpose(0, 1).reshape(2, 4) Out[13]: tensor([[ 1., 2., 7., 8.], [ 5., 6., 9., 10.]])
https://stackoverflow.com/questions/57777574/
why Gradient Descent doesn't work as expected with pytorch
so I'm starting with Pytorch and tried to start with an easy Linear Regression Example. Actually I made an easy Implementation of Linear Regression with Pytorch to calculate the equation 2*x+1 but the loss stay stuck at 120 and there is a Problem with Gradient Descent because it doesn't converge to a small loss value. I don't know why this is happening and it made me crazy because I don't see what's wrong. actually this example should be very easy to solve. this is the Code I'm using import torch import torch.nn.functional as F from torch.utils.data import TensorDataset, DataLoader import numpy as np X = np.array([i for i in np.arange(1, 20)]).reshape(-1, 1) X = torch.tensor(X, dtype=torch.float32, requires_grad=True) y = np.array([2*i+1 for i in np.arange(1, 20)]).reshape(-1, 1) y = torch.tensor(y, dtype=torch.float32, requires_grad=True) print(X.shape, y.shape) class LR(torch.nn.Module): def __init__(self, n_features, n_hidden1, n_out): super(LR, self).__init__() self.linear = torch.nn.Linear(n_features, n_hidden1) self.predict = torch.nn.Linear(n_hidden1, n_out) def forward(self, x): x = F.relu(self.linear(x)) x = self.predict(x) return x model = LR(1, 10, 1) optimizer = torch.optim.SGD(model.parameters(), lr=0.01) loss_fn = torch.nn.MSELoss() def train(epochs=100): for e in range(epochs): pred = model(X) loss = loss_fn(pred, y) optimizer.zero_grad() loss.backward() optimizer.step() print(f"epoch: {e} and loss= {loss}") desired output is a small loss value and that the model train to give a good prediction later.
Your learning rate is too large. The model takes a few steps in the right direction, but it can't land on an actually good minimizer and henceforth zigzags around it. If you try lr=0.001 instead, your performance will be much better. This is why it's often useful to decay your learning rate over time when using first order optimizers.
https://stackoverflow.com/questions/57795861/
ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 1]))
ValueError Traceback (most recent call last) &lt;ipython-input-30-33821ccddf5f&gt; in &lt;module&gt; 23 output = model(data) 24 # calculate the batch loss ---&gt; 25 loss = criterion(output, target) 26 # backward pass: compute gradient of the loss with respect to model parameters 27 loss.backward() C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\modules\module.py in __call__(self, *input, **kwargs) 487 result = self._slow_forward(*input, **kwargs) 488 else: --&gt; 489 result = self.forward(*input, **kwargs) 490 for hook in self._forward_hooks.values(): 491 hook_result = hook(self, input, result) C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target) 593 self.weight, 594 pos_weight=self.pos_weight, --&gt; 595 reduction=self.reduction) 596 597 C:\Users\mnauf\Anaconda3\envs\federated_learning\lib\site-packages\torch\nn\functional.py in binary_cross_entropy_with_logits(input, target, weight, size_average, reduce, reduction, pos_weight) 2073 2074 if not (target.size() == input.size()): -&gt; 2075 raise ValueError("Target size ({}) must be the same as input size ({})".format(target.size(), input.size())) 2076 2077 return torch.binary_cross_entropy_with_logits(input, target, weight, pos_weight, reduction_enum) ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 1])) I am training a CNN. Working on the Horses vs humans dataset. This is my code. I am using criterion = nn.BCEWithLogitsLoss() and optimizer = optim.RMSprop(model.parameters(), lr=0.01). My final layer is self.fc2 = nn.Linear(512, 1). Out last neuron, will output 1 for horse and 0 for human, right? or should I choose 2 neurons for output? 16 is the batch size. Since the error says ValueError: Target size (torch.Size([16])) must be the same as input size (torch.Size([16, 1])). I don't understand, where do I need to make change, to rectify the error.
target = target.unsqueeze(1), before passing target to criterion, changed the target tensor size from [16] to [16,1]. Doing it solved the issue. Furthermore, I also needed to do target = target.float() before passing it to criterion, because our outputs are in float. Besides, there was another error in the code. I was using sigmoid activation function in the last layer, but I shouldn’t because the criterion I am using already comes with sigmoid builtin.
https://stackoverflow.com/questions/57798033/
PyTorch dot product does not work for some cases
I am struggling with an issue I cannot solve in PyTorch code. My task is simple: just get the inner product of two tensors. However, the output becomes zero in certain cases instead of returning the correct value. For example, the code below demonstrates the issue. a = torch.tensor([3,1]) b = torch.tensor([3.,1.]) a.dot(a) # this returns 10, which is correct b.dot(b) # this returns 0., which is not correct I am using PyTorch version 1.2 and this has never happened to me before... Is there something simple that I am missing around the way I define the tensors? Thank you for your time!
I just ran the same code using torch version '1.0.1.post2' and saw the results tensor(10)and tensor(10.) respectively for a.dot(a) and b.dot(b). Please confirm if you are missing something else in the code.
https://stackoverflow.com/questions/57799794/
How to create custom neural network with custom weight initialization in tensorflow or pytorch
I'm trying to create a small neural network with custom connections between neurons. The connections should exist over several layers and not be fully connected (sparse) as shown in the picture. I would also like to do the weight initialization manually and not completely randomly. My goal is to determine whether a connection is positive or negative. Is it possible to create such a neural net in tensorflow (python/js) or pytorch?
To summarize: Can you do it? -- Yes, absolutely. Is it going to be pretty? -- No, absolutely not. In my explanation, I will further focus on PyTorch, as this is the library that I am more comfortable with, and that is especially more useful if you have custom operations that you can easily express in a pythonic manner. Tensorflow also has eager execution mode (more serious integration from version 2, if I remember that correctly), but it is traditionally done with computational graphs, which make this whole thing a little uglier than it needs to be. As you hopefully know, backpropagation (the "learning" step in any ANN) is basically an inverse pass through the network, to calculate gradients, or at least close enough to the truth for our problem at hand. Importantly, torch functions store this "reverse" direction, which makes it trivial for the user to call backpropagation functions. To model a simple network as described in your image, we have only one major disadvantage: The available operations are usually excelling at what they are doing because they are simply and can be optimized quite heavily. In your case, you have to express different layers as custom operations, which generally scales incredibly poorly, unless you can express the functionals as some form of matrix operation, which I do not see straigt away in your example. I am further assuming that you are applying some form of non-linearity, as it would otherwise be a network that would fail for any non-linearly separable problem. import torch import torch.nn as nn class CustomNetwork(nn.module): def __init__(self): self.h_1_1 = nn.Sequential(nn.Linear(1,2), nn.ReLU) # top node in first layer self.h_1_2 = nn.Sequential(nn.Linear(1,2), nn.ReLU) # bottom node in first layer # Note that these nodes have no shared weights, which is why we # have to initialize separately. self.h_2_1 = nn.Sequential(nn.Linear(1,1), nn.ReLU) # top node in second layer self.h_2_2 = nn.Sequential(nn.Linear(1,1), nn.ReLU) # bottom node in second layer self.h_2_1 = nn.Sequential(nn.Linear(2,1), nn.ReLU) # top node in third layer self.h_2_2 = nn.Sequential(nn.Linear(2,1), nn.ReLU) # bottom node in third layer # out doesn't require activation function due to pairing with loss function self.out = nn.Linear(2,1) def forward(self, x): # x.shape: (batch_size, 2) # first layer. shape of (batch_size, 2), respectively out_top = self.h_1_1(x[:,0]) out_bottom = self.h_1_2(x[:,1]) # second layer. shape of (batch_size, 1), respectively out_top_2 = self.h_2_1(out_top[:,0]) out_bottom_2 = self.h_2_2(out_bottom[:,0]) # third layer. shape of (batch_size, 1), respectively # additional concatenation of previous outputs required. out_top_3 = self.h_3_1(torch.cat([out_top_2, -1 * out_top[:,1]], dim=1)) out_bottom_3 = self.h_3_2(torch.cat([out_bottom_2, -1 * out_bottom[:,1]], dim=1)) return self.out(torch.cat([out_top_3, out_bottom_3], dim=1)) As you can see, any computational step is (in this case rather explicitly) given, and very much possible. Again, once you want to scale your number of neurons for each layer, you are going to have to be a little more creative in how you process, but for-loops do very much work in PyTorch as well. Note that this will in any case be much slower than a vanilla linear layer, though. If you can live with seperately trained weights, you can always also just define separate linear layers of smaller size and put them in a more convenient fashion.
https://stackoverflow.com/questions/57803287/
Why is my texture synthesis algorithm only producing blocky / noisy, non-sensible output?
My end-goal is to create a script for neural style transfer, however, during writing code for said task, I stumbled upon a certain problem: the texture synthesis part of the algorithm seemed to have some problems with reproducing the artistic style. In order to solve this, I decided to create another script where I'd try to solve the task of texture synthesis using a neural network on its own. TL;DR ... even after tackling the problem on its own, my script still produced blocky / noisy, non-sensible output. I've tried having a look at how other people have solved this task, but most of what I found were more sophisticated solutions ("fast neural-style-transfer", etc.). Also, I couldn't find too many PyTorch implementations. Since I've already spent the past couple of days on trying to fix this issue and considering that I'm new to the PyTorch-Framework, I have decided to ask the StackOverflow community for help and advice. I use the VGG16 network for my model ... class VGG16(nn.Module): def __init__(self): super(VGG16, self).__init__() vgg_fs = models.vgg16(pretrained=True).features self.sl1 = nn.Sequential() self.sl2 = nn.Sequential() self.sl3 = nn.Sequential() self.sl4 = nn.Sequential() self.sl5 = nn.Sequential() for i in range(4): self.sl1.add_module(str(i), vgg_fs[i]) for i in range(4, 9): self.sl2.add_module(str(i), vgg_fs[i]) for i in range(9, 16): self.sl3.add_module(str(i), vgg_fs[i]) for i in range(16, 23): self.sl4.add_module(str(i), vgg_fs[i]) for i in range(23, 30): self.sl5.add_module(str(i), vgg_fs[i]) for p in self.parameters(): p.requires_grad_(False) def forward(self, x): h = self.sl1(x) h1 = h h = self.sl2(h) h2 = h h = self.sl3(h) h3 = h h = self.sl4(h) h4 = h h = self.sl5(h) h5 = h return_tuple = namedtuple('hidden_states', ['h1', 'h2', 'h3', 'h4', 'h5']) ret = return_tuple(h1, h2, h3, h4, h5) return ret Then, I have some functions for gram-matrix computation and normalization ... def comp_gram(f): (b, c, h, w) = f.shape f = f.view(b, c, h * w) g = f.bmm(f.transpose(1, 2)) g = g / (c * h * w) return g def norm(b): mean = torch.Tensor([0.485, 0.456, 0.406]).cuda().view(3, 1, 1) std = torch.Tensor([0.229, 0.224, 0.225]).cuda().view(3, 1, 1) return (b - mean) / std And finally, my training-function ... def train(model, style_img, w=224, h=224, iters=32, lr=1): style = torch.from_numpy(np.array(Image.open(style_img))).cuda().float() style = style / 255. style = style.view(1, style.size()[2], *style.size()[:2]) style_fts = model(norm(style)) style_gms = [comp_gram(f) for f in style_fts] img = torch.rand(*style.size()[:2], h, w, requires_grad=True, device='cuda') optimizer = optim.Adam([img], lr=lr) mse_loss = nn.MSELoss() plt.ion() for i in range(iters): optimizer.zero_grad() actvs = model(norm(img)) lss = 0. for f, gm in zip(actvs, style_gms): g = comp_gram(f) lss += mse_loss(g, gm) lss.backward() optimizer.step() if (i % 5 == 0) or (i == iters - 1): plt.title('Iter#{:04d}'.format(i)) plt.imshow(img.detach().cpu().view(*img.shape[2:], img.shape[1])) plt.pause(1e-3) print('[iter#{:04d}]: Loss\t-&gt; {:}'.format(i, lss.item())) plt.ioff() plt.subplot(121) plt.title('Original') plt.imshow(style.cpu().view(*style.size()[2:], style.size()[1])) plt.subplot(122) plt.title('Style') plt.imshow(img.detach().cpu().view(*img.size()[2:], img.size()[1])) plt.show() I expected the algorithm to produce the style of the painting in some way, shape or form, but that didn't happen. ‍♂️ (Since I sadly don't have enough reputation to post an image, you can find a picture of my non-sensible output here: https://mattmoony.github.io/cdn/conv-net_pytorch-style-transfer/problem.png) I sincerely hope that you will be able to help me out and that I'm able to use this issue as a learning experience. Thank you!
Hurrah! After yet another day of researching and testing, I've finally discovered the bug in my code. The problem doesn't lie with the training process or the model itself, but rather with the lines responsible for loading the style image. (this article helped me discover the issue) So... I added the following two functions to my script ... def load_img(p): img = Image.open(p).convert('RGB') im_transform = transforms.Compose([ transforms.ToTensor() ]) img = im_transform(img).unsqueeze(0).cuda() return img def to_img(t): img = t.cpu().clone().detach() img = img.numpy().squeeze() img = img.transpose(1, 2, 0) img = img.clip(0, 1) return img And used them in my training function ... def train(...): ... style = load_img(style_img) ... if i % 5 == 0: plt.title('Iter#{:04d}'.format(i)) plt.imshow(to_img(img)) plt.pause(1e-3) ... &lt;etc.&gt; ... I'm glad that I was able to figure out what the problematic part of my script was and I'll do my best to avoid similar bugs in the future. I hope that this helps anyone experiencing similar problems or that it at least inspires them to keep on chasing for a solution.
https://stackoverflow.com/questions/57803706/
How can I use the LBFGS optimizer with pytorch ignite?
I started using Ignite recently and i found it very interesting. I would like to train a model using as an optimizer the LBFGS algorithm from the torch.optim module. This is my code: from ignite.engine import Events, Engine, create_supervised_trainer, create_supervised_evaluator from ignite.metrics import RootMeanSquaredError, Loss from ignite.handlers import EarlyStopping D_in, H, D_out = 5, 10, 1 model = simpleNN(D_in, H, D_out) # a simple MLP with 1 Hidden Layer model.double() train_loader, val_loader = get_data_loaders(i) optimizer = torch.optim.LBFGS(model.parameters(), lr=1) loss_func = torch.nn.MSELoss() #Ignite trainer = create_supervised_trainer(model, optimizer, loss_func) evaluator = create_supervised_evaluator(model, metrics={'RMSE': RootMeanSquaredError(),'LOSS': Loss(loss_func)}) @trainer.on(Events.ITERATION_COMPLETED) def log_training_loss(engine): print(&quot;Epoch[{}] Loss: {:.5f}&quot;.format(engine.state.epoch, len(train_loader), engine.state.output)) def score_function(engine): val_loss = engine.state.metrics['RMSE'] print(&quot;VAL_LOSS: {:.5f}&quot;.format(val_loss)) return -val_loss handler = EarlyStopping(patience=10, score_function=score_function, trainer=trainer) evaluator.add_event_handler(Events.COMPLETED, handler) trainer.run(train_loader, max_epochs=100) And the error that raises is: TypeError: step() missing 1 required positional argument: 'closure' I know that is required to define a closure for the implementation of LBFGS, so my question is how can I do it using ignite? or is there another approach for doing this?
The way to do it is like this: from ignite.engine import Engine model = ... optimizer = torch.optim.LBFGS(model.parameters(), lr=1) criterion = def update_fn(engine, batch): model.train() x, y = batch # pass to device if needed as here: https://github.com/pytorch/ignite/blob/40d815930d7801b21acfecfa21cd2641a5a50249/ignite/engine/__init__.py#L45 def closure(): y_pred = model(x) loss = criterion(y_pred, y) optimizer.zero_grad() loss.backward() return loss optimizer.step(closure) trainer = Engine(update_fn) # everything else is the same Source
https://stackoverflow.com/questions/57806980/
Can't replace classifier on Densenet121 in pytorch
I am trying to do some transfer learning using this github DenseNet121 model (https://github.com/gaetandi/cheXpert.git). I'm running into issues resizing the classification layer from 14 to 2 outputs. Relevant part of the github code is: class DenseNet121(nn.Module): """Model modified. The architecture of our model is the same as standard DenseNet121 except the classifier layer which has an additional sigmoid function. """ def __init__(self, out_size): super(DenseNet121, self).__init__() self.densenet121 = torchvision.models.densenet121(pretrained=True) num_ftrs = self.densenet121.classifier.in_features self.densenet121.classifier = nn.Sequential( nn.Linear(num_ftrs, out_size), nn.Sigmoid() ) def forward(self, x): x = self.densenet121(x) return x I load and init with: # initialize and load the model model = DenseNet121(nnClassCount).cuda() model = torch.nn.DataParallel(model).cuda() modeldict = torch.load("model_ones_3epoch_densenet.tar") model.load_state_dict(modeldict['state_dict']) It looks like DenseNet doesn't split layers up into children so model = nn.Sequential(*list(modelRes.children())[:-1]) won't work. model.classifier = nn.Linear(1024, 2) seems to work on default DenseNets, but with the modified classifier (additional sigmoid function) here it ends up just adding an additional classifier layer without replacing the original. I've tried model.classifier = nn.Sequential( nn.Linear(1024, dset_classes_number), nn.Sigmoid() ) But am having the same added instead of replaced classifier issue: ... ) (classifier): Sequential( (0): Linear(in_features=1024, out_features=14, bias=True) (1): Sigmoid() ) ) ) (classifier): Sequential( (0): Linear(in_features=1024, out_features=2, bias=True) (1): Sigmoid() ) )
If you want to replace the classifier inside densenet121 that is a member of your model you need to assign model.densenet121.classifier = nn.Sequential(...)
https://stackoverflow.com/questions/57807050/
Optimize Custom Parameters in Pytorch
I'm trying to create some custom parameters to optimize and came across this helpful link here. However, I'm a bit confused as to why this code works. Here is the code with some slight modifications from the original post to clearly see the behavior of the optimization. import torch import torch.nn as nn import torch.nn.functional as F import numpy as np class Mask(nn.Module): def __init__(self): super(Mask, self).__init__() self.weight = torch.nn.Parameter(data=torch.Tensor(5, 5), requires_grad=True) self.weight.data.uniform_(-1, 1) def forward(self, x): masked_wt = self.weight.mul(1) return masked_wt class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.mask = Mask() def forward(self,x): x = self.mask(x) return x model = Model() indata = torch.ones(5,5) optimizer = torch.optim.Adam(model.parameters(),lr=0.001) while True: x = model(indata) optimizer.zero_grad() loss = F.l1_loss(indata,x) loss.backward() optimizer.step() print(model.mask.weight) So two questions: In the forward function of the Mask class, why do I need to do self.weight.mul(1) and why doesn't x get used? x = model(indata) clearly does per element multiplication between the 5x5 matrix indata and the weight, but how does this happen if we didn't use x in the forward function of Mask?
You are right, Mask.forward discard x completely. However, the output of your model "sees" indata when computing the loss. What you are actually teaching your model is to have mask.weight == indata.
https://stackoverflow.com/questions/57808870/
What defines legitimate input dimensions of a pytorch nn?
From the tutorial / example github, the network to be trained on the MNIST dataset is defined as: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5, 1) self.conv2 = nn.Conv2d(20, 50, 5, 1) self.fc1 = nn.Linear(4*4*50, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2, 2) x = x.view(-1, 4*4*50) x = F.relu(self.fc1(x)) x = self.fc2(x) return F.log_softmax(x, dim=1) The image sizes this network is trained with are 28x28 pixels. Testing images of different sizes creates errors. To be precise: I tested images of size 27x27 and 32x32 for whom it does break with an error; an input size of 29x29 does create none. Where is the size of 28x28 actually defined? What formula can I use to discern parameters for different input sizes for different tasks? Can one use images of different sizes as input? How?
You can backtrack the size of the input image from the first fully connected layer i.e. fc1 = Linear(4*4*50, 500). The input to the fc1 is 50x4x4 (CxHxW) (here 50 is the channel dimension as evident from the previous conv2 layer). Thus, the output of conv2 (before max-pooling operation) is 50x8x8 as you're performing pooling using 2x2 - max_pool2d(x, 2, 2). torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, ...) Now, you can get the input size of image before the convolution operation using the formula (W-F+2P)/S + 1 = output size. Here, W is input size, F is filter/kernel size, and P is padding used, and S is the stride. Thus, (W-5+2*0)/1+1=8 => W=12. Hence, the input to conv2 is 20x12x12. In the same way, we can continue the process as follows: Output of conv1 (i.e. before max-pooling): 20x24x24 Input to conv1: 1x28x28. ((W-5+2*0)/1+1=24 => W=28) Hence, the input image size is 1x28x28. The error is because the fully connected layers expect input of fixed size and that defines your network. In order to pass variable sized input, you may use need to transform the input to size that your network (fc layers) expects using transformations such as cropping. Also, there are networks that can take variable size input e.g. Fully Convolutional Networks (FCN), which doesn't contain fc layers, but only conv layers. You may also read about Spatial Pyramid Pooling (used in a network called DeepLab for semantic segmentation). Read more here.
https://stackoverflow.com/questions/57815801/
Deep learning with Pytorch: understanding the neural network example
I'm reading the Pytorch documentation and I have a couple of questions about the neural network that is introduced. The documentation defines the following network: import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel, 6 output channels, 3x3 square convolution # kernel self.conv1 = nn.Conv2d(1, 6, 3) self.conv2 = nn.Conv2d(6, 16, 3) # an affine operation: y = Wx + b self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): # Max pooling over a (2, 2) window x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2)) # If the size is a square you can only specify a single number x = F.max_pool2d(F.relu(self.conv2(x)), 2) x = x.view(-1, self.num_flat_features(x)) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x def num_flat_features(self, x): size = x.size()[1:] # all dimensions except the batch dimension num_features = 1 for s in size: num_features *= s return num_features Later on, the following statement is made: Let try a random 32x32 input. Note: expected input size of this net (LeNet) is 32x32. To use this net on MNIST dataset, please resize the images from the dataset to 32x32. Question 1: Why do the images need to be 32x32 (where I assume that this means 32 pixels by 32)? The first convolution applies six kernel to an image, with every kernel being 3x3. This means that if the input channel is 32x32, the six output channels all have dimensions 30x30 (the 3x3 kernel grid makes you lose 2 pixels in width and height). The second convolution applies more kernels so that there now are sixteen output channels of dimensions 28x28 (again the 3x3 kernel grid makes you lose 2 pixels in width and height). Now I would expect 16x28x28 nodes in the next layer, since every one of the sixteen output channels has 28x28 pixels. Somehow, this is incorrect, and the next layer contains 16x6x6 nodes. Why is this true? Question 2: The second convolution layer goes from six input channels to sixteen output channels. How is this done? In the first convolution layer we go from one input channel to six input channels, which makes sense to me. You can just apply six kernels to the single input channel to arrive at six output channels. Going from six input channels to sixteen output channels does not make as much sense to me. How are the different kernels applied? Do you apply two kernels to the first five input channels to arrive at ten output channels, and apply six kernels to the last input channel, so that the total comes to sixteen output channels? Or does the neural network learn itself to use x kernels and apply them to the input channels that it finds most suitable?
I can now answer these questions my self. Question 1: To see why you need a 32x32 image for this neural network to work consider the following: Layer 1: First, convolution is applied with a 3x3 kernel. Since the image has dimensions 32x32, this will result in a grid of 30x30. Next, max pooling is applied to the grid, with a 2x2 kernel and stride of 2 resulting in a grid that has dimensions 15x15. Layer 2: First, convolution is applied with a 3x3 kernel to the 15x15 grid, resulting in a 13x13 grid. Next, max pooling is applied with a 2x2 kernel and stride of 2 resulting in a grid that has dimensions 6x6. We get a 6x6 grid and not a 7x7 grid because by default the floor function is used and not the ceil function. Since the convolution in layer 2 has sixteen output channels, the first linear layer needs 16x6x6 nodes! We see that the required input is indeed a 32x32 image. Question 2: Every output channel is created by applying six different kernels to each input channel and summing the results. This is explained in the documentation.
https://stackoverflow.com/questions/57822568/
epsilon parameter in Adam opitmizer
Using pyTorch and tensorflow (TF), I was wandering how the Adam optimizer is implemented for curiosity. And I do not know if I am wrong or not but it seems to me that the two implementations differ and the pyTorch one is the original one from https://arxiv.org/pdf/1412.6980.pdf. My problem comes from the eps-parameter. Using the TF implentation seems to lead to a time-and-b2 dependance of this parameter, namely q(t+1) = q(t) - \gamma * sqrt[(1-b2^t)]/(1-b1^t) * m(t)/[sqrt[v(t)]+eps] which in the original algorithm notation can be reformulate as q(t+1) = q(t) - \gamma * mhat(t)/[sqrt[vhat(t)]+ eps/sqrt[(1-b2^t)]] and this point out the variation of the eps-parameter which is not the case neither in the original algorithm neither in the pyTorch implementation. Am I wrong? or it is well known? Thanks for your help.
Indeed, you can check this in the docs for the TF Adam optimizer. To quote the relevant part: The default value of 1e-8 for epsilon might not be a good default in general. For example, when training an Inception network on ImageNet a current good choice is 1.0 or 0.1. Note that since AdamOptimizer uses the formulation just before Section 2.1 of the Kingma and Ba paper rather than the formulation in Algorithm 1, the "epsilon" referred to here is "epsilon hat" in the paper. If you check the "the formulation just before section 2.1" in the paper, they actually include the time dependence in alpha, resulting in a time-dependent "step size" alpha_t but a fixed epsilon. Note that at the end of the day, this is just rewriting/interpreting parameters in a slightly different fashion and doesn't change the actual workings of the algorithm. But you will need to be aware that choosing the same epsilon in the PyTorch and TF implementations will apparently not lead to the same results...
https://stackoverflow.com/questions/57824804/
Convert CUDA tensor to NumPy
First of all, I tried those solutions: 1, 2, 3, and 4, but did not work for me. After training and testing the neural network, I am trying to show some examples to verify my work. I named the method predict which I pass the image to it to predict for which class it belongs: def predict(model, image_path, topk=5): ''' Predict the class (or classes) of an image using a trained deep learning model. ''' output = process_image(image_path) output.unsqueeze_(0) output = output.cuda().float() model.eval() with torch.no_grad(): score = model(output) prob, idxs = torch.topk(score, topk) # Convert indices to classes idxs = np.array(idxs) idx_to_class = {val:key for key, val in model.class_to_idx.items()} classes = [idx_to_class[idx] for idx in idxs[0]] # Map the class name with collected topk classes names = [] for cls in classes: names.append(cat_to_name[str(cls)]) return prob, names Then there is the final step which displays the final result based on the training of the neural network and done like this: # TODO: Display an image along with the top 5 classes x_pos, y_pos = predict(model, img_pil, topk=5) ax_img = imshow(output) ax_img.set_title(y_pos[0]) plt.figure(figsize=(4,4)) plt.barh(range(len(y_pos)), np.exp(x_pos[0])) plt.yticks(range(len(y_pos)), y_pos) plt.show() The error is: --------------------------------------------------------------------------- TypeError Traceback (most recent call last) &lt;ipython-input-45-e3f9951e9804&gt; in &lt;module&gt;() ----&gt; 1 x_pos, y_pos = predict(model, img_pil, topk=5) 2 3 ax_img = imshow(output) 4 ax_img.set_title(y_pos[0]) 5 1 frames &lt;ipython-input-44-d77500f31561&gt; in predict(model, image_path, topk) 14 15 # Convert indices to classes ---&gt; 16 idxs = np.array(idxs) 17 idx_to_class = {val:key for key, val in model.class_to_idx.items()} 18 classes = [idx_to_class[idx] for idx in idxs[0]] /usr/local/lib/python3.6/dist-packages/torch/tensor.py in __array__(self, dtype) 456 def __array__(self, dtype=None): 457 if dtype is None: --&gt; 458 return self.numpy() 459 else: 460 return self.numpy().astype(dtype, copy=False) TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first. How do I solve this? I tried to change idx to idxs = idxs.cpu().numpy() and the error is: TypeError Traceback (most recent call last) &lt;ipython-input-62-e3f9951e9804&gt; in &lt;module&gt;() 5 6 plt.figure(figsize=(4,4)) ----&gt; 7 plt.barh(range(len(y_pos)), np.exp(x_pos[0])) 8 plt.yticks(range(len(y_pos)), y_pos) 9 /usr/local/lib/python3.6/dist-packages/torch/tensor.py in __array__(self, dtype) 456 def __array__(self, dtype=None): 457 if dtype is None: --&gt; 458 return self.numpy() 459 else: 460 return self.numpy().astype(dtype, copy=False) TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.
Try to change idxs = np.array(idxs) to idxs = idxs.cpu().numpy() And change plt.barh(range(len(y_pos)), np.exp(x_pos[0])) to plt.barh(range(len(y_pos)), np.exp(x_pos[0].cpu().numpy()))
https://stackoverflow.com/questions/57832423/
Pytorch: choosing columns from a 3d tensor, according to indices tensor
I have a 3D tensor M of dimensions [BxLxD] and a 1D tensor idx of dimensions [B,1] that contains column indices in the range (0, L-1). I want to create a 2D tensor N of dimensions [BxD] such that N[i,j] = M[i, idx[i], j]. How can this be done efficiently? Example: B,L,D = 2,4,2 M = torch.rand(B,L,D) &gt; tensor([[[0.0612, 0.7385], [0.7675, 0.3444], [0.9129, 0.7601], [0.0567, 0.5602]], [[0.5450, 0.3749], [0.4212, 0.9243], [0.1965, 0.9654], [0.7230, 0.6295]]]) idx = torch.randint(0, L, size = (B,)) &gt; tensor([3, 0]) N = get_N(M, idx) Expected output: &gt; tensor([[0.0567, 0.5602], [0.5450, 0.3749]]) Thanks.
import torch B,L,D = 2,4,2 def get_N(M, idx): return M[torch.arange(B), idx, :].squeeze() M = torch.tensor([[[0.0612, 0.7385], [0.7675, 0.3444], [0.9129, 0.7601], [0.0567, 0.5602]], [[0.5450, 0.3749], [0.4212, 0.9243], [0.1965, 0.9654], [0.7230, 0.6295]]]) idx = torch.tensor([3,0]) N = get_N(M, idx) print(N) result: tensor([[0.0567, 0.5602], [0.5450, 0.3749]]) slice along two dimensions.
https://stackoverflow.com/questions/57833071/
How to split and load huge dataset that doesn't fit into memory into pytorch Dataloader?
I'm training a deep learning model to do multi label classification of diseases in NIH's Chest Xray-14 dataset using Google's Colab. I can't load all images into Dataloader at once, given around 112k training examples and limited RAM. Is there a way to just store path of images in pytorch's DataLoader, reading only those images needed for current iteration during training, and once iteration is complete, the images are unloaded from memory, so on so forth until one epoch is complete.
Yes, the default behavior for the ImageFolder is to create a list of image paths and load the actual images only when needed. It doesn't support multiclass labels. However, you can write your own Dataset to support multi-label, referencing the ImageFolder class for details. During __init__ you construct a list of image paths and a corresponding list of labels. Images should only be loaded only when __getitem__ is invoked. Below is a stub of such a dataset class, the details will depend on the organization of your files, image types, and label format. class CustomDataset(torch.utils.data.Dataset): def __init__(self, args): """ Construct an indexed list of image paths and labels """ def __getitem__(self, n): """ Load image n in the list of image paths and return it along with its label. In the case of multiclass the label will probably be a list of values""" def __len__(self): """ return the total number of images in this dataset """ Once you've created a valid dataset instance an instance of DataLoader should be created, providing your dataset as an argument. A DataLoader is responsible for sampling its dataset, i.e. invoking the __getitem__ method you wrote, and putting individual samples into mini-batches. It also handles parallelized loading and defines how the indices are sampled. The DataLoader itself doesn't store more than it needs. The maximum number of samples it should hold in memory at any time is batch_size * num_workers (or batch_size if num_workers == 0).
https://stackoverflow.com/questions/57836355/
For each layer in neural networks (pytorch), how many biases should be there?
I have a simple model in pytorch. model = Network() It's details are: Network( (hidden): Linear(in_features=784, out_features=256, bias=True) (output): Linear(in_features=256, out_features=10, bias=True) (sigmoid): Sigmoid() (softmax): Softmax(dim=1) ) There are 3 neurons' layers in total. 1 input(786 neurons), 1 hidden(256 neurons) and 1 output (10 neurons). Therefore there'll be two weight layers. So there must be two biases (simply two floating point numbers) for both weight layers right? (correct me if i am wrong). Now after initializing my network i was curious about the two bias values. So i wanted to check the bias value of my hidden layer so i wrote: model.hidden.bias And what i got as the result was not i expected! I actually expected one value! And this is what i actually got: tensor([-1.6868e-02, -3.5661e-02, 1.2489e-02, -2.7880e-02, 1.4025e-02, -2.6085e-02, 1.2625e-02, -3.1748e-02, 5.0335e-03, 3.8031e-03, -3.1648e-02, -3.4881e-02, -2.0026e-02, 1.9728e-02, 6.2461e-03, 9.3936e-04, -5.9270e-03, -2.7183e-02, -1.9850e-02, -3.5693e-02, -1.9393e-02, 2.6555e-02, 2.3482e-02, 2.1230e-02, -2.2175e-02, -2.4386e-02, 3.4848e-02, -2.6044e-02, 1.3575e-02, 9.4125e-03, 3.0012e-02, -2.6078e-02, 7.1615e-05, -1.7061e-02, 6.6355e-03, -3.4966e-02, 2.9311e-02, 1.4060e-02, -2.5763e-02, -1.4020e-02, 2.9852e-02, -7.9176e-03, -1.8396e-02, 1.6927e-02, -1.1001e-03, 1.5595e-02, 1.2169e-02, -1.2275e-02, -2.9270e-03, -6.5685e-04, -2.4297e-02, 3.0048e-02, 2.9692e-03, -2.5398e-02, 2.9955e-03, -9.3653e-04, -1.2932e-02, 2.4232e-02, -3.5182e-02, -1.6163e-02, 3.0025e-02, 3.1227e-02, -8.2498e-04, 2.7102e-02, -2.3830e-02, -3.4958e-02, -1.1886e-02, 1.6097e-02, 1.4579e-02, -2.6744e-02, 1.1900e-02, -3.4855e-02, -4.2208e-03, -5.2035e-03, 1.7055e-02, -4.8580e-03, 3.4088e-03, 1.6923e-02, 3.5570e-04, -3.0478e-02, 8.4647e-03, 2.5704e-02, -2.3255e-02, 6.9396e-03, -1.2521e-03, -9.4101e-03, -2.5798e-02, -1.4438e-03, -7.2684e-03, 3.5417e-02, -3.4388e-02, 1.3706e-02, -5.1430e-03, 1.6174e-02, 1.8135e-03, -2.9018e-02, -2.9083e-02, 7.4100e-03, -2.7758e-02, 2.4367e-02, -3.8350e-03, 9.4390e-03, -1.0844e-02, 1.6381e-02, -2.5268e-02, 1.3553e-02, -1.0545e-02, -1.3782e-02, 2.8519e-02, 2.3630e-02, -1.9703e-02, -2.0147e-02, -1.0485e-02, 2.4637e-02, 1.9989e-02, 5.6601e-03, 1.9121e-02, -1.5286e-02, 2.5996e-02, -2.9833e-02, -2.9458e-02, 2.3944e-02, -3.0107e-02, -1.2307e-02, -1.8419e-02, 3.3551e-02, 1.2396e-02, 2.9356e-02, 3.3274e-02, 5.4677e-03, 3.1715e-02, 1.3361e-02, 3.3042e-02, 2.7843e-03, 2.2837e-02, -3.4981e-02, 3.2355e-02, -2.7658e-03, 2.2184e-02, -2.0203e-02, -3.3264e-02, -3.4858e-02, 1.0820e-03, -1.4279e-02, -2.8041e-02, 4.1962e-03, 2.4266e-02, -3.5704e-02, -2.6172e-02, 2.3335e-02, 2.0657e-02, -3.0387e-03, -5.7096e-03, -1.1062e-02, 1.3450e-02, -3.3965e-02, 1.9623e-03, -2.0067e-02, -3.3858e-02, -2.1931e-02, -1.5414e-02, 2.4454e-02, 2.5668e-02, -1.1932e-02, 5.7540e-04, 1.5130e-02, 1.3916e-02, -2.1521e-02, -3.0575e-02, 1.8841e-02, -2.3240e-02, -2.7297e-02, -3.2668e-02, -1.5544e-02, -5.9408e-03, 3.0241e-02, 2.2039e-02, -2.4389e-02, 3.1703e-02, 3.5305e-02, -2.7501e-03, 2.0154e-02, -5.3489e-03, 1.4177e-02, 1.6829e-02, 3.3066e-02, -1.3425e-02, -3.2565e-02, 6.5624e-03, -1.5681e-02, 2.3047e-02, 6.5880e-03, -3.3803e-02, 2.3790e-02, -5.5061e-03, 2.9413e-02, 1.2290e-02, -1.0958e-02, 1.2680e-03, 1.3343e-02, 6.6689e-03, -2.2975e-03, -1.2068e-02, 1.6523e-02, -3.1612e-02, -1.7529e-02, -2.2220e-02, -1.4723e-02, -1.3495e-02, -5.1805e-03, -2.9620e-02, 3.0571e-02, -3.0999e-02, 3.3681e-03, 1.3579e-02, 1.4837e-02, 1.5694e-02, -1.1178e-02, 4.6233e-03, -2.2583e-02, -3.5281e-03, 3.0918e-02, 2.6407e-02, 1.5822e-04, -3.0181e-03, 8.6989e-03, 2.8998e-02, -1.5975e-02, -3.1574e-02, -1.5609e-02, 1.0472e-02, 5.8976e-03, 7.0131e-03, -3.2047e-02, 2.6045e-02, -2.8882e-02, -2.2121e-02, -3.2960e-02, 1.8268e-02, 3.0984e-02, 1.4824e-02, 3.0010e-02, -5.7523e-03, -2.0017e-02, 4.8700e-03, 1.4997e-02, -1.4898e-02, 6.8572e-03, 9.7713e-03, 1.3410e-02, 4.9619e-03, 3.1016e-02, 3.1240e-02, -3.0203e-02, 2.1435e-02, 2.7331e-02], requires_grad=True) Can someone explain to me this behaviour? Why did i get 256 values instead of one? Edit1: Here is my understanding of the layers: For a whole layer of neurons, a bias is just a single value. Am i right? But what i am seeing as the output about are 256 values ? why ? did pytorch assume that i have a bias with each neuron ? is that okay?
So first it's important to realize what's going on inside of one of these layers. When you write: Linear(in_features=784, out_features=256, bias=True) You are modeling a linear relationship between the input and the output. You're probably familiar with this from basic math: Y = MX + B However instead of a "slope" and a "y-intercept", you have a weights matrix and a bias term. This is still a linear relationship, but with matrices as our input and output. Y is our output, M is our weights matrix, X is our input, and B is our Bias. You define that the input is a (N x 784) matrix, and our output is a (N x 256) matrix (N is the number of samples). If you're familiar with matrix multiplication this means that our weights matrix is (784 X 256). The output of MX will be a (N x 256) matrix, so our bias term must also be (N x 256) for the MX + B to work out. In general the number of values in the bias term will be the same as the number of out_features.
https://stackoverflow.com/questions/57836679/
Understanding the use of classes when training a neural network with Pytorch
I'm currently reading about using the cross-entropy loss to train a neural network in the pytorch documentation. The criterion that is to be used to calculate the loss is called as follows criterion = nn.CrossEntropyLoss() According to the torch.nn documentation, CrossEntropyLoss is a class. From my understanding this would mean that criterion is an object of type nn.CrossEntropyLoss. When training the neural network, criterion is used to calculate the loss in the following way loss = criterion(input, target) This is somewhat confusing to me. If criterion is an object, then how can it be used as a function? What I would expect is something like loss = criterion.calculate_loss(input, target) where calculate_loss() would be a method defined in the nn.CrossEntropyLoss class. Furthermore, the documentation also uses the following line of code running_loss += loss.item() Where does this item() method come from? I can't find a source mentioning item() online.
If criterion is an object, then how can it be used as a function? The criterion object has a forward method that is called in that case. criterion(input, target) is shorthand for criterion.forward(input, target) Where does this item() method come from? This method returns a one dimensional Tensor. The single value can be accessed as a number with item().
https://stackoverflow.com/questions/57842400/
Why does torch.gt function turn requires_grad into False?
The requires_grad of tensor b and c are True. But the requires_grad of tensor d is False. I am curious why this change happens because all the requires_grad of inputs are True. However, the requires_grad of tensor e is True. I can still do backward() on e. But is there an error in this way? I am using Python3.7 and Pytorch1.1. import torch import torch.nn as nn net = nn.Conv2d(1, 1, 3, padding=1) a = torch.randn(1, 1, 10, 10) b = net(a) c = net(b) d = torch.gt(b, c) e = b - c e[e &gt; 0] = 1.0 e[e &lt; 0] = 0.0
I assume this is because you cannot take a gradient of greater than operation. The return type is boolean: &gt;&gt;&gt; torch.gt(torch.tensor([[1, 2], [3, 4]]), torch.tensor([[1, 1], [4, 4]])) tensor([[False, True], [False, False]]) Whereas minus or other arithmetic operation returns another numeral.
https://stackoverflow.com/questions/57847484/
Torchvision normalize - how it operates on tuple of means/sds?
I don't understand how this transform works from torchvision. Ultimately I want to build a custom normalize class so I need to figure out how this works first. Here in the docs it describes the init like this: def __init__(self, mean, std, inplace=False): self.mean = mean self.std = std self.inplace = inplace And when I pass these parameters usually (not custom class) I pass them as a list or tuple for each channel: transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) But if I look at the call: return F.normalize(tensor, self.mean, self.std, self.inplace) All this passes the tuple to is F.normalize() which only accepts a single value for the p parameter. The class must iterate through the channels somehow to allow this to be implemented but how does it do this and how can I implement it in custom class? Based on this tutorial, I would describe it like this: class Normalize(object): """Convert ndarrays in sample to Tensors.""" def __init__(self, mean, std, inplace=False): self.mean = mean self.std = std self.inplace = inplace def __call__(self, sample): image, landmarks = sample['image'], sample['landmarks'] return {'image': F.normalize(image, self.mean, self.std, self.inplace), 'landmarks': landmarks} But this does not work because it does not go through each channel.
The normalize function called in there is this one https://github.com/pytorch/vision/blob/master/torchvision/transforms/functional.py#L191 The input is a tensor of shape (C, H, W) and mean and std can be sequences, that are internally converted to tensors. The normalization is done through broadcasting in this way: tensor.sub_(mean[:, None, None]).div_(std[:, None, None])
https://stackoverflow.com/questions/57849289/
Would it possible to use all memory of GPUs with one model?
There is a model and two GPUs. I put the model on GPU with model.cuda(). If I passed a big image to the model, it allocated all memory of GPU0 and then it raised CUDA out of memory error without allocating any memory of GPU1. Because there is only one image every forward(), I can not use such torch.nn.DataParallel things to split input. Is there any way to use all the memory of GPUs when passing a image to the model? I'm using Python3.7 and Pytorch1.1.
you can split your model into two submodule. like this: class MyModel(nn.Module): def __init__(self, split_gpus): self.large_submodule1 = ... self.large_submodule2 = ... self.split_gpus = split_gpus if split_gpus: self.large_submodule1.cuda(0) self.large_submodule1.cuda(1) def forward(self, x): x = self.large_submodule1(x) if split_gpus: x = x.cuda(1) # P2P GPU transfer return self.large_submodule2(x) from the pytorch discuss
https://stackoverflow.com/questions/57849535/
Optimizing docker image size
I am building a docker image for my python app using the base image python:3.5-slim-buster. I am running the below command inside the Dockerfile: RUN pip install --no-cache-dir -r requirements.txt which has torch library in the requirements file. After building the image it is having a size of 2.29 GB. But if I build the image without torch inside the requirements file, it has only ~900 MB. when I manually run the image and check inside the container: The torch (/usr/local/lib/python3.5/site-packages/torch) directory is 1.3GB. So even if I do a multistage build and try to copy the contents from /usr/local/lib/python3.5/site-packages to a new image, I suppose it is not going to help me. Is there any other standard optimization practice which can help me to reduce the image size?
Assuming you want a trained model of some kind from pytorch (usually neural network) you should indeed use multistage Docker build as follows (IMO at least): 1. Training model and exporting Write your script as per usual, including all dependencies you need. Train your model and save it as artifact using torchscript's torch.jit.script. 2. Second stage Using C++ write inference code loading your net and compile the source (use libtorch). 3. Final image Copy binary from previous step and put it is as Docker's entrypoint so you can run it as disposable neural net within container.
https://stackoverflow.com/questions/57855557/
Numpy random.choice probablities don't sum up to 1
I wanna randomly select sample points based on the probability distribution specified by prob for a given row. However, I get the error in np.random.choice that the probabilities don't add up to 1. This is very weird because I first normalize using the L1-norm along the rows and then I define a uniform distribution if the values are smaller than the threshold 1e-6. import numpy as np import torch.nn.functional as F prob = F.normalize(outputs, p=1, dim=1).clone().data.cpu().numpy() # outputs is a torch.Tensor of shape (14, 6890) all_zero = np.where(prob.max(1) &lt; 1e-6)[0] # find indices of rows where all values are smaller prob[all_zero] = np.full(prob.shape[1], 1 / prob.shape[1]) # fill those rows uniformly # ... somewhere later inside a method for j in range(14): sample = np.random.choice(6890, 4, replace=False, p=prob[j]) Do you understand, why that is?
As error suggests prob[j] doesn't sum to 1. Your epsilon 1e-6 is way too big to be considered insignificant, there is no need for this operation at all. If you insist, you have to redistribute zero-ed out values across what's left to 1 (and it seems you did just that actually). All in all you didn't normalize the array to 1: prob /= prob.sum(axis=1) # make it prob dist BTW. Broadcasting will extend your single number to the whole row, no need for np.full: prob[all_zero] = 1 / prob.shape[1]
https://stackoverflow.com/questions/57855659/
Caffe2 doesn't seem to see cuDNN?
I am trying to install SpConv (spatially sparse convolution library), however when running python3 setup.py bdist_wheel, I get an error which seems to be related to Caffe2 not being able to see cuDNN, as I infer from this message: CMake Error at /home/ivan/.local/lib/python3.6/site-packages/torch/share/cmake/Caffe2/Caffe2Config.cmake:96 (message): Your installed Caffe2 version uses cuDNN but I cannot find the cuDNN libraries. Please set the proper cuDNN prefixes and / or install cuDNN. I have tried reinstalling cuDNN but no luck. Can I manually point Caffe2 to cuDNN? This is because usually cuda is located in /usr/local/cuda/, however I have it in /usr/lib/cuda. Full output below: running bdist_wheel running build running build_py running build_ext Release |||||CMAKE ARGS||||| ['-DCMAKE_PREFIX_PATH=/home/ivan/.local/lib/python3.6/site-packages/torch', '-DPYBIND11_PYTHON_VERSION=3.6', '-DSPCONV_BuildTests=OFF', '-DCMAKE_CUDA_FLAGS="--expt-relaxed-constexpr" -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/mnt/home/ivan/second.pytorch/second/spconv/build/lib.linux-x86_64-3.6/spconv', '-DCMAKE_BUILD_TYPE=Release'] -- Caffe2: CUDA detected: 9.1 -- Caffe2: CUDA nvcc is: /usr/bin/nvcc -- Caffe2: CUDA toolkit directory: /usr -- Caffe2: Header version is: 9.1 -- Could NOT find CUDNN (missing: CUDNN_INCLUDE_DIR) CMake Warning at /home/ivan/.local/lib/python3.6/site-packages/torch/share/cmake/Caffe2/public/cuda.cmake:131 (message): Caffe2: Cannot find cuDNN library. Turning the option off Call Stack (most recent call first): /home/ivan/.local/lib/python3.6/site-packages/torch/share/cmake/Caffe2/Caffe2Config.cmake:88 (include) /home/ivan/.local/lib/python3.6/site-packages/torch/share/cmake/Torch/TorchConfig.cmake:40 (find_package) CMakeLists.txt:20 (find_package) -- Autodetected CUDA architecture(s): 6.1 -- Added CUDA NVCC flags for: -gencode;arch=compute_61,code=sm_61 CMake Error at /home/ivan/.local/lib/python3.6/site-packages/torch/share/cmake/Caffe2/Caffe2Config.cmake:96 (message): Your installed Caffe2 version uses cuDNN but I cannot find the cuDNN libraries. Please set the proper cuDNN prefixes and / or install cuDNN. Call Stack (most recent call first): /home/ivan/.local/lib/python3.6/site-packages/torch/share/cmake/Torch/TorchConfig.cmake:40 (find_package) CMakeLists.txt:20 (find_package) -- Configuring incomplete, errors occurred! See also "/mnt/home/ivan/second.pytorch/second/spconv/build/temp.linux-x86_64-3.6/CMakeFiles/CMakeOutput.log". See also "/mnt/home/ivan/second.pytorch/second/spconv/build/temp.linux-x86_64-3.6/CMakeFiles/CMakeError.log". Traceback (most recent call last): File "setup.py", line 99, in &lt;module&gt; zip_safe=False, File "/home/ivan/.local/lib/python3.6/site-packages/setuptools/__init__.py", line 145, in setup return distutils.core.setup(**attrs) File "/usr/lib/python3.6/distutils/core.py", line 148, in setup dist.run_commands() File "/usr/lib/python3.6/distutils/dist.py", line 955, in run_commands self.run_command(cmd) File "/usr/lib/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/usr/lib/python3/dist-packages/wheel/bdist_wheel.py", line 204, in run self.run_command('build') File "/usr/lib/python3.6/distutils/cmd.py", line 313, in run_command self.distribution.run_command(command) File "/usr/lib/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "/usr/lib/python3.6/distutils/command/build.py", line 135, in run self.run_command(cmd_name) File "/usr/lib/python3.6/distutils/cmd.py", line 313, in run_command self.distribution.run_command(command) File "/usr/lib/python3.6/distutils/dist.py", line 974, in run_command cmd_obj.run() File "setup.py", line 40, in run self.build_extension(ext) File "setup.py", line 82, in build_extension subprocess.check_call(['cmake', ext.sourcedir] + cmake_args, cwd=self.build_temp, env=env) File "/usr/lib/python3.6/subprocess.py", line 311, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['cmake', '/mnt/home/ivan/second.pytorch/second/spconv', '-DCMAKE_PREFIX_PATH=/home/ivan/.local/lib/python3.6/site-packages/torch', '-DPYBIND11_PYTHON_VERSION=3.6', '-DSPCONV_BuildTests=OFF', '-DCMAKE_CUDA_FLAGS="--expt-relaxed-constexpr" -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/mnt/home/ivan/second.pytorch/second/spconv/build/lib.linux-x86_64-3.6/spconv', '-DCMAKE_BUILD_TYPE=Release']' returned non-zero exit status 1. System: Ubuntu 18.04, CUDA 9.1, cuDNN 7.6.3
Found the problem. I needed to set CUDNN_INCLUDE_DIR to /usr/lib/cuda/include (i.e. where the cudnn.h file is located). Lesson learnt: take time to understand the error, missing: CUDNN_INCLUDE_DIR was key.
https://stackoverflow.com/questions/57856606/
pytorch questions: how to add bias term and extract its value? class vs sequential model? and softmax
I have a basic neural network model in pytorch like this: import torch import torch.nn as nn import torch.nn.functional as F class Net(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(Net, self).__init__() self.fc1 = nn.Linear(input_dim, hidden_dim) self.sigmoid = nn.Sigmoid() self.fc2 = nn.Linear(hidden_dim, output_dim) def forward(self, x): out = self.fc1(x) out = self.sigmoid(out) out = self.fc2(out) return out net = Net(400, 512,10) How can I extract bias/intercept term from net.parameters()? And is this model equivalent to using sequential()? net = nn.Sequential(nn.Linear(input_dim, hidden_dim[0]), nn.Sigmoid(), nn.Linear(hidden_dim[0], hidden_dim[1]), nn.Sigmoid(), nn.Linear(hidden_dim[1], output_dim)) Is nn.Softmax() optional at the end of either model for multi-class classification? If I understand correctly, with software it outputs probability of a certain class but without it returns predicted output? Thanks in advance for answering my newbie questions.
Let's answer questions one by one. is this model equivalent to using sequential() Short answer: No. You can see that you have added two Sigmoid and two linear layers. You can print your net and see the result: net = Net(400, 512,10) print(net.parameters()) print(net) input_dim = 400 hidden_dim = 512 output_dim = 10 model = Net(400, 512,10) net = nn.Sequential(nn.Linear(input_dim, hidden_dim), nn.Sigmoid(), nn.Linear(hidden_dim, hidden_dim), nn.Sigmoid(), nn.Linear(hidden_dim, output_dim)) print(net) The output is: Net( (fc1): Linear(in_features=400, out_features=512, bias=True) (sigmoid): Sigmoid() (fc2): Linear(in_features=512, out_features=10, bias=True) ) Sequential( (0): Linear(in_features=400, out_features=512, bias=True) (1): Sigmoid() (2): Linear(in_features=512, out_features=512, bias=True) (3): Sigmoid() (4): Linear(in_features=512, out_features=10, bias=True) ) I hope you can see where they differ. Your first question: How can I extract bias/intercept term from net.parameters() The answer: model = Net(400, 512,10) bias = model.fc1.bias print(bias) the output is: tensor([ 3.4078e-02, 3.1537e-02, 3.0819e-02, 2.6163e-03, 2.1002e-03, 4.6842e-05, -1.6454e-02, -2.9456e-02, 2.0646e-02, -3.7626e-02, 3.5531e-02, 4.7748e-02, -4.6566e-02, -1.3317e-02, -4.6593e-02, -8.9996e-03, -2.6568e-02, -2.8191e-02, -1.9806e-02, 4.9720e-02, --------------------------------------------------------------- -4.6214e-02, -3.2799e-02, -3.3605e-02, -4.9720e-02, -1.0293e-02, 3.2559e-03, -6.6590e-03, -1.2456e-02, -4.4547e-02, 4.2101e-02, -2.4981e-02, -3.6840e-03], requires_grad=True)
https://stackoverflow.com/questions/57863907/
Training with BatchNorm in pytorch
I'm wondering if I need to do anything special when training with BatchNorm in pytorch. From my understanding the gamma and beta parameters are updated with gradients as would normally be done by an optimizer. However, the mean and variance of the batches are updated slowly using momentum. So do we need to specify to the optimizer when the mean and variance parameters are updated, or does pytorch automatically take care of this? Is there a way to access the mean and variance of the BN layer so that I can make sure it was changing while I trained the model. If needed here is my model and training procedure: def bn_drop_lin(n_in:int, n_out:int, bn:bool=True, p:float=0.): "Sequence of batchnorm (if `bn`), dropout (with `p`) and linear (`n_in`,`n_out`) layers followed by `actn`." layers = [nn.BatchNorm1d(n_in)] if bn else [] if p != 0: layers.append(nn.Dropout(p)) layers.append(nn.Linear(n_in, n_out)) return nn.Sequential(*layers) class Model(nn.Module): def __init__(self, i, o, h=()): super().__init__() nodes = (i,) + h + (o,) self.layers = nn.ModuleList([bn_drop_lin(i,o, p=0.5) for i, o in zip(nodes[:-1], nodes[1:])]) def forward(self, x): x = x.view(x.shape[0], -1) for layer in self.layers[:-1]: x = F.relu(layer(x)) return self.layers[-1](x) Training: for i, data in enumerate(trainloader): # get the inputs; data is a list of [inputs, labels] inputs, labels = data # zero the parameter gradients optimizer.zero_grad() # forward + backward + optimize outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step()
Batchnorm layers behave differently depending on if the model is in train or eval mode. When net is in train mode (i.e. after calling net.train()) the batch norm layers contained in net will use batch statistics along with gamma and beta parameters to scale and translate each mini-batch. The running mean and variance will also be adjusted while in train mode. These updates to running mean and variance occur during the forward pass (when net(inputs) is called). The gamma and beta parameters are like any other pytorch parameter and are updated only once optimizer.step() is called. When net is in eval mode (net.eval()) batch norm uses the historical running mean and running variance computed during training to scale and translate samples. You can check the batch norm layers running mean and variance by displaying the layers running_mean and running_var members to ensure batch norm is updating them as expected. The learnable gamma and beta parameters can be accessed by displaying the weight and bias members of a batch norm layer respectively. Edit Below is a simple demonstration code showing that running_mean is updated during forward. Observe that it is not updated by the optimizer. &gt;&gt;&gt; import torch &gt;&gt;&gt; import torch.nn as nn &gt;&gt;&gt; layer = nn.BatchNorm1d(5) &gt;&gt;&gt; layer.train() &gt;&gt;&gt; layer.running_mean tensor([0., 0., 0., 0., 0.]) &gt;&gt;&gt; result = layer(torch.randn(5,5)) &gt;&gt;&gt; layer.running_mean tensor([ 0.0271, 0.0152, -0.0403, -0.0703, -0.0056])
https://stackoverflow.com/questions/57865112/
Simple Conv Net
I'm new on pytorch and I would like your light on a small net I try to setup. class PzConv2d(nn.Module): """ Convolution 2D Layer followed by PReLU activation """ def __init__(self, n_in_channels, n_out_channels, **kwargs): super(PzConv2d, self).__init__() self.conv = nn.Conv2d(n_in_channels, n_out_channels, bias=True, **kwargs) self.activ = nn.ReLU() def forward(self, x): x = self.conv(x) return self.activ(x) class PzPool2d(nn.Module): """ Average Pooling Layer """ def __init__(self, kernel_size, stride, padding=0): super(PzPool2d, self).__init__() self.pool = nn.AvgPool2d(kernel_size=kernel_size, stride=stride, padding=padding, ceil_mode=True, count_include_pad=False) def forward(self, x): return self.pool(x) class PzFullyConnected(nn.Module): """ Dense or Fully Connected Layer followed by ReLU """ def __init__(self, n_inputs, n_outputs, withrelu=True, **kwargs): super(PzFullyConnected, self).__init__() self.withrelu = withrelu self.linear = nn.Linear(n_inputs, n_outputs, bias=True) self.activ = nn.ReLU() def forward(self, x): x = self.linear(x) if self.withrelu: x = self.activ(x) return x class NetCNN(nn.Module): def __init__(self,n_input_channels,debug=False): super(NetCNN, self).__init__() self.n_bins = 180 self.debug = debug self.conv0 = PzConv2d(n_in_channels=n_input_channels, n_out_channels=64, kernel_size=5,padding=2) self.pool0 = PzPool2d(kernel_size=2,stride=2,padding=0) self.conv1 = PzConv2d(n_in_channels=64, n_out_channels=92, kernel_size=3,padding=2) self.pool1 = PzPool2d(kernel_size=2,stride=2,padding=0) self.conv2 = PzConv2d(n_in_channels=92, n_out_channels=128, kernel_size=3,padding=2) self.pool2 = PzPool2d(kernel_size=2,stride=2,padding=0) self.fc0 = PzFullyConnected(n_inputs=12800,n_outputs=1024) self.fc1 = PzFullyConnected(n_inputs=1024,n_outputs=self.n_bins) def num_flat_features(self, x): size = x.size()[1:] # all dimensions except the batch dimension num_features = 1 for s in size: num_features *= s return num_features def forward(self, x, dummy): # x:image tensor N_batch, Channels, Height, Width # size N, Channels:=5 filtres, H,W = 64 pixels # dummy: is not used # stage 0 conv 64 x 5x5 x = self.conv0(x) x = self.pool0(x) # stage 1 conv 92 x 3x3 x = self.conv1(x) x = self.pool1(x) # stage 2 conv 128 x 3x3 x = self.conv2(x) x = self.pool2(x) x = self.fc0(x.view(-1,self.num_flat_features(x))) x = self.fc1(x) output = x return output I have checked that the dimensions of the intermediate "x" tensor in the forward process is well shaped (at least when I send a random input image tensor). But if you see something strange let me know, please. Now, I have seen code with F."function" sequence in the forward method, instead of declaring the different layers as I have done. Does it make a difference? (Notice that I'm using F.cross_entropy as loss function, so I do not end may network by a SoftMax.) Thanks.
As you can see from pytorch doc there are "layers" and there are "functionals". You already noticed that they are quite similar, but there is a difference: A layer is often more than just a "functional" it also wraps around trainable parameters. Therefore, you can have a F.conv2d(...) in your forward() function, but you will have to manually provide (store/update) the weights/kernel for this convolution. On the other hand, if you are using nn.Conv2d pytorch takes care of managing/storing/updating the weights/kernels for you. Some layers have no internal parameters/buffers (e.g., nn.ReLU, nn.Softmax etc.) thus you can choose if you want to have a "layer" for this operation or only calling the appropriate functional in your forward() function. It is a matter of convenience and habits, it's up to you.
https://stackoverflow.com/questions/57885446/
Memory error when iterate over two dataloaders simultaneously in pytorch
I am trying to train my model using 2 dataloaders from 2 different datasets. I found how to set up this by using cycle() and zip() because my datasets are not the same length from here: How to iterate over two dataloaders simultaneously using pytorch? File "/home/Desktop/example/train.py", line 229, in train_2 for i, (x1, x2) in enumerate(zip(cycle(train_loader_1), train_loader_2)): File "/home/.conda/envs/3dcnn/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 346, in __next__ data = self.dataset_fetcher.fetch(index) # may raise StopIteration File "/home/.conda/envs/3dcnn/lib/python3.7/site-packages/torch/utils/data/_utils/fetch.py", line 47, in fetch return self.collate_fn(data) File "/home/.conda/envs/3dcnn/lib/python3.7/site-packages/torch/utils/data/_utils/collate.py", line 80, in default_collate return [default_collate(samples) for samples in transposed] File "/home/.conda/envs/3dcnn/lib/python3.7/site-packages/torch/utils/data/_utils/collate.py", line 80, in &lt;listcomp&gt; return [default_collate(samples) for samples in transposed] File "/home/.conda/envs/3dcnn/lib/python3.7/site-packages/torch/utils/data/_utils/collate.py", line 56, in default_collate return torch.stack(batch, 0, out=out) RuntimeError: [enforce fail at CPUAllocator.cpp:64] . DefaultCPUAllocator: can't allocate memory: you tried to allocate 154140672 bytes. Error code 12 (Cannot allocate memory) I tried to solve that by setting num_workers=0, decreasing the batch size, using pinned_memory=False and shuffle=False... But none of it worked... I am having 256GB of RAM and 4 NVIDIA TESLA V100 GPUs. I tried to run it just by not training in 2 dataloaders simultaneously but individually and it worked. However for my project I need this parallel training with 2 datasets...
Based on this discussion, instead of cycle() and zip() I avoid any errors by using: try: data, target = next(dataloader_iterator) except StopIteration: dataloader_iterator = iter(dataloader) data, target = next(dataloader_iterator) kudos to @srossi93 from this pytorch post!
https://stackoverflow.com/questions/57888191/
PyTorch: Dataloader for time series task
I have a Pandas dataframe with n rows and k columns loaded into memory. I would like to get batches for a forecasting task where the first training example of a batch should have shape (q, k) with q referring to the number of rows from the original dataframe (e.g. 0:128). The next example should be (128:256, k) and so on. So, ultimately, one batch should have the shape (32, q, k) with 32 corresponding to the batch size. Since TensorDataset from data_utils does not work here, I am wondering what the best way would be. I tried to use np.array_split() to get as first dimension the number of possible splits of q values in order to write a custom DataLoader but then reshaping is not guaranteed to work since not all arrays have the same shape. Here is a minimal example to make it more clear. In this case, batch size is 3 and q is 2: import pandas as pd import numpy as np df = pd.DataFrame(data=np.arange(0,30).reshape(10,3),columns=['A','B','C']) The dataset: A B C 0 0 1 2 1 3 4 5 2 6 7 8 3 9 10 11 4 12 13 14 5 15 16 17 6 18 19 20 7 21 22 23 8 24 25 26 9 27 28 29 The first batch in this case should have the shape (3,2,3) and look like: array([[[ 0., 1., 2.], [ 3., 4., 5.]], [[ 3., 4., 5.], [ 6., 7., 8.]], [[ 6., 7., 8.], [ 9., 10., 11.]]])
You can write your analog of the TensorDataset. To do this you need to inherit from the Dataset class. from torch.utils.data import Dataset, DataLoader class MyDataset(Dataset): def __init__(self, data_frame, q): self.data = data_frame.values self.q = q def __len__(self): return self.data.shape[0] // self.q def __getitem__(self, index): return self.data[index * self.q: (index+1) * self.q]
https://stackoverflow.com/questions/57893415/
How to repeat tensor in a specific new dimension in PyTorch
If I have a tensor A which has shape [M, N], I want to repeat the tensor K times so that the result B has shape [M, K, N] and each slice B[:, k, :] should has the same data as A. Which is the best practice without a for loop. K might be in other dimension. torch.repeat_interleave() and tensor.repeat() does not seem to work. Or I am using it in a wrong way.
tensor.repeat should suit your needs but you need to insert a unitary dimension first. For this we could use either tensor.unsqueeze or tensor.reshape. Since unsqueeze is specifically defined to insert a unitary dimension we will use that. B = A.unsqueeze(1).repeat(1, K, 1) Code Description A.unsqueeze(1) turns A from an [M, N] to [M, 1, N] and .repeat(1, K, 1) repeats the tensor K times along the second dimension.
https://stackoverflow.com/questions/57896357/
Is it possible to load a pretrained Pytorch model from a GCS bucket URL without first persisting locally?
I'm asking this in the context of Google Dataflow, but also generally. Using PyTorch, I can reference a local directory containing multiple files that comprise a pretrained model. I happen to be working with a Roberta model, but the interface is the same for others. ls some-directory/ added_tokens.json config.json merges.txt pytorch_model.bin special_tokens_map.json vocab.json from pytorch_transformers import RobertaModel # this works model = RobertaModel.from_pretrained('/path/to/some-directory/') However, my pretrained model is stored in a GCS bucket. Let's call it gs://my-bucket/roberta/. In the context of loading this model in Google Dataflow, I'm trying to remain stateless and avoid persisting to disk, so my preference would be to get this model straight from GCS. As I understand it, the PyTorch general interface method from_pretrained() can take the string representation of a local dir OR a URL. However, I can't seem to load the model from a GCS URL. # this fails model = RobertaModel.from_pretrained('gs://my-bucket/roberta/') # ValueError: unable to parse gs://mahmed_bucket/roberta-base as a URL or as a local path If I try to use the public https URL of the directory blob, it will also fail, although that is likely due to lack of authentication since the credentials referenced in the python environment that can create clients don't translate to public requests to https://storage.googleapis # this fails, probably due to auth bucket = gcs_client.get_bucket('my-bucket') directory_blob = bucket.blob(prefix='roberta') model = RobertaModel.from_pretrained(directory_blob.public_url) # ValueError: No JSON object could be decoded # and for good measure, it also fails if I append a trailing / model = RobertaModel.from_pretrained(directory_blob.public_url + '/') # ValueError: No JSON object could be decoded I understand that GCS doesn't actually have subdirectories and it's actually just being a flat namespace under the bucket name. However, it seems like I'm blocked by the necessity of authentication and a PyTorch not speaking gs://. I can get around this by persisting the files locally first. from pytorch_transformers import RobertaModel from google.cloud import storage import tempfile local_dir = tempfile.mkdtemp() gcs = storage.Client() bucket = gcs.get_bucket(bucket_name) blobs = bucket.list_blobs(prefix=blob_prefix) for blob in blobs: blob.download_to_filename(local_dir + '/' + os.path.basename(blob.name)) model = RobertaModel.from_pretrained(local_dir) But this seems like such a hack, and I keep thinking I must be missing something. Surely there's a way to stay stateless and not have to rely on disk persistence! So is there a way to load a pretrained model stored in GCS? Is there a way to authenticate when doing the public URL request in this context? Even if there is a way to authenticate, will the non-existence of subdirectories still be an issue? Thanks for the help! I'm also happy to be pointed to any duplicate questions 'cause I sure couldn't find any. Edits and Clarifications My Python session is already authenticated to GCS, which is why I'm able to download the blob files locally and then point to that local directory with load_frompretrained() load_frompretrained() requires a directory reference because it needs all the files listed at the top of the question, not just pytorch-model.bin To clarify question #2, I was wondering if there's some way of giving the PyTorch method a request URL that had encrypted credentials embedded or something like that. Kind of a longshot, but I wanted to make sure I hadn't missed anything. To clarify question #3 (in addition to the comment on one answer below), even if there's a way to embed credentials in the URL that I don't know about, I still need to reference a directory rather than a single blob, and I don't know if the GCS subdirectory would be recognized as such because (as the Google docs state) subdirectories in GCS are an illusion and they don't represent a real directory structure. So I think this question is irrelevant or at least blocked by question #2, but it's a thread I chased for a bit so I'm still curious.
MAJOR EDIT: You can install wheel files on Dataflow workers, and you can also use worker temp storage to persist binary files locally! It's true that (currently as of Nov 2019) you can't do this by supplying a --requirements argument. Instead you have to use setup.py like this. Assume any constants IN CAPS are defined elsewhere. REQUIRED_PACKAGES = [ 'torch==1.3.0', 'pytorch-transformers==1.2.0', ] setup( name='project_dir', version=VERSION, packages=find_packages(), install_requires=REQUIRED_PACKAGES) Run script python setup.py sdist python project_dir/my_dataflow_job.py \ --runner DataflowRunner \ --project ${GCP_PROJECT} \ --extra_package dist/project_dir-0.1.0.tar.gz \ # SNIP custom args for your job and required Dataflow Temp and Staging buckets # And within the job, here's downloading and using the model from GCS in the context of a custom Dataflow operator. For convenience we wrapped a few utility methods in a SEPARATE MODULE (important to get around Dataflow dependency uploads) and imported them at the LOCAL SCOPE of the custom operator, not global. class AddColumn(beam.DoFn): PRETRAINED_MODEL = 'gs://my-bucket/blah/roberta-model-files' def get_model_tokenizer_wrapper(self): import shutil import tempfile import dataflow_util as util try: return self.model_tokenizer_wrapper except AttributeError: tmp_dir = tempfile.mkdtemp() + '/' util.download_tree(self.PRETRAINED_MODEL, tmp_dir) model, tokenizer = util.create_model_and_tokenizer(tmp_dir) model_tokenizer_wrapper = util.PretrainedPyTorchModelWrapper( model, tokenizer) shutil.rmtree(tmp_dir) self.model_tokenizer_wrapper = model_tokenizer_wrapper logging.info( 'Successfully created PretrainedPyTorchModelWrapper') return self.model_tokenizer_wrapper def process(self, elem): model_tokenizer_wrapper = self.get_model_tokenizer_wrapper() # And now use that wrapper to process your elem however you need. # Note that when you read from BQ your elements are dictionaries # of the column names and values for each BQ row. Utility functions in SEPARATE MODULE within the codebase. In our case in the project root this was in dataflow_util/init.py but you don't have to do it that way. from contextlib import closing import logging import apache_beam as beam import numpy as np from pytorch_transformers import RobertaModel, RobertaTokenizer import torch class PretrainedPyTorchModelWrapper(): def __init__(self, model, tokenizer): self.model = model self.tokenizer = tokenizer def download_tree(gcs_dir, local_dir): gcs = beam.io.gcp.gcsio.GcsIO() assert gcs_dir.endswith('/') assert local_dir.endswith('/') for entry in gcs.list_prefix(gcs_dir): download_file(gcs, gcs_dir, local_dir, entry) def download_file(gcs, gcs_dir, local_dir, entry): rel_path = entry[len(gcs_dir):] dest_path = local_dir + rel_path logging.info('Downloading %s', dest_path) with closing(gcs.open(entry)) as f_read: with open(dest_path, 'wb') as f_write: # Download the file in chunks to avoid requiring large amounts of # RAM when downloading large files. while True: file_data_chunk = f_read.read( beam.io.gcp.gcsio.DEFAULT_READ_BUFFER_SIZE) if len(file_data_chunk): f_write.write(file_data_chunk) else: break def create_model_and_tokenizer(local_model_path_str): """ Instantiate transformer model and tokenizer :param local_model_path_str: string representation of the local path to the directory containing the pretrained model :return: model, tokenizer """ model_class, tokenizer_class = (RobertaModel, RobertaTokenizer) # Load the pretrained tokenizer and model tokenizer = tokenizer_class.from_pretrained(local_model_path_str) model = model_class.from_pretrained(local_model_path_str) return model, tokenizer And there you have it folks! More details can be found here: https://beam.apache.org/documentation/sdks/python-pipeline-dependencies/ What I've discovered is that this whole chain of questioning is irrelevant because Dataflow only allows you to install source distribution packages on workers which means you can't actually install PyTorch. When you supply a requirements.txt file, Dataflow will install with the --no-binary flag which prevents installation of Wheel (.whl) packages and only allows source distributions (.tar.gz). I decided trying to roll my own source distribution for PyTorch on Google Dataflow where it's half C++ and part Cuda and part who knows what was a fool's errand. Thanks for the input along the way y'all.
https://stackoverflow.com/questions/57898998/