instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Integrating ROS with pycharm
I wanted to run ROS in PyCharm, but could not find that .desktop file as mentioned here in which changes should be made. Moreover, I want to use the same environment that is created for PyTorch, do not want to change the interpreter. Can someone help me out with this? Regards.
You could add a virtual environment with the following instructions, then you should add ROS distpackages (roslib) on it with this instruction. File > Settings (or Ctrl+Alt+s as shortcut)> Project: > Project interpreter. In the project interpreter dropdown list, you can specify ROS Python interpreter by selecting th...
https://stackoverflow.com/questions/55246952/
What is the best way to use multiprocessing CPU inference for PyTorch models?
I have to productionize a PyTorch BERT Question Answer model. The CPU inference is very slow for me as for every query the model needs to evaluate 30 samples. Out of the result of these 30 samples, I pick the answer with the maximum score. GPU would be too costly for me to use for inference. Can I leverage multiproces...
Another possible way to get better performance would be to reduce the model as much as possible. One of the most promising techniques is quantized and binarized neural networks. Here are some references: https://arxiv.org/abs/1603.05279 https://arxiv.org/abs/1602.02505
https://stackoverflow.com/questions/55253708/
How to integrate LIME with PyTorch?
Using this mnist image classification model : %reset -f import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import torch.utils.data as data_utils import numpy as np import m...
Here's my solution: Lime expects an image input of type numpy. This is why you get the attribute error and a solution would be to convert the image (from Tensor) to numpy before passing it to the explainer object. Another solution would be to select a specific image with the test_loader_subset and convert it with img ...
https://stackoverflow.com/questions/55257039/
PyTorch specify model parameters
I am trying to create a convolutional model in PyTorch where one layer is fixed (initialized to prescribed values) another layer is learned (but initial guess taken from prescribed values). Here is a sample code for model definition: import torch.nn as nn class Net(nn.Module): def __init__(self, weights_fixed...
Just wrap the learnable parameter with nn.Parameter (requires_grad=True is the default, no need to specify this), and have the fixed weight as a Tensor without nn.Parameter wrapper. All nn.Parameter weights are automatically added to net.parameters(), so when you do training like optimizer = optim.SGD(net.parameters()...
https://stackoverflow.com/questions/55267538/
How to return intermideate gradients (for non-leaf nodes) in pytorch?
My question is concerning the syntax of pytorch register_hook. x = torch.tensor([1.], requires_grad=True) y = x**2 z = 2*y x.register_hook(print) y.register_hook(print) z.backward() outputs: tensor([2.]) tensor([4.]) this snippet simply prints the gradient of z w.r.t x and y, respectively. Now my (most likely ...
I think you can use those hooks to store the gradients in a global variable: grads = [] x = torch.tensor([1.], requires_grad=True) y = x**2 + 1 z = 2*y x.register_hook(lambda d:grads.append(d)) y.register_hook(lambda d:grads.append(d)) z.backward() But you most likely also need to remember the corresponding tensor...
https://stackoverflow.com/questions/55305262/
TypeError: forward() missing 1 required positional argument: 'hidden'
I'm trying to visualize my GRU model using PyTorchViz but every time I run this code it gives me an error. I want something like this in the import torch from torch import nn from torchviz import make_dot, make_dot_from_trace model = IC_V6(f.tokens) x = torch.randn(1,8) make_dot(model(x), params=dict(model.named_...
I think the error message is pretty straight forward. You have two positional arguments input_tokens and hidden for your forward(). Python complains that one of them (hidden) is missing when you call your forward() function. Looking at your code, you call your forward like this: model(x) So x is mapped to input...
https://stackoverflow.com/questions/55341072/
Error when trying to send neural net generated image in flask
I'm making a basic api to request for generated images from a generator model from pytorch. I've done this using flask and I'm running it locally on MacOS. Everything works and the image returns but then python quits unexpectedly. Here is the code and the error: Error: 2019-03-25 16:21:23.514 Python[78776:1407049]...
I worked out from people having the same problem: https://github.com/matplotlib/matplotlib/issues/11094 Closing plt before returning fixes the error.
https://stackoverflow.com/questions/55342589/
In language modeling, why do I have to init_hidden weights before every new epoch of training? (pytorch)
I have a question about the following code in pytorch language modeling: print("Training and generating...") for epoch in range(1, config.num_epochs + 1): total_loss = 0.0 model.train() hidden = model.init_hidden(config.batch_size) for ibatch, i in enumerate(range(0, train_len...
The hidden state stores the internal state of the RNN from predictions made on previous tokens in the current sequence, this allows RNNs to understand context. The hidden state is determined by the output of the previous token. When you predict for the first token of any sequence, if you were to retain the hidden sta...
https://stackoverflow.com/questions/55350811/
How to deal with mini-batch loss in Pytorch?
I feed mini-batch data to model, and I just want to know how to deal with the loss. Could I accumulate the loss, then call the backward like: ... def neg_log_likelihood(self, sentences, tags, length): self.batch_size = sentences.size(0) logits = self.__get_lstm_features(sentences, length) ...
The loss has to be reduced by mean using the mini-batch size. If you look at the native PyTorch loss functions such as CrossEntropyLoss, there is a separate parameter reduction just for this and the default behaviour is to do mean on the mini-batch size.
https://stackoverflow.com/questions/55368741/
Torch allocates zero GPU memory on PyTorch
I am trying to use GPU to train my model but it seems that torch fails to allocate GPU memory. My model is a RNN built on PyTorch device = torch.device('cuda: 0' if torch.cuda.is_available() else "cpu") rnn = RNN(n_letters, n_hidden, n_categories_train) rnn.to(device) criterion = nn.NLLLoss() criterion.to(device) op...
Your problem is that to() is not an in-place operation. If you call rnn.to(device) it will return a new object / model located on the desired device. But it will not move the old object anywhere! So changing: rnn = RNN(n_letters, n_hidden, n_categories_train) rnn.to(device) to: rnn = RNN(n_letters, n_hidden, n_cat...
https://stackoverflow.com/questions/55368861/
In Colaboratory, CUDA cannot be used for the torch
The error message is as follows: RuntimeError Traceback (most recent call last) <ipython-input-24-06e96beb03a5> in <module>() 11 12 x_test = np.array(test_features) ---> 13 x_test_cuda = torch.tensor(x_test, dtype=torch.float).cuda() 14 test = torch.utils.data.TensorDataset(x_test_cuda) ...
Click on Runtime and select Change runtime type. Now in Hardware Acceleration, select GPU and hit Save.
https://stackoverflow.com/questions/55368921/
How to train a neural network model with bert embeddings instead of static embeddings like glove/fasttext?
I am looking for some heads up to train a conventional neural network model with bert embeddings that are generated dynamically (BERT contextualized embeddings which generates different embeddings for the same word which when comes under different context). In normal neural network model, we would initialize the model...
If you are using Pytorch. You can use https://github.com/huggingface/pytorch-pretrained-BERT which is the most popular BERT implementation for Pytorch (it is also a pip package!). Here I'm just going to outline how to use it properly. For this particular problem there are 2 approaches - where you obviously cannot use ...
https://stackoverflow.com/questions/55369821/
Trying to understand Pytorch's implementation of LSTM
I have a dataset containing 1000 examples where each example has 5 features (a,b,c,d,e). I want to feed 7 examples to an LSTM so it predicts the feature (a) of the 8th day. Reading Pytorchs documentation of nn.LSTM() I came up with the following: input_size = 5 hidden_size = 10 num_layers = 1 output_size = 1 lstm = ...
When I extend your code to a full example -- I also added some comments to may help -- I get the following: import torch import torch.nn as nn input_size = 5 hidden_size = 10 num_layers = 1 output_size = 1 lstm = nn.LSTM(input_size, hidden_size, num_layers) fc = nn.Linear(hidden_size, output_size) X = [ [[1,2,3...
https://stackoverflow.com/questions/55408365/
PyTorch datasets: ImageFolder and subfolder filtering
I would like to use ImageFolder to create an Image Dataset. My current image directory structure looks like this: /root -- train/ ---- 001.jpg ---- 002.jpg ---- .... -- test/ ---- 001.jpg ---- 002.jpg ---- .... I would like to have a dataset dedicated to training data, and a dataset dedicated to test data. As I un...
ImageFolder expects the data folder (the one that you pass as root) to contain subfolders representing the classes to which its images belong. Something like this: data/ ├── train/ | ├── class_0/ | | ├── 001.jpg | | ├── 002.jpg | | └── 003.jpg | └── class_1/ | ├── 004.jpg | └── 005.jpg └── t...
https://stackoverflow.com/questions/55435832/
ModuleNotFoundError: No module named 'torch._C'
I want to import the torch,but then the interpreter return this result,i have no idea how to deal with it Traceback (most recent call last): File "D:/Programing/tool/Python/learn_ml_the_hard_way/ML/scipy1.py", line 1, in <module> import torch File "D:\Programing\python\Anaconda3.5\lib\site-packages\torc...
I had the same problem and followed the instructions in this link You can also find the torch path with this command if needed: sudo find / -iname torch
https://stackoverflow.com/questions/55441939/
Pytorch Not Updating Variables in .step()
I'm attempting to convert old code to PyTorch code as an experiment. Ultimately, I will be doing regression on a 10,000+ x 100 Matrix, updating weights and whatnot appropriately. Trying to learn, I'm slowly scaling up on toy examples. I'm hitting a wall with the following sample code. import torch import torch.nn as...
It looks like a case of cargo programming to me. Notice that your Model class doesn't make use of self in forward, so it is effectively a "regular" (non-method) function, and model is entirely stateless. The simplest fix to your code is to make optimizer aware of w and b, by creating it as optimizer = torch.optim.SGD(...
https://stackoverflow.com/questions/55444804/
Querying an image with bilinear interpolation e.e. finding RGB value in the fractional coordinates using Pytorch
I have a input T1 of size (1,256,256,3) i.e. images/grid of batch size 1. I have another tensor T2 of size (1, N, 2) i.e. tensor consisting of coordinates i.e. [ [10.5 , 200.787], [150.568, 190.456], …]. How do I compute functional values (using bilinear interpolation) of coordinates in T2 from T1 data? Thanks for any...
try grid_sample: torch.nn.functional.grid_sample(input, grid, mode='bilinear', padding_mode='zeros') Given an input and a flow-field grid, computes the output using input values and pixel locations from grid. For each output location output[n, :, h, w], the size-2 vector grid[n, h, w] specifies input pixel location...
https://stackoverflow.com/questions/55472629/
Iterate over two Pytorch tensors at once?
I have two Pytorch tensors (really, just 1-D lists), t1 and t2. Is it possible to iterate over them in parallel, i.e. do something like for a,b in zip(t1,t2) ? Thanks.
For me (Python version 3.7.3 and PyTorch version 1.0.0) the zip function works as expected with PyTorch tensors: >>> import torch >>> t1 = torch.ones(3) >>> t2 = torch.zeros(3) >>> list(zip(t1, t2)) [(tensor(1.), tensor(0.)), (tensor(1.), tensor(0.)), (tensor(1.), tensor(0.))] The...
https://stackoverflow.com/questions/55486631/
Unpickling saved pytorch model throws AttributeError: Can't get attribute 'Net' on <module '__main__' despite adding class definition inline
I'm trying to serve a pytorch model in a flask app. This code was working when I ran this on a jupyter notebook earlier but now I'm running this within a virtual env and apparently it can't get attribute 'Net' even though the class definition is right there. All the other similar questions tell me to add the class defi...
(This is a partial answer) I don't think torch.save(model,'model.pt') works from the command prompt, or when a model is saved from one script running as '__main__' and loaded from another. The reason is that torch must be automatically loading the module that was used to save the file, and it gets the module name from ...
https://stackoverflow.com/questions/55488795/
How to make the convolution in pytorch associative?
The discrete convolution is by definition associative. But when I try to verify this in pytorch, I can not find get a plausible result. The associative law is $f*(g*\psi)=(f * g)*\psi$, so I create three discrete functions centered at zero(as tensors) and convolve them with proper zero paddings so that all non-zero el...
Long story short, this is because of batching. The first argument of torch.conv2d is interpreted as [batch, channel, height, width], the second as [out_channel, in_channel, height, width] and the output as [batch, channel, height, width]. So if you call conv2d(a, conv2d(b, c)), you treat b's leading dimension as batch ...
https://stackoverflow.com/questions/55499891/
How to change (assign) new value in FloatTensor, Pytorch?
I am changing/assigning the value on the array(torch.cuda.floatTensor). I tried some way but it does not work. Please help me! #1 #dis is [torch.cuda.FloatTensor of size 3185x1 (GPU 0)] s = dis.size(0) #3185 for i in range (0,s,1): if (dis[i,0] &lt; 0): dis[i,0]== 0 #There is no error but It does not wor...
IIUC, you need to replace values smaller than 0 with 0, Just use torch.clamp, which is meant for such use cases: dis = dis.clamp(min=0) Example: import torch dis = torch.tensor([[1], [-3], [0]]) #tensor([[ 1], # [-3], # [ 0]]) dis.clamp(min=0) #tensor([[1], # [0], # [0]])
https://stackoverflow.com/questions/55506634/
Differences between F.relu(X) and torch.max(X, 0)
I am trying to implement the following loss function To me, the most straight forword implementation would be using torch.max losses = torch.max(ap_distances - an_distances + margin, torch.Tensor([0])) However, I saw other implementations on github using F.relu losses = F.relu(ap_distances - an_distances + margi...
torch.max is not differentiable according to this discussion. A loss function needs to be continuous and differentiable to do backprop. relu is differentiable as it can be approximated and hence the use of it in a loss function.
https://stackoverflow.com/questions/55545354/
PyTorch will not fit straight line to two data points
I'm facing issues in fitting a simple y= 4x1 line with 2 data points using pytorch. While running the inference code, the model seems to output same value to any input which is strange. Pls find the code attached along with the data files used by me. Appreciate any help here. import torch import numpy as np import pan...
Your model is collapsing. You can probably see that based on the prints. You may want to use a lower learning rate (1e-5, 1e-6, etc.). Switching from SGD(...)to Adam(...) may be easier if you do not have experience and want less trouble fine-tuning these hparams. Also, maybe 100 epochs is not enough. As you did not sha...
https://stackoverflow.com/questions/55558978/
How to do element wise multiplication for two 4D unequal size tensors in pytorch?
I have got a tensor A and Tensor B. Size of A = [2,64,56,56] Size of B = [2,64,29,29] How can I perform torch.mul(A,B)? The tensors are of unequal size. RuntimeError: shape [2, 64, 56, 56] is invalid for input of size 107648
You can check out the documentation here: https://pytorch.org/docs/stable/torch.html#torch.mul There, you can read: The shapes of input and other must be broadcastable. You can read about broadcastability here: https://pytorch.org/docs/stable/notes/broadcasting.html#broadcasting-semantics Lastly, it probably ma...
https://stackoverflow.com/questions/55559610/
How can i solve backward() got an unexpected keyword argument 'retain_variables'?
I write the code following below but I got this error: TypeError: backward() got an unexpected keyword argument 'retain_variables' My code is: def learn(self, batch_state, batch_next_state, batch_reward, batch_action): outputs = self.model(batch_state).gather(1, batch_action.unsqueeze(1)).squeeze(1) next_ou...
I was having the same problem. This solution worked for me. td_loss.backward(retain_graph = True) It worked.
https://stackoverflow.com/questions/55564676/
I don't understand the code for training a classifier in pytorch
I don't understand the line labels.size(0). I'm new to Pytorch and been quite confused about the data structure. correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) ...
labels is a Tensor with dimensions [N, 1], where N is equal to the number of samples in the batch. .size(...) returns a subclass of tuple (torch.Size) with the dimensions of the Tensor, and .size(0) returns an integer with the value of the first (0-based) dimension (i.e., N).
https://stackoverflow.com/questions/55565687/
Explicit slicing across a particular dimension
I've got a 3D tensor x (e.g 4x4x100). I want to obtain a subset of this by explicitly choosing elements across the last dimension. This would have been easy if I was choosing the same elements across last dimension (e.g. x[:,:,30:50] but I want to target different elements across that dimension using the 2D tensor indi...
Iterating over the idx, and collecting the slices is not a bad option if the number of 'rows' isn't too large (and the size of the sizes is relatively big). In [55]: x = np.array([[1,2,3,4,5,6],[10,20,30,40,50,60]]) In [56]: idx = [1,3] ...
https://stackoverflow.com/questions/55572737/
Whats the equivalent of tf.nn.softmax_cross_entropy_with_logits in pytorch?
I was trying to replicate a code ,which was written in tensorflow ,with pytorch. I came across a loss function in tensorflow, softmax_cross_entropy_with_logits.I was looking for an equivalent of it in pytorch and i found torch.nn.MultiLabelSoftMarginLoss,though im not quite sure it is the right function.Also i dont kno...
Use torch.nn.CrossEntropyLoss(). It combines both softmax and cross-entropy. From documentation: This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class. Example: # define loss function loss_fn = torch.nn.CrossEntropyLoss(reduction='mean') # during training for (x, y) in train_loader: ...
https://stackoverflow.com/questions/55577519/
Unable to save Pytorch model to Google Drive in Google Colab?
I am trying to save my model to my drive on google colab. I have used the following code to mount my Google Drive- from google.colab import drive drive.mount('/content/gdrive') After all the preprocessing, model definition and training, I want to save my model to the drive because training it will take a long time. ...
You likely need a leading / in your path. Try changing this line: path = f'content/gdrive/My Drive/Machine Learning Models/kaggle_jigsaw_{model_name}_iter_{iter}.pth' to: path = f'/content/gdrive/My Drive/Machine Learning Models/kaggle_jigsaw_{model_name}_iter_{iter}.pth'
https://stackoverflow.com/questions/55596375/
How does the apply(fn) function in pytorch work with a function without return statement as argument?
I have some questions about the following code fragments: &gt;&gt;&gt; def init_weights(m): print(m) if type(m) == nn.Linear: m.weight.data.fill_(1.0) print(m.weight) &gt;&gt;&gt; net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2)) &gt;&gt;&gt; net.apply(init_weights) apply...
We find the answers to your questions in said documentation of torch.nn.Module.apply(fn): Applies fn recursively to every submodule (as returned by .children()) as well as self. Typical use includes initializing the parameters of a model (see also torch-nn-init). Why does this code sample work, althouh there...
https://stackoverflow.com/questions/55613518/
Using Multiple GPUs outside of training in PyTorch
I'm calculating the accumulated distance between each pair of kernel inside a nn.Conv2d layer. However for large layers it runs out of memory using a Titan X with 12gb of memory. I'd like to know if it is possible to divide such calculations across two gpus. The code follows: def ac_distance(layer): total = 0 ...
Parallelism while training neural networks can be achieved in two ways. Data Parallelism - Split a large batch into two and do the same set of operations but individually on two different GPUs respectively Model Parallelism - Split the computations and run them on different GPUs As you have asked in the question, y...
https://stackoverflow.com/questions/55624102/
How does one dynamically add new parameters to optimizers in Pytorch?
I was going through this post in the pytorch forum, and I also wanted to do this. The original post removes and adds layers but I think my situation is not that different. I also want to add layers or more filters or word embeddings. My main motivation is that the AI agent does not know the whole vocabulary/dictionary ...
Just to add an answer to the title of your question: "How does one dynamically add new parameters to optimizers in Pytorch?" You can append params at any time to the optimizer: import torch import torch.optim as optim model = torch.nn.Linear(2, 2) # Initialize optimizer optimizer = optim.Adam(model.parameters(), l...
https://stackoverflow.com/questions/55640836/
How to convert BatchNorm weight of caffe to pytorch BathNorm?
BathNorm and Scale weight of caffe model can be read from pycaffe, which are three weights in BatchNorm and two weights in Scale. I tried to copy those weights to pytorch BatchNorm with codes like this: if 'conv3_final_bn' == name: assert len(blobs) == 3, '{} layer blob count: {}'.format(name, len(blobs)) torc...
Got it! There is still a third parameter in BatchNorm of caffe. Codes should be: if 'conv3_final_bn' == name: assert len(blobs) == 3, '{} layer blob count: {}'.format(name, len(blobs)) torch_mod['conv3_final_bn.running_mean'] = blobs[0].data / blobs[2].data[0] torch_mod['conv3_final_bn.running_var'] = blob...
https://stackoverflow.com/questions/55644109/
How to use torch.nn.CrossEntropyLoss as autoencoder's reconstruction loss?
I want to compute the reconstruction accuracy of my autoencoder using CrossEntropyLoss: ae_criterion = nn.CrossEntropyLoss() ae_loss = ae_criterion(X, Y) where X is the autoencoder's reconstruction and Y is the target (since it is an autoencoder, Y is the same as the original input X). Both X and Y have shape [42, 3...
For CrossEntropyLoss, shape of the Y must be (42, 32), each element must be a Long scalar in the interval [0, 129]. You may want to use BCELoss or BCEWithLogitsLoss for your problem.
https://stackoverflow.com/questions/55651920/
How can I use KNN, Random Forest models in Pytorch?
This may seem like a X Y problem, but initially I had huge data and I was not able to train in given resources (RAM problem). So I thought I could use batch feature of Pytorch. But I want to use Methods like KNN, Random Forest, Clustering except Deep Learning. So is it possible or can I use scikit libraries in Pytorch?...
Update Currently, there are some sklearn alternatives utilizing GPU, most prominent being cuML (link here) provided by rapidsai. Previous answer I would advise against using PyTorch solely for the purpose of using batches. Argumentation goes as follows: scikit-learn has docs about scaling where one can find MiniBatchK...
https://stackoverflow.com/questions/55663672/
How to fix 'ImportError: /home/... .../lib/libtorch.so.1: undefined symbol: nvrtcGetProgramLogSize' in DGL?
I get an error in the importation of pytorch inside dgl (Deep Graph Library by DeepMind), concretely: ImportError: /home/user/anaconda3/envs/my_env/lib/python3.7/site-packages/torch/lib/libtorch.so.1: undefined symbol: nvrtcGetProgramLogSize I tried to reinstall pytorch (uninstall reinstall with conda un/install). I ...
I also ran into this, but I actually wanted to use GPU, so installing pytorch-cpu was not an option for me. Instead, installing pytorch package from pytorch channel (instead of defaults) solved the issue for me: conda install pytorch --channel pytorch
https://stackoverflow.com/questions/55665606/
Manage memory differently on train and test time pytorch
Currently I'm writing a segmentation model based on U-net with pytorch and I want to use something similar to inverted residual introduced on mobilenet v2 to improve the model's speed on cpu. pytorch code for mobile netv2 Then I realize that the model uses a lot more memory on train phase and test phase. While the mod...
After reading the official pytorch code for resnet, I realize I shouldn't give all variables a name.aka I shouldn't write: conv1 = self.conv1(x) conv2 = self.conv2(conv1) I should just write: out = self.conv1(x) out = self.conv2(out) On this way nothing refers to obj corresponds to conv1 after it is used and pyth...
https://stackoverflow.com/questions/55667005/
Torch.cuda.is_available() keeps switching to False
I have tried several solutions which hinted at what to do when the CUDA GPU is available and CUDA is installed but the Torch.cuda.is_available() returns False. They did help but only temporarily, meaning torch.cuda-is_available() reported True but after some time, it switched back to False. I use CUDA 9.0.176 and GTX 1...
The reason for torch.cuda.is_available() resulting False is the incompatibility between the versions of pytorch and cudatoolkit. As on Jun-2022, the current version of pytorch is compatible with cudatoolkit=11.3 whereas the current cuda toolkit version = 11.7. Source Solution: Uninstall Pytorch for a fresh installatio...
https://stackoverflow.com/questions/55717751/
PyTorch: Batch Outer-Addition
I have two PyTorch tensors: A and B, both of shape (b, c, 3). I want to make outer product C of A and B so that the resulting shape is (b, c, 3, 3), and replace the multiplication operation with addition. How should I do it?
You can add a corresponding singleton dimension: C = A[..., None] + B[..., None, :] For example, with batch and channel dimensions equal to 1 (b=1, c=1): import torch A = torch.tensor([[[1, 2, 3.]]]) B = torch.tensor([[[4., 5., 6.]]]) A[..., None] + B[..., None, :] Out[ ]: tensor([[[[5., 6., 7.], [6., 7....
https://stackoverflow.com/questions/55739993/
Missing Keys in state_dict
I am having problems loading my model on google colab. here is the code: I have attached the code below I have tried changing the name of the statedict and it does not help basically, I am trying to save my model for later use, but, this is becoming extremely difficult since I am not being able to properly save and l...
You need to access the 'model_state_dict' key inside the loaded checkpoint. Try: netG.load_state_dict(torch.load('generator.pth')['model_state_dict']) You'll probably need to apply the same fix to the discriminator as well.
https://stackoverflow.com/questions/55744941/
Model learns with SGD but not Adam
I was going through a basic PyTorch MNIST example here and noticed that when I changed the optimizer from SGD to Adam the model did not converge. Specifically, I changed line 106 from optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum) to optimizer = optim.Adam(model.parameters(), lr=args....
Adam is famous for working out of the box with its default paremeters, which, in almost all frameworks, include a learning rate of 0.001 (see the default values in Keras, PyTorch, and Tensorflow), which is indeed the value suggested in the Adam paper. So, I would suggest changing to optimizer = optim.Adam(model.para...
https://stackoverflow.com/questions/55770783/
What is the meaning of "x:" and of the following line?
What is the meaning of x: and of the following line? image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) Can somebody explain the syntax of this line? It is from PyTorch tutorial: https://pytorch.org/tutorials/beginner/transfer_learning...
image_datasets = {x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']} x comes from the for you have below. for x in ['train', 'val'], so for each value in ['train', 'val'], you are creating a dict in which that x...
https://stackoverflow.com/questions/55792839/
error: unrecognized arguments: - pytorch code in colab
I tried to run my code on google colab. but I get this message (error: unrecognized arguments)when I'm trying to call this function : def parse_opts(): parser = argparse.ArgumentParser() parser.add_argument( '--root_path', default='/root/data/ActivityNet', type=str, help='Root directory path of d...
The problem only appears in Jupyter notebook/lab/colab. Change args = parser.parse_args() to args = parser.parse_args(args=[]) and it should fix it.
https://stackoverflow.com/questions/55793112/
RuntimeError: CUDA out of memory. Problem when re-loading the model in a loop
I am running into the classic: CUDA out of memory. What I want to do: I want to load the same model using a different matrix of embeddings every time. I have to do that 300 times, one for each dimension of the word embeddings. I am not training the model, that is why I am using model.eval(), I thought that would be ...
It looks like acc_dim accumulates the grad history - see https://pytorch.org/docs/stable/notes/faq.html Because you're only do inference, with torch.no_grad(): should be used. This will completely sidestep the possible issue with accumulating grad history. model.eval() doesn't prevent grad bookkeeping from happening,...
https://stackoverflow.com/questions/55800592/
Check if the expected object is of backend CUDA or CPU?
I am trying to run a code on both CPU and CUDA. The problem arise when I create objects, as I need to know what's expected. I need to determine if the computer is expecting a CUDA or CPU tensor, before it is created. Code: def initilize(self, input): self.x = torch.nn.Parameter(torch.zeros((1,M)) d...
You can just use self.x = torch.nn.Parameter(torch.zeros((1,M)).to(device)), no need for if (expecting_cuda == True): because to(device) will also work for cpu.
https://stackoverflow.com/questions/55806248/
Error in loading state_dict for customed model
I had problems when loading the weights of model. Here's some parts of the model class InceptionV4(nn.Module): def __init__(self, num_classes=1001): super(InceptionV4, self).__init__() # Special attributs self.input_space = None self.input_size = (299, 299, 3) self.mean = None ...
I faced this problem several times. The error indicates that your model state_dict has different names from the pre-trained weights that you load. I don't see the pretrained model for Inception_v4 in torchvision model zoo, so it would be a little difficult to tell exactly where your InceptionV4 class has a problem wit...
https://stackoverflow.com/questions/55825961/
Different `grad_fn` for similar looking operations in Pytorch (1.0)
I am working on an attention model, and before running the final model, I was going through the tensor shapes which flow through the code. I have an operation where I need to reshape the tensor. The tensor is of the shape torch.Size([[30, 8, 9, 64]]) where 30 is the batch_size, 8 is the number of attention head (this ...
Aren't these two the same operations? No. While they produce effectively the same tensor, the operations are not the same, and they are not guaranteed to have the same storage. TensorShape.cpp: // _unsafe_view() differs from view() in that the returned tensor isn't treated // as a view for the purposes of automatic d...
https://stackoverflow.com/questions/55835557/
Pytorch LSTM text-generator repeats same words
UPDATE: It was a mistake in the logic generating new characters. See answer below. ORIGINAL QUESTION: I built an LSTM for character-level text generation with Pytorch. The model trains well (loss decreases reasonably etc.) but the trained model ends up outputting the last handful of words of the input repeated over an...
ANSWER: I had made a stupid mistake when producing the characters with the trained model: I got confused with the batch size and assumed that at each step the network would predict an entire batch of new characters when in fact it only predicts a single one… That's why it simply repeated the end of the input. Yikes! A...
https://stackoverflow.com/questions/55861392/
Pytorch is installed, but while importing getting error
I have installed Anaconda on windows 8, after that done with the PyTorch. But while importing torch getting error. import torch AttributeError Traceback (most recent call last) &lt;ipython-input-4-eb42ca6e4af3&gt; in &lt;module&gt; ----&gt; 1 import torch I:\ProgramData\Anacond...
Try out the below in your anaconda prompt conda create -n &lt;env_name&gt;python=3.6 conda activate &lt;env_name&gt; conda install pytorch-cpu torchvision-cpu -c pytorch If you are using a GPU conda install pytorch torchvision cudatoolkit=9.0 -c pytorch Please refer https://pytorch.org/
https://stackoverflow.com/questions/55880253/
How get a Python pathlib Path from an Azure blob datastore?
I am trying to do some custom manipulation of a torch.utils.data.DataLoader in AzureML but cannot get it to instantiate directly from my azureml.core.Datastore : ws = Workspace( # ... etc ... ) ds = Datastore.get(ws, datastore_name='my_ds') am = ds.as_mount() # HOW DO I GET base_path, data_file from am? dataloader =...
You can perhaps try using the DataPath class. It exposes attributes such as path_on_datastore which might be the path you're looking for. To construct this class from your DataReference object i.e. variable am; you can use create_from_data_reference() method. Example: ds = Datastore.get(ws, datastore_name='my_ds') ...
https://stackoverflow.com/questions/55884641/
Unexpected and missing keys in state_dict when converting pytorch to onnx
When I convert a '.pth' model from PyTorch to ONNX, an error like Unexpected keys and missing keys occur. This is my model: 1 import torch 2 import torch.onnx 3 from mmcv import runner 4 import torch.`enter code here`nn as nn 5 from mobilenet import MobileNet 6 # A model class instance (class ...
In line 19, try using model=runner.load_state_dict(..., strict=False). Using the parameter strict=False tells the load_state_dict function that there might be missing keys in the checkpoint, which usually come from the BatchNorm layer as I see in this case.
https://stackoverflow.com/questions/55898666/
How to convert tensor to image array?
I would like to convert a tensor to image array and use tensor.data() method. But it doesn't work. #include &lt;torch/script.h&gt; // One-stop header. #include &lt;iostream&gt; #include &lt;memory&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include "itkImage.h" #include "itkImageF...
I have found the solution. When I convert the y to kCPU, it works. Because it in CUDA before.
https://stackoverflow.com/questions/55899140/
Why am I getting different results after saving and loading model weights in pytorch?
I have written a model, the architecture is follows: CNNLSTM( (cnn): CNNText( ...
After loading the model, you need to write model.eval(). state_dict = torch.load(MODEL_PATH) model.load_state_dict(state_dict) model.eval() Reference : Pytorch Documentation This is what it says: When saving a model for inference, it is only necessary to save the trained model’s learned parameters. Saving the model’s...
https://stackoverflow.com/questions/55900754/
what is the difference between unsqueez_ in pytorch and epxand_dim in keras and what will be the shape of output after using it?
I am a beginner in keras and I have a pytorch code that I need to change it to keras, but I could not understand some part of it. specially I have problems in the size of the output shape. the shape of image is (:, 3,32,32) and the first dimension of image is the size of the batch. now, my question is: what this line ...
It seems like you are Keras-user or Tensorflow-user and trying to learn Pytorch. You should go to the website of Pytorch document to understand more about each operation. unsqueeze is to expand the dim by 1 of the tensor. The underscore in unsqueeze_() means this is in-place function. view() can be understood as ....
https://stackoverflow.com/questions/55910278/
PyTorch Design: Why does torch.distributions.multivariate_normal have methods outside of its class?
I'm trying to understand the design of pytorch a little bit better. I was trying to draw samples from a multivariate normal, and found torch.distributions.multivariate_normal, which to my surprise is a module with many protected functions defined outside of its MultivariateNormal() class. I was confused as to why this...
You can call MultivariateNormal directly: import torch gaussian = torch.distributions.MultivariateNormal(torch.ones(2),torch.eye(2)) But the class MultivariateNormal is implemented in the file "torch/distributions/multivariate_normal.py", so both calls are correct
https://stackoverflow.com/questions/55927149/
Why does loss continue decreasing but performance keep unchanged?
I am using bert-lstm-crf model, with bert model from https://github.com/huggingface/pytorch-pretrained-BERT/ and lstm crf models are written by myself. After training bert-lstm-crf model for 25 epochs, the performance on training set, dev set and test set keep unchanged but the loss continue decreasing. Where should I...
I have modified this PyTorch implementation of BERT-NER model and added CRF. I have the following class which works fine in my case. class BertWithCRF(BertPreTrainedModel): def __init__(self, config, labels, dropout=0.1): super(BertWithCRF, self).__init__(config) self.tagset_size = len(labels) ...
https://stackoverflow.com/questions/55929458/
Why doesn't the Discriminator's and Generators' loss change?
I'm trying to implement a Generative Adversarial Network (GAN) for the MNIST-Dataset. I use Pytorch for this. My problem is, that after one epoch the Discriminator's and the Generator's loss doesn't change. I already tried two other methods to build the network, but they cause all the same problem :/ import os import...
I found out the solution of the problem. BCEWithLogitsLoss() and Sigmoid() doesn't work together, because BCEWithLogitsLoss() includes the Sigmoid activation. So you can use BCEWithLogitsLoss() without Sigmoid() or you can use Sigmoid() and BCELoss()
https://stackoverflow.com/questions/55936611/
pytorch parallelize for loop of Cross Validation
I have a cuda9-docker with tensorflow and pytorch installed, I am doing cross validation on an image dataset. Currently I am using a for loop to do the cross validation. Something like for data_train, data_test in sklearn.kfold(5, all_data): train(data_train) test(data_test) But the for loop takes too long, will...
You use try horovod with PyTorch. ResNet50 example is here: https://github.com/horovod/horovod/blob/master/examples/pytorch/pytorch_imagenet_resnet50.py horovod-related changes should be small and isolated.
https://stackoverflow.com/questions/55938914/
FastAI v1 PyTorch Custom Model
i have been trying to use fastai with a custom torch model. My code is as follow: X_train = np.load(dirpath + 'X_train.npy') X_valid = np.load(dirpath + 'X_valid.npy') Y_train = np.load(dirpath + 'Y_train.npy') Y_valid = np.load(dirpath + 'Y_valid.npy') X_train's shape is : (240, 122, 96), and Y_train's shape is : ...
Although I didn't understand the error message you posted, I see one problem in your code. out = out[:,-1,:] # batch_size x 480 out = self.batch_norm_1(self.activation_1(out)) But you declared batch_norm_1 as: self.batch_norm_1 = nn.BatchNorm1d(122) Which should be: self.batch_norm_1 = nn.BatchNorm1d(480)
https://stackoverflow.com/questions/55943259/
Training and testing CNN with pytorch. With and without model.eval()
I have two questions:- I am trying to train a convolution neural network initialized with some pre trained weights (Netwrok contains batch normalization layers as well) (taking reference from here). Before training I want to calculate a validation error using loss_fn = torch.nn.MSELoss().cuda(). And in the reference,...
What could be reason behind it as I have read on many posts that model.eval should be used before testing the model and model.train() before training it. Note: testing the model is called inference. As explained in the official documentation: Remember that you must call model.eval() to set dropout and batch n...
https://stackoverflow.com/questions/55948551/
Transfer learning with OpenNMT
I'm training a transformer model with OpenNMT-py on MIDI music files, but results are poor because I only have access to a small dataset pertaining to the style I want to study. To help the model learn something useful, I would like to use a much larger dataset of other styles of music for a pre-training and then fine-...
Please be more specific about your questions and show some code which will help you to get a productive response from the SO community. If I were in your place and wanted to freeze a neural network component, I would simply do: for name, param in self.encoder.named_parameters(): param.requires_grad = False Her...
https://stackoverflow.com/questions/55954232/
GAN, discriminator output only 0 or 1
I'm trying to train SRGAN. (Super Resolution GAN) However, the discriminator's output converge to 0 or 1 whatever the input is. Discriminator's loss function is only D_loss = 0.5*(D_net(fake) + 1 - D_net(real)) D_net(fake) and D_net(real) both becomes 0 or 1. (sigmoid) How can I fix it? for epoch_idx in range...
I am not sure if I understand your problem correctly. You meant that the sigmoid output from the discriminator is either 0 or 1? In your loss function: D_loss = 0.5 * (fake_D_out + 1 - real_D_out), you are directly optimizing on the sigmoid output and looks like the discriminator overfits to your data that it can acc...
https://stackoverflow.com/questions/55957396/
Is there a difference between "torch.nn.CTCLoss" supported by PYTORCH and "CTCLoss" supported by torch_baidu_ctc?
Is there a difference between "torch.nn.CTCLoss" supported by PYTORCH and "CTCLoss" supported by torch_baidu_ctc? i think, I didn't notice any difference when I compared the tutorial code. Does anyone know the true? Tutorial code is located below. import torch from torch_baidu_ctc import ctc_loss, CTCLoss # Activa...
CTC loss only part of PyTorch since the 1.0 version and it is a better way to go because it is natively part of PyTorch. If you are using PyTorch 1.0 or newer, use torch.nn.CTCLoss. warp-ctc does not seem to be maintained, the last commits changing the core code are from 2017. Later, they only fixed bindings for (an a...
https://stackoverflow.com/questions/55962112/
Best Way to Overcome Early Convergence for Machine Learning Model
I have a machine learning model built that tries to predict weather data, and in this case I am doing a prediction on whether or not it will rain tomorrow (a binary prediction of Yes/No). In the dataset there is about 50 input variables, and I have 65,000 entries in the dataset. I am currently running a RNN with a si...
Not sure why exactly you are using only one hidden layer and what is the shape of your history data but here are the things you can try: Try more than one hidden layer Experiment with LSTM and GRU layer and combination of these layers together with RNN. Shape of your data i.e. the history you look at to predict the w...
https://stackoverflow.com/questions/55973335/
How to fine tune BERT on its own tasks?
I wanted to pre-train BERT with the data from my own language since multilingual (which includes my language) model of BERT is not successful. Since whole pre-training costs a lot, I decided to fine tune it on its own 2 tasks: masked language model and next sentence prediction. There are previous implementation on diff...
A wonderful resource for BERT is: https://github.com/huggingface/pytorch-pretrained-BERT. This repository contains op-for-op PyTorch reimplementations, pre-trained models and fine-tuning examples for Google's BERT model. You can find the language model fine-tuning examples in the following link. The three example scri...
https://stackoverflow.com/questions/55973414/
How to normalize set of images between (-1,1)
i have a dataset on images and i would like to normalize them betwwen (-1,1) before feeding them to NN how can i do that ? x=sample #Normalized Data normalized = (x-min(x))/(max(x)-min(x)) # Histogram of example data and normalized data par(mfrow=c(1,2)) hist(x, breaks=10, xlab="Data", col="light...
Assuming your image img_array is an np.array : normalized_input = (img_array - np.amin(img_array)) / (np.amax(img_array) - np.amin(img_array)) Will normalize your data between 0 and 1. Then, 2*normalized_input-1 will shift it between -1 and 1 If you want to normalize multiple images, you can make it a function : ...
https://stackoverflow.com/questions/55980579/
Why TensorBoard summary is not updating?
I use tensorboard with pytorch1.1 to log loss values. I use writer.add_scalar("loss", loss.item(), global_step) in every for- loop body. However, the plotting graph does not update while the training is processing. Every time I want to see the latest loss, I have to restart the tensorboard server. The code is here ...
Also for those who have multiple event log files for a single run, you need to start your tensorboard with --reload_multifile True
https://stackoverflow.com/questions/55980785/
why can't I reimplement my tensorflow model with pytorch?
I am developing a model in tensorflow and find that it is good on my specific evaluation method. But when I transfer to pytorch, I can't achieve the same results. I have checked the model architecture, the weight init method, the lr schedule, the weight decay, momentum and epsilon used in BN layer, the optimizer, and t...
I did a similar conversion recently. First you need to make sure that the forward path produces the same results: disable all randomness, initialize with the same values, give it a very small input and compare. If there is a discrepancy, disable parts of the network and compare enabling layers one by one. When the fo...
https://stackoverflow.com/questions/55980918/
RuntimeError: Assertion `cur_target >= 0 && cur_target < n_classes' failed
I get: RuntimeError: Assertion `cur_target >= 0 &amp;&amp; cur_target &lt; n_classes' failed. at /opt/conda/conda-bld/pytorch_1550796191843/work/aten/src/THNN/generic/ClassNLLCriterion.c:93 When running this code: criterion = nn.CrossEntropyLoss() #Define the optimizer optimizer=optim.SGD(net.pa...
The exception says that one of your labels is out of bounds. Maybe they start from 1 instead of 0? Try printing them out.
https://stackoverflow.com/questions/55981101/
How to correctly access elements in a 3D-Pytorch-Tensor?
I am trying to access multiple elements in a 3D-Pytorch-Tensor, but the number of elements that are returned is wrong. This is my code: import torch a = torch.FloatTensor(4,3,2) print("a = {}".format(a)) print("a[:][:][0] = {}".format(a[:][:][0])) This is the output: a = tensor([[[-4.8569e+36, 3.0760e-41], ...
Short answer, you need to use a[:, :, 0] More explanation: When you do a[:] it returns a itself. So a[:][:][0] is same as doing a[0] which will give you the elements at the 0th position of the first axis (hence the size is (3,2)). What you want are elements from the 0th position of the last axis for which you need to ...
https://stackoverflow.com/questions/55982067/
conv2d function in pytorch
I'm trying to use the function torch.conv2d from Pytorch but can't get a result I understand... Here is a simple example where the kernel (filt) is the same size as the input (im) to explain what I'm looking for. import pytorch filt = torch.rand(3, 3) im = torch.rand(3, 3) I want to compute a simple convolution wi...
The tensor shape of your input and the filter should be: (batch, dim_ch, width, height) and NOT: (width, height, 1, 1) e.g. import torch import torch.nn.functional as F x = torch.randn(1,1,4,4); y = torch.randn(1,1,4,4); z = F.conv2d(x,y); Output shape of z: torch.Size([1,1,1,1])
https://stackoverflow.com/questions/55994955/
Inplace arithmetic operation versus normal arithmetic operation in PyTorch Tensors
I am trying to build Linear regression using Pytorch framework and while implementing Gradient Descent, I observed two different outputs based on how I use arithmetic operation in Python code. Below is the code: #X and Y are input and target labels respectively X = torch.randn(100,1)*10 Y = X + 3*torch.randn(100,1)...
I think the reason is simple. When you do: w = w - lr * w.grad b = b - lr * b.grad The w and b in the left-hand side are two new tensors and their .grad is None. However, when you do inplace operation, you do not create any new tensor, you just update the value of the concerned tensor. So, in this scenario, inplac...
https://stackoverflow.com/questions/56019560/
Vectorize to Apply Function to 3d Array
I am trying to apply a function to 3d torch tensor while the function is applied to 2d tensor which is read through the axis 1 of the 3d torch tensor. For example, I have a torch tensor of the shape (51, 128, 20100) (a variable with name autoencode_logprob) and the function(rawid2sentence) runs on the input of the sha...
Since I do not know what rawids2sentence or encode function does, I can help you with to do the max operation. In the following statement, autoencode_logprobs[:, i].max(1)[1] You identify the index of the maximum values along dim=1 for each 51 x 20100 tensor. So, the output is a vector of size 51. You can perform ...
https://stackoverflow.com/questions/56027238/
'An attempt has been made to start' in lr_find with fast.ai
I am running this small piece of code to identify learning rate: import cv2 from fastai.vision import * from fastai.callbacks.hooks import * path = untar_data(URLs.CAMVID) path_lbl = path/'labels' path_img = path/'images' fnames = get_image_files(path_img) lbl_names = get_image_files(path_lbl) img_f = fnames[0] img = ...
Oh, the solution is to wrap code in a method and invoke it: import cv2 from fastai.vision import * from fastai.callbacks.hooks import * def main(): path = untar_data(URLs.CAMVID) path_lbl = path/'labels' path_img = path/'images' fnames = get_image_files(path_img) lbl_names = get_image_files(path_l...
https://stackoverflow.com/questions/56028489/
Validation loss not moving with MLP in Regression
Given input features as such, just raw numbers: tensor([0.2153, 0.2190, 0.0685, 0.2127, 0.2145, 0.1260, 0.1480, 0.1483, 0.1489, 0.1400, 0.1906, 0.1876, 0.1900, 0.1925, 0.0149, 0.1857, 0.1871, 0.2715, 0.1887, 0.1804, 0.1656, 0.1665, 0.1137, 0.1668, 0.1168, 0.0278, 0.1170, 0.1189, 0.1163, 0.2337,...
From the code you provided, it is tough to say why the validation loss is constant but I see several problems in your code. Why do you validate for each training mini-batch? Instead, you should validate your model after you do the training for one complete epoch (iterating over your full dataset once). So, the skelet...
https://stackoverflow.com/questions/56069685/
How to convert keras LSTM to pytorch LSTM?
I have a very simple LSTM example written in Keras that I am trying to port to pytorch. But it does not seem to be able to learn at all. I am an absolute beginning so any advice is appreciated. KERAS: X_train_lmse has shape (1691, 1, 1), I am essentially running X(t) with X(t-1) as single feature lstm_model = Seque...
You miss the relu activation function in your PyTorch model (See Relu layer in PyTorch). Also, you seem to be using a customized kernel_initalizer for the weights. You can pass your initialization weights in the model call: ... y_pred = lstm_model(X_train_tensor, (hn, cn)) ...
https://stackoverflow.com/questions/56084625/
Windows installing pytorch 0.3
I need to install pytorch==0.3 (I'm using conda), but when I run the command line, conda says that the needed packages are not available. Is there a way I can install it (possibly without using ubuntu)?
peterjc123 released the version for windows here: https://anaconda.org/peterjc123/pytorch
https://stackoverflow.com/questions/56087752/
Input Tensors not being moved to GPU in pytorch
When running my code, I get the error: Input and parameter tensors are not at the same device, found input tensor at cpu and parameter tensor at cuda:0 even though I'm using .cuda() on my inputs. Google Colab link Code: use_cuda = True if use_cuda and torch.cuda.is_available(): model.cuda() def test(): model.e...
The cuda()method returns the tensor on the right gpu so you need to assign it back to your input variable: lstmInput, label = lstimInput.cuda(), label.cuda()
https://stackoverflow.com/questions/56105521/
How to calculate gradients on a tensor in PyTorch?
I want to calculate the gradient of a tensor and however, it gives error as RunTimeerror: grad can be implicitly created only for scalar outputs and here is what I am trying to code: x = torch.full((2,3), 4,requires_grad=True) y = (2*x**2+3) y.backward() And at this point, it throws an error.
Since there is no summing up/reducing the loss-value , like .sum() Hence the issue could be fixed by: y.backward(torch.ones_like(x)) which performs a Jacobian-vector product with a tensor of all ones and get the gradient.
https://stackoverflow.com/questions/56111340/
What wrong when i load state_dict of resnet50.pth with pytorch
i load the resnet50.pth and KeyError of 'state_dict' pytorch version is 0.4.1 i tried delete/add torch.nn.parallel but it didn't help and resnet50.pth loaded from pytorch API related code model = ResNet(len(CLASSES), pretrained=args.use_imagenet_weights) if cuda_is_available: model = nn.DataParallel(model, dev...
Did you perhaps mean the following? state_dict = torch.load(args.model['state_dict']) From your edit, it seems that your model is the model itself. There is no state_dict. So just use state_dict = torch.load(args.model)
https://stackoverflow.com/questions/56115736/
Adding parameters to a pretrained model
In Pytorch, we load the pretrained model as follows: net.load_state_dict(torch.load(path)['model_state_dict']) Then the network structure and the loaded model have to be exactly the same. However, is it possible to load the weights but then modify the network/add an extra parameter? Note: If we add an extra paramet...
Let's create a model and save its' state. class Model1(nn.Module): def __init__(self): super(Model1, self).__init__() self.encoder = nn.LSTM(100, 50) def forward(self): pass model1 = Model1() torch.save(model1.state_dict(), 'filename.pt') # saving model Then create a second model ...
https://stackoverflow.com/questions/56116892/
How to cover a label list under the multi-label classification context into one-hot encoding with pytorch?
I have a list of one batch data with multi-label for every sample. So how to covert it into torch.Tensor in one-hot encoding? For example, with batch_size=5 and class_num=6, label =[ [1,2,3], [4,6], [1], [1,4,5], [4] ] how to make it into one-hot encoding in pytorch? label_tensor=tensor([ [1,1,1,0,0,0], [0,0,0,1,0,...
If the batch size can be derived from len(labels): def to_onehot(labels, n_categories, dtype=torch.float32): batch_size = len(labels) one_hot_labels = torch.zeros(size=(batch_size, n_categories), dtype=dtype) for i, label in enumerate(labels): # Subtract 1 from each LongTensor because your ...
https://stackoverflow.com/questions/56123419/
Saving Pytorch model.state_dict() to s3
I am trying to save a trained Pytorch model to S3. However, the torch.save(model.state_dict(), file_name) seems to support only local files. How can the state dict be saved to an S3 file? I'm using Torch 0.4.0
As discussed by Soumith Chintala, Pytorch doesn't have custom APIs to do this job. However you can use boto3 or Petastorm library to solve the problem. Here's a concrete example to write to an S3 object directly: import boto3 # Convert your existing model to JSON saved_model = model.to_json() # Write JSON object to...
https://stackoverflow.com/questions/56144895/
Strange behavior of Inception_v3
I am trying to create a generative network based on the pre-trained Inception_v3. 1) I fix all the weights in the model 2) create a Variable whose size is (2, 3, 299, 299) 3) create targets of size (2, 1000) that I want my final layer activations to become as close as possible to by optimizing the Variable. (I d...
Thanks to @iacolippo the issue is solved. Turns out the problem was due to Pytorch 1.0.0. No problem with Pytorch 0.4.1. though.
https://stackoverflow.com/questions/56146262/
How to use torch to speed up some common computations?
I am trying make some common computations, like matrix multiplication, but without gradient computation. An example of my computation is like import numpy as np from scipy.special import logsumexp var = 1e-8 a = np.random.randint(0,10,(128,20)) result = np.logsumexp(a, axis=1) / 2. + np.log(np.pi * var) I want to ...
You could use torch only to do the computations. import torch # optimization by passing device argument, tensor is created on gpu and hence move operation is saved # convert to float to use with logsumexp a = torch.randint(0,10, (128,20), device="cuda").float() result = torch.logsumexp(a, dim=1)/ 2. ...
https://stackoverflow.com/questions/56166455/
How to convert some tensorflow code into pytorch version
I recently started using pytorch. I've been using tensorflow framework before. I have a piece of code that I implemented with tensorflow, which I now want to convert to the pytorch version. I'm new to pytorch and I'm not familiar with its functions and the transformation process is not smooth, so I'd like to consult. ...
Here is my Implementation (I am taking an example of logits of dimension [3,5]): Tensorflow Version: import tensorflow as tf def kl_loss_compute(logits1, logits2): """ KL loss """ pred1 = tf.nn.softmax(logits1) print(pred1.eval()) pred2 = tf.nn.softmax(logits2) print(pred2.eval()) loss = t...
https://stackoverflow.com/questions/56168482/
How to use multiprocessing in PyTorch?
I'm trying to use PyTorch with complex loss function. In order to accelerate the code, I hope that I can use the PyTorch multiprocessing package. The first trial, I put 10x1 features into the NN and get 10x4 output. After that, I want to pass 10x4 parameters into a function to do some calculation. (The calculation wi...
First of all, Torch Variable API is deprecated since a very long time, just don't use it. Next, torch.from_numpy( np.asarray(list(range( 0,10))).reshape(10,1) ).float() is wrong at many levels: np.asarray of list is useless since a copy will be performed anyway, and np.array takes list as input by design. Then, np.aran...
https://stackoverflow.com/questions/56174874/
DataParallel multi-gpu RuntimeError: chunk expects at least a 1-dimensional tensor
I am trying to run my model on multiple gpus using DataParallel by setting model = nn.DataParallel(model).cuda(), but everytime getting this error - RuntimeError: chunk expects at least a 1-dimensional tensor (chunk at /pytorch/aten/src/ATen/native/TensorShape.cpp:184). My code is correct. Does anyone know wha...
To identify the problem, you should check the shape of your input data for each mini-batch. The documentation says, nn.DataParallel splits the input tensor in dim0 and sends each chunk to the specified GPUs. From the error message, it seems you are trying to pass a 0-dimensional tensor. One possible reason can be if y...
https://stackoverflow.com/questions/56177305/
How to calculate correct batch size for LSTM?
I have a daily time series data like below. CashIn CashOut Date 2016-01-01 0.0 6500.0 2016-01-02 0.0 23110.0 2016-01-03 0.0 7070.0 2016-01-04 0.0 18520.0 2016-01-05 20840.0 22200.0 . . . 2019-03-25 59880.0 25500.0 2019-03-26 49270.0 17860.0 2019-03-27 45160.0 48600.0 20...
I think that you'll always end up with a number that is not working. Because it's not the best practice. I suggest that you use the DataLoader which will easily load batches for you (and here's how you can have a custom dataset fed to the dataloder). By giving the batch_size to the Dataloader it will split your dataset...
https://stackoverflow.com/questions/56201842/
Can’t convert np.ndarray of type numpy.bool_
I am wondering why I am getting this error when I used : Y_train_class = torch.tensor(Y_train_class.values) TypeError: can't convert np.ndarray of type numpy.bool_. The only supported types are: double, float, float16, int64, int32, and uint8. I have tried to convert my data to float but seems failed X_train ...
I got this type of error when my Y_train had a string value instead of integers. After replacing strings with integers my error got resolved.
https://stackoverflow.com/questions/56203536/
Getting the last layer from a pretrained pytorch for transfer learning?
This is what I did: list(tmp.state_dict().keys())[-1].split('.')[0] What is the proper way? My goal is to replace the last layer for the purpose of transfer learning.
You can simple follow these steps to get the last layer from a pretrained pytorch model: We can get the layers by using model.children(). Convert this into a list by using a list() command on it. Remove the last layer by indexing the list. Finally, use the PyTorch function nn.Sequential() to stack this modified li...
https://stackoverflow.com/questions/56212588/
how to upload and read a zip file containing training and testing images data from google colab from my pc
I am new to google colab. I am implementing a pretrained vgg16 and resnet50 model using pytorch, but I am unable to load my file and read it as it returns an error of no directory found I have uploaded the data through file also I have used to upload it using from google.colab import files uploaded = files.upload()...
You are probably trying to access the wrong path. In my notebook, the file was uploaded to the working directory. Use google.colab.files to upload the zip. from google.colab import files files.upload() Upload your file. Google Colab will display where it was saved: Saving dummy.zip to dummy.zip Then just run !...
https://stackoverflow.com/questions/56218134/
RuntimeError: expected type torch.cuda.FloatTensor but got torch.FloatTensor
I keep getting the error message below. I cannot seem to pinpoint to the tensor mentioned. Below you'll find the trainer.py and main.py modules. The model I am developing is GAN on CelebA dataset. I am running the code on a remote server so have spent a handful amount of time debugging my model. This is the full error...
You are getting that error because one of out_cls, label_org is not on the GPU. Where does your code enact the parser.add_argument('--cuda', action='store_true', help='enables cuda') option? Perhaps something like: trainer = Trainer(opt) if opt.cuda: trainer = trainer.cuda()
https://stackoverflow.com/questions/56240001/
AttributeError: module 'torch' has no attribute '_six'. Bert model in Pytorch
I tried to load pre-trained model by using BertModel class in pytorch. I have _six.py under torch, but it still shows module 'torch' has no attribute '_six' import torch from pytorch_pretrained_bert import BertTokenizer, BertModel, BertForMaskedLM # Load pre-trained model (weights) model = BertModel.from_pretrained('...
In jupyter notebook simply restarting kernel works fine
https://stackoverflow.com/questions/56241856/
How can I force torch.jit.trace to compule my module by ignoring hooks?
I have a module containing hook, and I would like to compile it with jit's trace: compiled_model = torch.jit.trace(model, torch.rand(1, 3, 256, 256)) But I get the error: ValueError: Modules that have hooks assigned can't be compiled How can I force trace to ignore the hooks ?
If you want to bypass trace's check, you can recursively remove all the hooks from your model. This can be done by iterating over the children: from collections import OrderedDict def remove_hooks(model): model._backward_hooks = OrderedDict() model._forward_hooks = OrderedDict() model._forward_pre_hooks =...
https://stackoverflow.com/questions/56242857/
Expected target size (50, 88), got torch.Size([50, 288, 88])
I am trying to train my neuronal network. Train in the model is correct, but I can't calculate loss. The output and the target have the same dimension. I had tried to use torch.stack, but I can't because the size of the each input is (252, x) where x is the same in the 252 elements, but is different for the others inp...
I think you are using CrossEntropyLoss incorrectly. See the documentation here. In particular, if the input is of shape [NxCxd] then target should be of shape [Nxd], and value in target are integer between 0 and C-1 i.e you can just provide the class labels and it is not required to one-hot encode the target variable....
https://stackoverflow.com/questions/56243672/
Reshape and pad a tensor given a list of lengths
I have given a 2d tensor in of shape a x b like the following (where a = 9 and each of A1, A2, ..., C2 represents a b-dimensional vector): Furthermore, I have an array of lengths, where sum(lengths) = a and each entry is a positive integer: Then I would like to obtain a 3d output tensor out, where the first leng...
Here is my implementation using torch.nn.utils.rnn.pad_sequence(): in_tensor = torch.rand((9, 3)) print(in_tensor) print(36*'=') lengths = torch.tensor([3, 4, 2]) cum_len = 0 y = [] for idx, val in enumerate(lengths): y.append(in_tensor[cum_len : cum_len+val]) cum_len += val print(torch.nn.utils.rnn.pad_sequen...
https://stackoverflow.com/questions/56258174/
How to understand this on pytorch website?
I notice this on pytorch official website: https://pytorch.org/docs/stable/nn.html If the following conditions are satisfied: 1) cudnn is enabled, 2) input data is on the GPU, 3) input data has dtype torch.float16, 4) V100 GPU is used, and 5) input data is not in PackedSequence format. Then, persistent algor...
This refers a to very low level performance optimization of GPU cache usage, which is explained more in-depth here (note: this is not a PyTorch material, but I believe it does a good enough job at explaining). In other words, if all the bullets are satisfied, PyTorch will default to a different algorithm under the hood...
https://stackoverflow.com/questions/56285876/
Pytorch: no CUDA-capable device is detected on Linux
When trying to run some Pytorch code I get this error: THCudaCheck FAIL file=/pytorch/aten/src/THC/THCGeneral.cpp line=74 error=38 : no CUDA-capable device is detected Traceback (most recent call last): File "demo.py", line 173, in test pca = torch.FloatTensor( np.load('../basics/U_lrw1.npy')[:,:6]).cuda() RuntimeErro...
I didn't get the main reason for your problem. But I noticed one thing, GPU-Util 100%, while there are no processes running behind. You can try out in the following directions. sudo nvidia-smi -pm 1 which enables in persistence mode. This might solve your problem. The combination of ECC with non persistence mode ...
https://stackoverflow.com/questions/56311034/
How to initialize the weights of different layers of nn.Sequential block in different styles in pytorch?
Let's suppose I have a nn.Sequential block, it has 2 linear layers. I want to initialize the weights of first layer by uniform distribution but want to initialize the weights of second layer as constant 2.0. net = nn.Sequential() net.add_module('Linear_1', nn.Linear(2, 5, bias = False)) net.add_module('Linear_2', nn.L...
Here is one way of doing so: import torch import torch.nn as nn net = nn.Sequential() ll1 = nn.Linear(2, 5, bias = False) torch.nn.init.uniform_(ll1.weight, a=0, b=1) # a: lower_bound, b: upper_bound net.add_module('Linear_1', ll1) print(ll1.weight) ll2 = nn.Linear(5, 5, bias = False) torch.nn.init.constant_(ll2.w...
https://stackoverflow.com/questions/56312886/