instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
Extracting the top-k value-indices from a 1-D Tensor | Given a 1-D tensor in Torch (torch.Tensor), containing values which can be compared (say floating point), how can we extract the indices of the top-k values in that tensor?
Apart from the brute-force method, I am looking for some API call, that Torch/lua provides, which can perform this task efficiently.
| As of pull request #496 Torch now includes a built-in API named torch.topk. Example:
> t = torch.Tensor{9, 1, 8, 2, 7, 3, 6, 4, 5}
-- obtain the 3 smallest elements
> res = t:topk(3)
> print(res)
1
2
3
[torch.DoubleTensor of size 3]
-- you can also get the indices in addition
> res, ind = t:topk(3)
&g... | https://stackoverflow.com/questions/34750268/ |
How to Display Custom Images in Tensorboard (e.g. Matplotlib Plots)? | The Image Dashboard section of the Tensorboard ReadMe says:
Since the image dashboard supports arbitrary pngs, you can use this to embed custom visualizations (e.g. matplotlib scatterplots) into TensorBoard.
I see how a pyplot image could be written to file, read back in as a tensor, and then used with tf.image_s... | It is quite easy to do if you have the image in a memory buffer. Below, I show an example, where a pyplot is saved to a buffer and then converted to a TF image representation which is then sent to an image summary.
import io
import matplotlib.pyplot as plt
import tensorflow as tf
def gen_plot():
"""Create a pypl... | https://stackoverflow.com/questions/38543850/ |
Python wheels: cp27mu not supported | I'm trying to install pytorch (http://pytorch.org/) on Linux, and according to my machine configuration, the command I should run is:
pip install https://s3.amazonaws.com/pytorch/whl/torch-0.1.6.post17-cp27-cp27mu-linux_x86_64.whl
On one machine (Linux distribution Slackware 14.1) the installation fails with error: t... | This is exactly that.
Recompile python under slack with --enable-unicode=ucs4 and you can then install the whl.
| https://stackoverflow.com/questions/41767005/ |
Loading Torch7 trained models (.t7) in PyTorch | I am using Torch7 library for implementing neural networks. Mostly, I rely on pre-trained models. In Lua I use torch.load function to load a model saved as torch .t7 file. I am curious about switching to PyTorch( http://pytorch.org) and I read the documents. I couldn't find any information regarding the mechanisms to ... | As of PyTorch 1.0 torch.utils.serialization is completely removed. Hence no one can import models from Lua Torch into PyTorch anymore. Instead, I would suggest installing PyTorch 0.4.1 through pip in a conda environment (so that you can remove it after this) and use this repo to convert your Lua Torch model to PyTorch ... | https://stackoverflow.com/questions/41861354/ |
PyTorch: How to use DataLoaders for custom Datasets | How to make use of the torch.utils.data.Dataset and torch.utils.data.DataLoader on your own data (not just the torchvision.datasets)?
Is there a way to use the inbuilt DataLoaders which they use on TorchVisionDatasets to be used on any dataset?
| Yes, that is possible. Just create the objects by yourself, e.g.
import torch.utils.data as data_utils
train = data_utils.TensorDataset(features, targets)
train_loader = data_utils.DataLoader(train, batch_size=50, shuffle=True)
where features and targets are tensors. features has to be 2-D, i.e. a matrix where each... | https://stackoverflow.com/questions/41924453/ |
What does .view() do in PyTorch? | What does .view() do to a tensor x? What do negative values mean?
x = x.view(-1, 16 * 5 * 5)
| view() reshapes the tensor without copying memory, similar to numpy's reshape().
Given a tensor a with 16 elements:
import torch
a = torch.range(1, 16)
To reshape this tensor to make it a 4 x 4 tensor, use:
a = a.view(4, 4)
Now a will be a 4 x 4 tensor. Note that after the reshape the total number of elements need to... | https://stackoverflow.com/questions/42479902/ |
How do I print the model summary in PyTorch? | How do I print the summary of a model in PyTorch like what model.summary() does in Keras:
Model Summary:
____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
=============... | While you will not get as detailed information about the model as in Keras' model.summary, simply printing the model will give you some idea about the different layers involved and their specifications.
For instance:
from torchvision import models
model = models.vgg16()
print(model)
The output in this case would be... | https://stackoverflow.com/questions/42480111/ |
How do I save a trained model in PyTorch? | How do I save a trained model in PyTorch? I have read that:
torch.save()/torch.load() is for saving/loading a serializable object.
model.state_dict()/model.load_state_dict() is for saving/loading model state.
| Found this page on their github repo:
Recommended approach for saving a model
There are two main approaches for serializing and restoring a model.
The first (recommended) saves and loads only the model parameters:
torch.save(the_model.state_dict(), PATH)
Then later:
the_model = TheModelClass(*args, **kwargs)
the_mode... | https://stackoverflow.com/questions/42703500/ |
L1/L2 regularization in PyTorch | How do I add L1/L2 regularization in PyTorch without manually computing it?
| See the documentation. Add a weight_decay parameter to the optimizer for L2 regularization.
| https://stackoverflow.com/questions/42704283/ |
How can I install torchtext? | I have PyTorch installed in my machine but whenever I try to do the following-
from torchtext import data
from torchtext import datasets
I get the following error.
ImportError: No module named 'torchtext'
How can I install torchtext?
| The package was released with setuptools support. You can clone the repository and run python setup.py install. Unfortunately, I don't think that they have released it on pip.
| https://stackoverflow.com/questions/42711144/ |
What is the difference between view() and unsqueeze() in Torch? | Use of unsqueeze():
input = torch.Tensor(2, 4, 3) # input: 2 x 4 x 3
print(input.unsqueeze(0).size()) # prints - torch.size([1, 2, 4, 3])
Use of view():
input = torch.Tensor(2, 4, 3) # input: 2 x 4 x 3
print(input.view(1, -1, -1, -1).size()) # prints - torch.size([1, 2, 4, 3])
According to documentation, unsqueeze() ... | view() can only take a single -1 argument.
So, if you want to add a singleton dimension, you would need to provide all the dimensions as arguments. For e.g., if A is a 2x3x4 tensor, to add a singleton dimension, you would need to do A:view(2, 1, 3, 4).
However, sometimes, the dimensionality of the input is unknown when... | https://stackoverflow.com/questions/42866654/ |
Why tensor.view() is not working in pytorch? | I have the following piece of code.
embedded = self.embedding(input).view(1, 1, -1)
embedded = self.drop(embedded)
print(embedded[0].size(), hidden[0].size())
concatenated_output = torch.cat((embedded[0], hidden[0]), 1)
The last line of the code is giving me the following error.
RuntimeError: inconsistent tensor... | embedded was a 3d-tensor and hidden was a tuple of two elements (hidden states and cell states) where each element is a 3d-tensor. hidden was the output from LSTM layer. In PyTorch, LSTM returns hidden states [h] and cell states [c] as a tuple which made me confused about the error.
So, I updated the last line of the ... | https://stackoverflow.com/questions/42866752/ |
How to convert a list or numpy array to a 1d torch tensor? | I have a list (or, a numpy array) of float values. I want to create a 1d torch tensor that will contain all those values. I can create the torch tensor and run a loop to store the values.
But I want to know is there any way, I can create a torch tensor with initial values from a list or array? Also suggest me if there... | These are general operations in pytorch and available in the documentation. PyTorch allows easy interfacing with numpy. There is a method called from_numpy and the documentation is available here
import numpy as np
import torch
array = np.arange(1, 11)
tensor = torch.from_numpy(array)
| https://stackoverflow.com/questions/42894882/ |
AttributeError: module 'torch' has no attribute 'cmul' | I was trying to do element-wise multiplication of two tensors using the example provided here.
My code:
import torch
x = torch.Tensor([2, 3])
y = torch.Tensor([2, 1])
z = torch.cmul(x, y)
print(z)
It is giving me the following error.
AttributeError: module 'torch' has no attribute 'cmul'
Can anyone tell me why ... | I got the solution. Instead of using cmul, I need to use mul. The following code worked for me!
import torch
x = torch.Tensor([2, 3])
y = torch.Tensor([2, 1])
z = torch.mul(x, y)
print(z)
PS: I was using pytorch, not lua.
| https://stackoverflow.com/questions/42939708/ |
Performing Convolution (NOT cross-correlation) in pytorch | I have a network that I am trying to implement in pytorch, and I cannot seem to figure out how to implement "pure" convolution. In tensorflow it could be accomplished like this:
def conv2d_flipkernel(x, k, name=None):
return tf.nn.conv2d(x, flipkernel(k), name=name,
strides=(1, 1, ... | TLDR Use the convolution from the functional toolbox, torch.nn.fuctional.conv2d, not torch.nn.Conv2d, and flip your filter around the vertical and horizontal axis.
torch.nn.Conv2d is a convolutional layer for a network. Because weights are learned, it does not matter if it is implemented using cross-correlation, becau... | https://stackoverflow.com/questions/42970009/ |
AttributeError: cannot assign module before Module.__init__() call | I am getting the following error.
Traceback (most recent call last):
File "main.py", line 63, in <module>
question_classifier = QuestionClassifier(corpus.dictionary, embeddings_index, corpus.max_sent_length, args)
File "/net/if5/wua4nw/wasi/academic/research_with_prof_chang/projects/question_answering/du... | Looking at the pytorch source code for Module, we see in the docstring an example of deriving from Module includes:
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5)
self.conv2 = nn.Conv2d(20, 20, 5)
So you probably... | https://stackoverflow.com/questions/43080583/ |
How to count the amount of layers in a CNN? | The Pytorch implementation of ResNet-18.
has the following structure, which appears to be 54 layers, not 18.
So why is it called "18"? How many layers does it actually have?
ResNet (
(conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)
(bn1): BatchNorm2d(64, eps=1e-05, mo... | From your output, we can know that there are 20 convolution layers (one 7x7 conv, 16 3x3 conv, and plus 3 1x1 conv for downsample). Basically, if you ignore the 1x1 conv, and counting the FC (linear) layer, the number of layers are 18.
And I've also made an example on how to visualize your architecture in pytorch via g... | https://stackoverflow.com/questions/43175778/ |
IDE autocomplete for pytorch | I'm using Visual Studio Code. Recently tried out Kite. Both of which doesn't seem to have autocomplete for pytorch.
Is is possible with these tools ? If not, can someone suggest an editor that does ?
Thank you!
| Use Pycharm https://www.jetbrains.com/pycharm/
Get Community version, because it is free with debugger and autocomplete. (more than enough for student)
To get autocomplete and run/debug the code on Pycharm IDE, you have to set correct project interpreter path to your environment (or virtual environment) which you in... | https://stackoverflow.com/questions/43287476/ |
PyTorch reshape tensor dimension | I want to reshape a vector of shape (5,) into a matrix of shape (1, 5).
With numpy, I can do:
>>> import numpy as np
>>> a = np.array([1, 2, 3, 4, 5])
>>> a.shape
(5,)
>>> a = np.reshape(a, (1, 5))
>>> a.shape
(1, 5)
>>> a
array([[1, 2, 3, 4, 5]])
But how do I do t... | Use torch.unsqueeze(input, dim, out=None):
>>> import torch
>>> a = torch.Tensor([1, 2, 3, 4, 5])
>>> a
1
2
3
4
5
[torch.FloatTensor of size 5]
>>> a = a.unsqueeze(0)
>>> a
1 2 3 4 5
[torch.FloatTensor of size 1x5]
| https://stackoverflow.com/questions/43328632/ |
Pytorch, what are the gradient arguments | I am reading through the documentation of PyTorch and found an example where they write
gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
print(x.grad)
where x was an initial variable, from which y was constructed (a 3-vector). The question is, what are the 0.1, 1.0 and 0.0001 arguments of the... |
The original code I haven't found on PyTorch website anymore.
gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
print(x.grad)
The problem with the code above is there is no function based on how to calculate the gradients. This means we don't know how many parameters (arguments the function tak... | https://stackoverflow.com/questions/43451125/ |
Error when compiling pytorch: 'cstdint' file not found | I was attempting to compile pytorch using NO_CUDA=1 python setup.py install on Mac OS X, but I got these errors:
In file included from /Users/ezyang/Dev/pytorch-tmp/torch/lib/tmp_install/include/THPP/Tensor.hpp:3:
/Users/ezyang/Dev/pytorch-tmp/torch/lib/tmp_install/include/THPP/Storage.hpp:6:10: fatal error:
'c... | You need to setup environment variables to have Python use the correct C compiler on OS X. You should do this instead:
NO_CUDA=1 MACOSX_DEPLOYMENT_TARGET=10.9 CC=clang CXX=clang++ python setup.py install
| https://stackoverflow.com/questions/43640454/ |
How to use the BCELoss in PyTorch? | I want to write a simple autoencoder in PyTorch and use BCELoss, however, I get NaN out, since it expects the targets to be between 0 and 1. Could someone post a simple use case of BCELoss?
| Update
The BCELoss function did not use to be numerically stable. See this issue https://github.com/pytorch/pytorch/issues/751. However, this issue has been resolved with Pull #1792, so that BCELoss is numerically stable now!
Old answer
If you build PyTorch from source, you can use the numerically stable function ... | https://stackoverflow.com/questions/43708693/ |
pytorch Network.parameters() missing 1 required positional argument: 'self' | There's a problem when I call Network.parameters() in pytorch in this line in my main function:
optimizer = optim.SGD(Network.parameters(), lr=0.001, momentum=0.9)
I get the error code:
TypeError: parameters() missing 1 required positional argument: 'self'
My network is defined in this class
class Network(nn.Module... | When doing Network.parameters() you are calling the static method parameters.
But, parameters is an instance method.
So you have to instansiate Network before calling parameters.
network = Network()
optimizer = optim.SGD(network.parameters(), lr=0.001, momentum=0.9)
Or, if you only needs Network first this particu... | https://stackoverflow.com/questions/43779500/ |
Pytorch, TypeError: object() takes no parameters | This is probably a beginner question, but nevertheless: When running an image classifier build with pytorch, I get this error:
Traceback (most recent call last):
File "/pytorch/kanji_torch.py", line 47, in <module>
network = Network()
File "/pytorch/kanji_torch.py", line 113, in __init__
self.conv1 = n... | You might have a problem with your pytorch version, when I run the code:
class Network(torch.nn.Module):
def __init__(self):
super(Network, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(32, 64, 5)
self.pool2 = nn.MaxP... | https://stackoverflow.com/questions/43781526/ |
How to run PyTorch on GPU by default? | I want to run PyTorch using cuda. I set model.cuda() and torch.cuda.LongTensor() for all tensors.
Do I have to create tensors using .cuda explicitly if I have used model.cuda()?
Is there a way to make all computations run on GPU by default?
| I do not think you can specify that you want to use cuda tensors by default.
However you should have a look to the pytorch offical examples.
In the imagenet training/testing script, they use a wrapper over the model called DataParallel.
This wrapper has two advantages:
it handles the data parallelism over multiple G... | https://stackoverflow.com/questions/43806326/ |
Fixing a subset of weights in Neural network during training | I am considering creating a customized neural network. The basic structure is the same as usual, but I want to truncate the connections between layers. For example, if I construct a network with two hidden layers, I would like to delete some weights and keep the others, like so:
This is not conventional dropout (to av... | Yes you can do this in tensorflow.
You would have some layer in your tensorflow code something like so:
m = tf.Variable( [width,height] , dtype=tf.float32 ))
b = tf.Variable( [height] , dtype=tf.float32 ))
h = tf.sigmoid( tf.matmul( x,m ) + b )
What you want is some new matrix, let's call it k for kill. It is go... | https://stackoverflow.com/questions/43851657/ |
Accuracy score in pyTorch LSTM | I have been running this LSTM tutorial on the wikigold.conll NER data set
training_data contains a list of tuples of sequences and tags, for example:
training_data = [
("They also have a song called \" wake up \"".split(), ["O", "O", "O", "O", "O", "O", "I-MISC", "I-MISC", "I-MISC", "I-MISC"]),
("Major Genera... | I would use numpy in order to not iterate the list in pure python.
The results are the same, but it runs much faster
def accuracy_score(y_true, y_pred):
y_pred = np.concatenate(tuple(y_pred))
y_true = np.concatenate(tuple([[t for t in y] for y in y_true])).reshape(y_pred.shape)
return (y_true == y_pred).s... | https://stackoverflow.com/questions/43962599/ |
Can I slice tensors with logical indexing or lists of indices? | I'm trying to slice a PyTorch tensor using a logical index on the columns. I want the columns that correspond to a 1 value in the index vector. Both slicing and logical indexing are possible, but are they possible together? If so, how? My attempt keeps throwing the unhelpful error
TypeError: indexing a tensor with an ... | I think this is implemented as the index_select function, you can try
import torch
A_idx = torch.LongTensor([0, 2]) # the index vector
B = torch.LongTensor([[1, 2, 3], [4, 5, 6]])
C = B.index_select(1, A_idx)
# 1 3
# 4 6
| https://stackoverflow.com/questions/43989310/ |
PyTorch: How to convert pretrained FC layers in a CNN to Conv layers | I want to convert a pre-trained CNN (like VGG-16) to a fully convolutional network in Pytorch. How can I do so?
| You can do that as follows (see comments for description):
import torch
import torch.nn as nn
from torchvision import models
# 1. LOAD PRE-TRAINED VGG16
model = models.vgg16(pretrained=True)
# 2. GET CONV LAYERS
features = model.features
# 3. GET FULLY CONNECTED LAYERS
fcLayers = nn.Sequential(
# stop at last l... | https://stackoverflow.com/questions/44146655/ |
how does the pytorch autograd work? | I submitted this as an issue to cycleGAN pytorch implementation, but since nobody replied me there, i will ask again here.
I'm mainly puzzled by the fact that multiple forward passes was called before one single backward pass, see the following in code cycle_gan_model
# GAN loss
# D_A(G_A(A))
self.fake_B = self.netG_... | Pytorch uses a tape based system for automatic differentiation. that means that it will backpropagate from the last operation it did. I think that the best way to understand is make a diagram from the process. I attach one that I did by hand
Now you will see that some modules are "repeated". The way I think about them... | https://stackoverflow.com/questions/44198736/ |
Convolutional NN for text input in PyTorch | I am trying to implement a text classification model using a CNN. As far as I know, for text data, we should use 1d Convolutions. I saw an example in pytorch using Conv2d but I want to know how can I apply Conv1d for text? Or, it is actually not possible?
Here is my model scenario:
Number of in-channels: 1, Number of o... | This example of Conv1d and Pool1d layers into an RNN resolved my issue.
So, I need to consider the embedding dimension as the number of in-channels while using nn.Conv1d as follows.
m = nn.Conv1d(200, 10, 2) # in-channels = 200, out-channels = 10
input = Variable(torch.randn(10, 200, 5)) # 200 = embedding dim, 5 = se... | https://stackoverflow.com/questions/44212831/ |
OverflowError: (34, 'Numerical result out of range') in PyTorch | I am getting the following error (see the stacktrace) when I ran my code in a different GPU (Tesla K-20, cuda 7.5 installed, 6GB memory). Code works fine if I run in GeForce 1080 or Titan X GPU.
Stacktrace:
File "code/source/main.py", line 68, in <module>
train.train_epochs(train_batches, dev_batches, args.... | One workaround that is suggested in discuss.pytorch.org is as follows.
Replacing the following lines in adam.py:-
bias_correction1 = 1 - beta1 ** state['step']
bias_correction2 = 1 - beta2 ** state['step']
BY
bias_correction1 = 1 - beta1 ** min(state['step'], 1022)
bias_correction2 = 1 - beta2 ** min(state['step']... | https://stackoverflow.com/questions/44230829/ |
KeyError: 'unexpected key "module.encoder.embedding.weight" in state_dict' | I am getting the following error while trying to load a saved model.
KeyError: 'unexpected key "module.encoder.embedding.weight" in state_dict'
This is the function I am using to load a saved model.
def load_model_states(model, tag):
"""Load a previously saved model states."""
filename = os.path.join(args.sa... | I solved the problem. Actually I was saving the model using nn.DataParallel, which stores the model in module, and then I was trying to load it without DataParallel. So, either I need to add a nn.DataParallel temporarily in my network for loading purposes, or I can load the weights file, create a new ordered dict witho... | https://stackoverflow.com/questions/44230907/ |
backward, grad function in pytorch | I'm trying to implement backward, grad function in pytorch.
But, I don't know why this value is returned.
Here is my code.
x = Variable(torch.FloatTensor([[1,2],[3,4]]), requires_grad=True)
y = x + 2
z = y * y
gradient = torch.ones(2, 2)
z.backward(gradient)
print(x.grad)
I think that result value should be [[6,8... | The below piece of code on pytorch v0.12.1
import torch
from torch.autograd import Variable
x = Variable(torch.FloatTensor([[1,2],[3,4]]), requires_grad=True)
y = x + 2
z = y * y
gradient = torch.ones(2, 2)
z.backward(gradient)
print(x.grad)
returns
Variable containing:
6 8
10 12
[torch.FloatTensor of size 2... | https://stackoverflow.com/questions/44264018/ |
Why should be the function backward be called only on 1 element tensor or with gradients w.r.t to Variable? | I am new to pytorch. I want to understand as to why we can't call the backward function on a variable containing a tensor of say size say [2,2].
And if we do want to call it on a variable containing tensor of say size say [2,2], we have to do that by first defining a gradient tensor and then calling the backward functi... | from the tutorial on autograd
If you want to compute the derivatives, you can call .backward() on a
Variable. If Variable is a scalar (i.e. it holds a one element data),
you don’t need to specify any arguments to backward(), however if it
has more elements, you need to specify a grad_output argument that is
... | https://stackoverflow.com/questions/44264443/ |
PyTorch: access weights of a specific module in nn.Sequential() | When I use a pre-defined module in PyTorch, I can typically access its weights fairly easily. However, how do I access them if I wrapped the module in nn.Sequential() first? r.g:
class My_Model_1(nn.Module):
def __init__(self,D_in,D_out):
super(My_Model_1, self).__init__()
self.layer = nn.Linear(D_i... | From the PyTorch forum, this is the recommended way:
model_2.layer[0].weight
| https://stackoverflow.com/questions/44284506/ |
Deep learning: save and load a universal machine model through different libraries | My questions can be divided into two parts.
Is there a format of machine learning model file that can be used through different libraries? For example, I saved a model by pytorch, then load it using tensorflow?
If not, is there a library that can help transfer the formats so that a pytorch machine learning model can ... | Very interesting question. A neural network is a mathematical abstraction consisting of a network of layers (convolution, recurrent, ...), operations (dot product, non-linearity, ...) and their respective parameters (weights, biases).
AFAIK, there's not an universal model file. Nonetheless, different libraries allow ... | https://stackoverflow.com/questions/44318616/ |
How to get a uniform distribution in a range [r1,r2] in PyTorch? | I want to get a 2-D torch.Tensor with size [a,b] filled with values from a uniform distribution (in range [r1,r2]) in PyTorch.
| If U is a random variable uniformly distributed on [0, 1], then (r1 - r2) * U + r2 is uniformly distributed on [r1, r2].
Thus, you just need:
(r1 - r2) * torch.rand(a, b) + r2
Alternatively, you can simply use:
torch.FloatTensor(a, b).uniform_(r1, r2)
To fully explain this formulation, let's look at some concr... | https://stackoverflow.com/questions/44328530/ |
How can I install python modules in a docker image? | I have an image called: Image and a running container called: container. I want to install pytorch and anacoda. what's the easiest way to do this? Do I have to change the dockerfile and build a new image? Thanks a lot.
| Yes, the best thing is to build your image in such a way it has the python modules are in there.
Here is an example. I build an image with the build dependencies:
$ docker build -t oz123/alpine-test-mycoolapp:0.5 - < Image
Sending build context to Docker daemon 2.56 kB
Step 1 : FROM alpine:3.5
---> 88e169ea8f... | https://stackoverflow.com/questions/44339375/ |
How to convert Pytorch autograd.Variable to Numpy? | The title says it all. I want to convert a PyTorch autograd.Variable to its equivalent numpy array. In their official documentation they advocated using a.numpy() to get the equivalent numpy array (for PyTorch tensor). But this gives me the following error:
Traceback (most recent call last): File "stdin", line 1, i... | Two possible case
Using GPU: If you try to convert a cuda float-tensor directly to numpy like shown below,it will throw an error.
x.data.numpy()
RuntimeError: numpy conversion for FloatTensor is not supported
So, you cant covert a cuda float-tensor directly to numpy, instead you have to convert it into a ... | https://stackoverflow.com/questions/44340848/ |
PyTorch Linear layer input dimension mismatch | Im getting this error when passing the input data to the Linear (Fully Connected Layer) in PyTorch:
matrices expected, got 4D, 2D tensors
I fully understand the problem since the input data has a shape (N,C,H,W) (from a Convolutional+MaxPool layer) where:
N: Data Samples
C: Channels of the data
H,W: Height and Wid... | After reading some Examples I found the solution. here is how you do it without messing up the forward/backward pass flow:
(_, C, H, W) = x.data.size()
x = x.view( -1 , C * H * W)
| https://stackoverflow.com/questions/44357055/ |
What is the relationship between PyTorch and Torch? | There are two PyTorch repositories :
https://github.com/hughperkins/pytorch
https://github.com/pytorch/pytorch
The first clearly requires Torch and lua and is a wrapper, but the second doesn't make any reference to the Torch project except with its name.
How is it related to the Lua Torch?
| Here a short comparison on pytorch and torch.
Torch:
A Tensor library like numpy, unlike numpy it has strong GPU support.
Lua is a wrapper for Torch (Yes! you need to have a good understanding of Lua), and for that you will need LuaRocks package manager.
PyTorch:
No need for the LuaRocks package manager, no need to ... | https://stackoverflow.com/questions/44371560/ |
Handling C++ arrays in Cython (with numpy and pytorch) | I am trying to use cython to wrap a C++ library (fastText, if its relevant). The C++ library classes load a very large array from disk. My wrapper instantiates a class from the C++ library to load the array, then uses cython memory views and numpy.asarray to turn the array into a numpy array, then calls torch.from_nump... | I can think of three sensible ways of doing it. I'll outline them below (i.e. none of the code will be complete but hopefully it will be clear how to finish it).
1. C++ owns the memory; Cython/Python holds a shared pointer to the C++ class
(This is looks to be the lines you're already thinking along).
Start by creat... | https://stackoverflow.com/questions/44396749/ |
Implementing Adagrad in Python | I'm trying to implement Adagrad in Python. For learning purposes, I am using matrix factorisation as an example. I'd be using Autograd for computing the gradients.
My main question is if the implementation is fine.
Problem description
Given a matrix A (M x N) having some missing entries, decompose into W and H havin... | At a cursory glance, your code closely matches that at https://github.com/benbo/adagrad/blob/master/adagrad.py
del_W, del_H = grad_cost(W, H)
matches
grad=f_grad(w,sd,*args)
gt_w+= np.square(del_W)
gt_h+= np.square(del_H)
matches
gti+=grad**2
mod_learning_rate_W = np.divide(learning_rate, np.sqrt(gt_w+e... | https://stackoverflow.com/questions/44405297/ |
pytorch custom layer "is not a Module subclass" | I am new to PyTorch, trying it out after using a different toolkit for a while.
I would like understand how to program custom layers and functions. And as a simple test, I wrote this:
class Testme(nn.Module): ## it _is_ a sublcass of module ##
def __init__(self):
super(Testme, self).__init__()
... | That's a simple one. You almost got it, but you forgot to actually create an instance of your new class Testme. You need to do this, even if the creation of an instance of a particular class doesn't take any parameters (as for Testme). But it's easier to forget than for a convolutional layer, to which you typically pas... | https://stackoverflow.com/questions/44406819/ |
when is a pytorch custom function needed (rather than only a module)? | Pytorch beginner here! Consider the following custom Module:
class Testme(nn.Module):
def __init__(self):
super(Testme, self).__init__()
def forward(self, x):
return x / t_.max(x).expand_as(x)
As far as I understand the documentation:
I believe this could also be implemented as a custom Function. A... | This information is gathered and summarised from the official PyTorch Documentaion.
torch.autograd.Functionreally lies at the heart of the autograd package in PyTorch. Any graph you build in PyTorch and any operation you conduct on Variables in PyTorch is based on a Function. Any function requires an __init__(), forw... | https://stackoverflow.com/questions/44428784/ |
How to load a list of numpy arrays to pytorch dataset loader? | I have a huge list of numpy arrays, where each array represents an image and I want to load it using torch.utils.data.Dataloader object. But the documentation of torch.utils.data.Dataloader mentions that it loads data directly from a folder. How do I modify it for my cause? I am new to pytorch and any help would be gre... | I think what DataLoader actually requires is an input that subclasses Dataset. You can either write your own dataset class that subclasses Datasetor use TensorDataset as I have done below:
import torch
import numpy as np
from torch.utils.data import TensorDataset, DataLoader
my_x = [np.array([[1.0,2],[3,4]]),np.arra... | https://stackoverflow.com/questions/44429199/ |
Creating one hot vector from indices given as a tensor | I have a tensor of size 4 x 6 where 4 is batch size and 6 is sequence length. Every element of the sequence vectors are some index (0 to n). I want to create a 4 x 6 x n tensor where the vectors in 3rd dimension will be one hot encoding of the index which means I want to put 1 in the specified index and rest of the val... | NEW ANSWER
As of PyTorch 1.1, there is a one_hot function in torch.nn.functional. Given any tensor of indices indices and a maximal index n, you can create a one_hot version as follows:
n = 5
indices = torch.randint(0,n, size=(4,7))
one_hot = torch.nn.functional.one_hot(indices, n) # size=(4,7,n)
Very old Answer
At... | https://stackoverflow.com/questions/44461772/ |
tensor division in pytorch. Assertion error | This is kind of a pytorch beginner question. In pytorch I'm trying to do element wise division with two tensors of size [5,5,3]. In numpy it works fine using np.divide(), but somehow I get an error here. I'm using PyTorch version 0.1.12 for Python 3.5.
c = [torch.DoubleTensor of size 5x5x3]
input_patch = [torch.Float... | Input_patch is a slice of a torch.autograd Variable, and c is made by doing
c = torch.from_numpy(self.patch_filt[:, :, :, 0]).float()
Anyway, mexmex, thanks to your comment I've solved it by defining c as
Variable(torch.from_numpy(self.patch_filt[:, :, :, 0])).float()
| https://stackoverflow.com/questions/44518677/ |
How do I multiply matrices in PyTorch? | With numpy, I can do a simple matrix multiplication like this:
a = numpy.ones((3, 2))
b = numpy.ones((2, 1))
result = a.dot(b)
However, this does not work with PyTorch:
a = torch.ones((3, 2))
b = torch.ones((2, 1))
result = torch.dot(a, b)
This code throws the following error:
RuntimeError: 1D tensors expected, but ... | Use torch.mm:
torch.mm(a, b)
torch.dot() behaves differently to np.dot(). There's been some discussion about what would be desirable here. Specifically, torch.dot() treats both a and b as 1D vectors (irrespective of their original shape) and computes their inner product. The error is thrown because this behaviour make... | https://stackoverflow.com/questions/44524901/ |
python child process exit unexpectedly with exit code -9 | I have a PyTorch script with 16 processes. Following is a code snippet from the main process:
procs = [mp.Process(target=self.worker_wrapper, args=(i, )) for i in range(self.n_workers)]
for p in procs: p.start()
while True:
time.sleep(60)
for i, p in enumerate(procs):
self.logger.info('Check: id %d, ex... | Exit code -9 means the process was killed via SIGKILL.
It's probably due to your machine running out of memory and the OS kernel was triggering the OOM killer.
To verify that, check the kernel logs via dmesg you should notice the OOM killer targeting your worker processes.
You need to reduce the memory footprint o... | https://stackoverflow.com/questions/44576035/ |
CUDA vs. DataParallel: Why the difference? | I have a simple neural network model and I apply either cuda() or DataParallel() on the model like following.
model = torch.nn.DataParallel(model).cuda()
OR,
model = model.cuda()
When I don't use DataParallel, rather simply transform my model to cuda(), I need to explicitly convert the batch inputs to cuda() and ... | Because, DataParallel allows CPU inputs, as it's first step is to transfer inputs to appropriate GPUs.
Info source: https://discuss.pytorch.org/t/cuda-vs-dataparallel-why-the-difference/4062/3
| https://stackoverflow.com/questions/44580450/ |
Custom loss function in PyTorch | I have three simple questions.
What will happen if my custom loss function is not differentiable? Will pytorch through error or do something else?
If I declare a loss variable in my custom function which will represent the final loss of the model, should I put requires_grad = True for that variable? or it doesn't mat... | Let me have a go.
This depends on what you mean by "non-differentiable". The first definition that makes sense here is that PyTorch doesn't know how to compute gradients. If you try to compute gradients nevertheless, this will raise an error. The two possible scenarios are:
a) You're using a custom PyTorch operatio... | https://stackoverflow.com/questions/44597523/ |
Is Torch7 defined-by-run like Pytorch? | Pytorch have Dynamic Neural Networks (defined-by-run) as opposed to Tensorflow which have to compile the computation graph before run.
I see that both Torch7 and PyTorch depend on TH, THC, THNN, THCUNN (C library). Does Torch7 have Dynamic Neural Networks (defined-by-run) feature ?
| No, Torch7 use static computational graphs, as in Tensorflow. It is one of the major differences between PyTorch and Torch7.
| https://stackoverflow.com/questions/44614977/ |
subtraction of scalar from tensor yields 'inconsistent tensor size' in pytorch | I'm using pytorch and my variables are
x = [torch.FloatTensor of size 1x3x32x32]
mean = Variable containing:
1.00000e-02 *
2.0518
[torch.FloatTensor of size 1]
what I want to do is subtract the scalar mean from x by doing
x = x - mean
However, I'm getting this error:
RuntimeError: inconsistent tensor size at /... | what you are trying only works if mean is truly a scalar, i.e. a float() (in this case) and not a torch.FloatTensor of size 1. You can either extract a true scalar from mean or expand mean to the size of x in order to perform the subtraction.
To extract the float from mean, do:
x = x - mean[0]
To expand mean to t... | https://stackoverflow.com/questions/44631520/ |
Convert 'int' to pytorch 'Variable' makes problems | First project with pytorch and I got stuck trying to convert an MNIST label 'int' into a torch 'Variable'. Debugger says it has no dimension?!
# numpy mnist data
X_train, Y_train = read_data("training")
X_test , Y_test = read_data("testing")
arr = np.zeros(5)
for i in range(5):
# in your training loop:
costs... | The error is telling you exactly what is happening. Your target variable is empty.
Edit (after the comment below):
if Y_train[k] = 5, then np.array(Y_train[k], dtype=np.float).shape = (), and in turn Variable(b) becomes a tensor with no dimension.
In order to fix this you will need to pass a list to np.array() and... | https://stackoverflow.com/questions/44631628/ |
Pytorch: how to add L1 regularizer to activations? | I would like to add the L1 regularizer to the activations output from a ReLU.
More generally, how does one add a regularizer only to a particular layer in the network?
Related material:
This similar post refers to adding L2 regularization, but it appears to add the regularization penalty to all layers of the network... | Here is how you do this:
In your Module's forward return final output and layers' output for which you want to apply L1 regularization
loss variable will be sum of cross entropy loss of output w.r.t. targets and L1 penalties.
Here's an example code
import torch
from torch.autograd import Variable
from torch.nn imp... | https://stackoverflow.com/questions/44641976/ |
How do you implement variable-length recurrent neural networks? | What is a full working example (not snippets) of variable-length sequence inputs into recurrent neural networks (RNNs)?
For example PyTorch supposedly can implement variable-length sequences as input into RNNs, but there do not seem to be examples of full working code.
Relevant:
https://github.com/pytorch/pytorch... | Sadly, there is no such thing as 'variable length' neural networks. This is because there is no way a network can 'know' which weights to use for extra input nodes that it wasn't trained for.
However, the reason you are seeing a 'variable length' on that page, is because they process:
a b c d e
a b c d e f g h
a b c ... | https://stackoverflow.com/questions/44642939/ |
How do you use PyTorch PackedSequence in code? | Can someone give a full working code (not a snippet, but something that runs on a variable-length recurrent neural network) on how would you use the PackedSequence method in PyTorch?
There do not seem to be any examples of this in the documentation, github, or the internet.
https://github.com/pytorch/pytorch/releases... | Not the most beautiful piece of code, but this is what I gathered for my personal use after going through PyTorch forums and docs. There can be certainly better ways to handle the sorting - restoring part, but I chose it to be in the network itself
EDIT: See answer from @tusonggao which makes torch utils take care of s... | https://stackoverflow.com/questions/44643137/ |
Pytorch: Convert FloatTensor into DoubleTensor | I have 2 numpy arrays, which I convert into tensors to use the TensorDataset object.
import torch.utils.data as data_utils
X = np.zeros((100,30))
Y = np.zeros((100,30))
train = data_utils.TensorDataset(torch.from_numpy(X).double(), torch.from_numpy(Y))
train_loader = data_utils.DataLoader(train, batch_size=50, shu... | Your numpy arrays are 64-bit floating point and will be converted to torch.DoubleTensor standardly. Now, if you use them with your model, you'll need to make sure that your model parameters are also Double. Or you need to make sure, that your numpy arrays are cast as Float, because model parameters are standardly cast ... | https://stackoverflow.com/questions/44717100/ |
Why do we need to explicitly call zero_grad()? | Why do we need to explicitly zero the gradients in PyTorch? Why can't gradients be zeroed when loss.backward() is called? What scenario is served by keeping the gradients on the graph and asking the user to explicitly zero the gradients?
| We explicitly need to call zero_grad() because, after loss.backward() (when gradients are computed), we need to use optimizer.step() to proceed gradient descent. More specifically, the gradients are not automatically zeroed because these two operations, loss.backward() and optimizer.step(), are separated, and optimizer... | https://stackoverflow.com/questions/44732217/ |
PyTorch: Extract learned weights correctly | I am trying to extract the weights from a linear layer, but they do not appear to change, although error is dropping monotonously (i.e. training is happening). Printing the weights' sum, nothing happens because it stays constant:
np.sum(model.fc2.weight.data.numpy())
Here are the code snippets:
def train(epochs... | Use model.parameters() to get trainable weight for any model or layer. Remember to put it inside list(), or you cannot print it out.
The following code snip worked
>>> import torch
>>> import torch.nn as nn
>>> l = nn.Linear(3,5)
>>> w = list(l.parameters())
>>> w
| https://stackoverflow.com/questions/44734327/ |
Re-weight the input to a neural network | For example, I feed a set of images into a CNN. And the default weight of these images is 1. How can I re-weight some of these images so that they have different weights? Can 'DataLoader' achieve this goal in pytorch?
I learned two other possibilities:
Defining a custom loss function, providing weights for each samp... | I can think of two ways to achieve this.
Pass on the weight explicitly, when you backpropagate the gradients.
After you computed loss, and when you're about to backpropagate, you can pass a Tensor to backward() and all the subsequent gradients will be scaled by the corresponding element, i.e. do something like
loss = ... | https://stackoverflow.com/questions/44743305/ |
Torch sum a tensor along an axis | How do I sum over the columns of a tensor?
torch.Size([10, 100]) ---> torch.Size([10])
| The simplest and best solution is to use torch.sum().
To sum all elements of a tensor:
torch.sum(x) # gives back a scalar
To sum over all rows (i.e. for each column):
torch.sum(x, dim=0) # size = [ncol]
To sum over all columns (i.e. for each row):
torch.sum(x, dim=1) # size = [nrow]
It should be noted that the dimen... | https://stackoverflow.com/questions/44790670/ |
Apply json config file using parse_args() in pycharm | I'm running sequence to sequence code in git, but I got error about parse_args().
my code is like this:
parser = argparse.ArgumentParser()
parser.add_argument(
"--config",
help="path to json config",
required=True)
args = parser.parse_args()
config_file_path = args.config
config = read_config(config_file_p... | args = parser.parse_args() parses the sys.argv[1:] list, which is provided to the interpreter from the operating system shell - ie. from the commandline.
$:python prog.py --config afilename
You can also do
args = parser.parse_args(['--config', 'afilename'])
this handy during testing.
It also helps to:
import s... | https://stackoverflow.com/questions/44815875/ |
how to append a singleton numpy array item into a list? | I am attaching the code first which will give you a better idea
` prediction = prediction.data.max(1)[1] #gives a tensor value
prediction = (prediction.cpu().numpy().item()) #converts that tensor into a numpy array
result.append(int_to_word[prediction])`
I am using pytorch for word generation. The line pr... | Numpy arrays are immutable with respect to their dimensions. They do not support the append operation. You'll have to declare results as a list, then append your values to your list, and then convert it to a numpy array:
result = []
...
result.append(prediction) # inside some loop
...
result = np.array(result)
| https://stackoverflow.com/questions/44819563/ |
No N-dimensional tranpose in PyTorch | PyTorch's torch.transpose function only transposes 2D inputs. Documentation is here.
On the other hand, Tensorflow's tf.transpose function allows you to transpose a tensor of N arbitrary dimensions.
Can someone please explain why PyTorch does not/cannot have N-dimension transpose functionality? Is this due to the dyn... | It's simply called differently in pytorch. torch.Tensor.permute will allow you to swap dimensions in pytorch like tf.transpose does in TensorFlow.
As an example of how you'd convert a 4D image tensor from NHWC to NCHW (not tested, so might contain bugs):
>>> img_nhwc = torch.randn(10, 480, 640, 3)
>>&g... | https://stackoverflow.com/questions/44841654/ |
How to debug(monitoring value of object in other class' function) in Pycharm | I'm running seq2seq code in pycharm in order to study pytorch.
The code has many classes and these classes have many function.
I'd like to monitor value of objects in other function, so I'm running code in console one by one.
Is there any good way to this using debug?
I haven't done debug before.
Please help me..... | I'm not familiar with these tools specifically, but here is how I would approach it. It's also kinda hard to express how to properly use a gui interactively through text, so if you are new to a debugger in general it might be good to start with some tutorials. Jetbrains has some PyCharm debugger tutorials online.
PyC... | https://stackoverflow.com/questions/44843773/ |
How do you alter the size of a Pytorch Dataset? | Say I am loading MNIST from torchvision.datasets.MNIST, but I only want to load in 10000 images total, how would I slice the data to limit it to only some number of data points? I understand that the DataLoader is a generator yielding data in the size of the specified batch size, but how do you slice datasets?
tr = da... | It is important to note that when you create the DataLoader object, it doesnt immediately load all of your data (its impractical for large datasets). It provides you an iterator that you can use to access each sample.
Unfortunately, DataLoader doesnt provide you with any way to control the number of samples you wish ... | https://stackoverflow.com/questions/44856691/ |
Find number of non-zero elements in a tensor along an aixs | I want to find the number of non-zero elements in a tensor along a particular axis. Is there any PyTorch function which can do this?
I tried to use the nonzero() method in PyTorch.
torch.nonzero(losses).size(0)
Here, lossess is a tensor of shape 64 x 1. When I run the above statement, it gives me the following erro... | Meaning of the error message - TypeError: Type Variable doesn't implement stateless method nonzero is, we cannot use torch.nonzero() on autograd.Variable but only on simple tensors. Also it should be noted that, tensors are stateless while the Variables are stateful.
| https://stackoverflow.com/questions/44857373/ |
PyTorch - Element-wise multiplication between a variable and a tensor? | As of PyTorch 0.4 this question is no longer valid. In 0.4 Tensors and Variables were merged.
How can I perform element-wise multiplication with a variable and a tensor in PyTorch? With two tensors works fine. With a variable and a scalar works fine. But when attempting to perform element-wise multiplication with a va... | Yes, you are correct. Elementwise multiplication (like most other operations) is only supported for Tensor * Tensor or Variable * Variable, but not for Tensor * Variable.
To perform your multiplication above, wrap your Tensor as a Variable which doesn't require gradients. The additional overhead is insignificant.
y_... | https://stackoverflow.com/questions/44875430/ |
Pytorch nn.functional.batch_norm for 2D input | I am currently implementing a model on which I need to change the running mean and standard deviation during test time. As such, I assume the nn.functional.batch_norm would be a better choice than the nn.BatchNorm2d
However, I have batches of images as input, and am currently not sure how to take in the images. How wo... | The key is that 2D batchnorm performs the same normalization for each channel. i.e. if you have a batch of data with shape (N, C, H, W) then your mu and stddev should be shape (C,). If your images do not have a channel dimension, then add one using view.
Warning: if you set training=True then batch_norm computes and u... | https://stackoverflow.com/questions/44887446/ |
requires_grad relation to leaf nodes | From the docs:
requires_grad – Boolean indicating whether the Variable has been
created by a subgraph containing any Variable, that requires it. Can
be changed only on leaf Variables
What does it mean by leaf nodes here? Are leaf nodes only the input nodes?
If it can be only changed at the leaf nodes, how c... |
Leaf nodes of a graph are those nodes (i.e. Variables) that were not computed directly from other nodes in the graph. For example:
import torch
from torch.autograd import Variable
A = Variable(torch.randn(10,10)) # this is a leaf node
B = 2 * A # this is not a leaf node
w = Variable(torch.randn(10,10)) # this is a ... | https://stackoverflow.com/questions/44913720/ |
How two rows can be swapped in a torch tensor? | var = [[0, 1, -4, 8],
[2, -3, 2, 1],
[5, -8, 7, 1]]
var = torch.Tensor(var)
Here, var is a 3 x 4 (2d) tensor. How the first and second row can be swapped to get the following 2d tensor?
2, -3, 2, 1
0, 1, -4, 8
5, -8, 7, 1
| The other answer does not work, as some dimensions get overwritten before they are copied:
>>> var = [[0, 1, -4, 8],
[2, -3, 2, 1],
[5, -8, 7, 1]]
>>> x = torch.tensor(var)
>>> index = torch.LongTensor([1, 0, 2])
>>> x[index] = x
>>> x
tensor([[ 0, 1, -4, 8],... | https://stackoverflow.com/questions/44935176/ |
How padded sequences given as packed sequences are dealt by RNN in pytorch? | In pytorch, we can give a packed sequence as an input to the RNN. From official doc, input of an RNN can be as follows.
input (seq_len, batch, input_size): tensor containing the features of the input sequence. The input can also be a packed variable length sequence.
Example
packed = torch.nn.utils.rnn.pack_padd... | For the second question: hidden states at padded sequences will not be computed.
To answer how is that happening, let's first see what pack_padded_sequence does for us:
from torch.nn.utils.rnn import pad_sequence, pad_packed_sequence, pack_padded_sequence
raw = [ torch.ones(25, 300) / 2,
torch.ones(22, 300)... | https://stackoverflow.com/questions/44942931/ |
Backpropagation without updating weights (DCGAN) | The basic idea is, that I load a trained model (DCGAN) and make a anomaly detection with it on images. For the anomaly detection I have to do some iterations on the test phase to evaluate it, if it is a anomaly or not.
For that I have two Loss-Functions in the test setup, which should be calculating a backpropagation... | Yes, you're on the right track there.
You can individually set the requires_grad attribute of your model parameters (more precisely of all leaf nodes in your computational graph). I am not familiar with DCGAN, but I assume the latent vector is a trainable parameter, too (else a back-propagation update makes little sen... | https://stackoverflow.com/questions/44946190/ |
Why does an attribute has a method? | I use pytorch define a Variable x, compute and get its gradient x.grad, meaning grad is an attribute of instance x. But, I can use x.grad.data.zero_() to set x.grad to zero meaning that data.zero_() is method of x.grad. Why does an attribute has a method? Thanks a lot.
| It will be just an object attribute, for example we can have an attribute of type String. And we all now String have his own methods including the method that prints out the value of itself
| https://stackoverflow.com/questions/44951963/ |
Why RNN need two bias vectors? | In pytorch RNN implementation, there are two biases, b_ih and b_hh.
Why is this? Is it different from using one bias? If yes, how? Will it affect performance or efficiency?
| The formular in Pytorch Document in RNN is self-explained. That is b_ih and b_hh in the equation.
You may think that b_ih is bias for input (which pair with w_ih, weight for input) and b_hh is bias for hidden (pair with w_hh, weight for hidden)
| https://stackoverflow.com/questions/45005163/ |
Include .whl installation in requirements.txt | How do I include this in the requirements.txt file?
For Linux:
pip install http://download.pytorch.org/whl/cu75/torch-0.1.12.post2-cp27-none-linux_x86_64.whl
pip install torchvision
FOR MacOS:
pip install http://download.pytorch.org/whl/torch-0.1.12.post2-cp27-none-macosx_10_7_x86_64.whl
pip install torchvision
... | You can use environment markers:
http://download.pytorch.org/whl/cu75/torch-0.1.12.post2-cp27-none-linux_x86_64.whl ; sys_platform == "linux"
http://download.pytorch.org/whl/cu75/torch-0.1.12.post2-cp27-none-linux_x86_64.whl ; sys_platform == "linux2"
http://download.pytorch.org/whl/torch-0.1.12.post2-cp27-none-macosx... | https://stackoverflow.com/questions/45018492/ |
Understanding a simple LSTM pytorch | import torch,ipdb
import torch.autograd as autograd
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
rnn = nn.LSTM(input_size=10, hidden_size=20, num_layers=2)
input = Variable(torch.randn(5, 3, 10))
h0 = Variable(torch.randn(2, 3, 20))
c0 = Variable... | The output for the LSTM is the output for all the hidden nodes on the final layer.
hidden_size - the number of LSTM blocks per layer.
input_size - the number of input features per time-step.
num_layers - the number of hidden layers.
In total there are hidden_size * num_layers LSTM blocks.
The input dimensions are (seq... | https://stackoverflow.com/questions/45022734/ |
How to simplify DataLoader for Autoencoder in Pytorch | Is there any easier way to set up the dataloader, because input and target data is the same in case of an autoencoder and to load the data during training? The DataLoader always requires two inputs.
Currently I define my dataloader like this:
X_train = rnd.random((300,100))
X_val = rnd.random((75,100))
trai... | Why not subclassing TensorDataset to make it compatible with unlabeled data ?
class UnlabeledTensorDataset(TensorDataset):
"""Dataset wrapping unlabeled data tensors.
Each sample will be retrieved by indexing tensors along the first
dimension.
Arguments:
data_tensor (Tensor): contains sample ... | https://stackoverflow.com/questions/45099554/ |
Indexing second dimension of Tensor using indices | I selected element in my tensor using a tensor of indices. Here the code below I use list of indices 0, 3, 2, 1 to select 11, 15, 2, 5
>>> import torch
>>> a = torch.Tensor([5,2,11, 15])
>>> torch.randperm(4)
0
3
2
1
[torch.LongTensor of size 4]
>>> i = torch.randperm(4)
>&... | If using pytorch version v0.1.12
For this version there isnt an easy way to do this. Even though pytorch promises tensor manipulation to be exactly like numpy's, there are some capabilities that are still lacking. This is one of them.
Typically you would be able to do this relatively easily if you were working with ... | https://stackoverflow.com/questions/45121182/ |
PyTorch RuntimeError : Gradients are not CUDA tensors |
I am getting the following error while doing seq to seq on characters and feeding to LSTM, and decoding to words using attention. The forward propagation is fine but while computing loss.backward() I am getting the following error.
RuntimeError: Gradients aren't CUDA tensors
My train() function is as followed.
... | Make sure that all the objects that inherit nn.Module also call their .cuda(). Make sure to call before you pass any tensor to them. (essentially before training)
For example, (and I am guessing your encoder and decoder are such objects), do this right before you call train().
encoder = encoder.cuda()
decoder = decoder... | https://stackoverflow.com/questions/45206561/ |
Is torchvision.datasets.cifar.CIFAR10 a list or not? | When I try to figure out what is inside torchvision.datasets.cifar.CIFAR10, I did some simple code
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
print(trainset[1])
print(trainset[:10])
print(type(trainset))
However, I got so... |
Slicing isnt supported by CIFAR10, which is why you are getting that error. If you want the first 10 you will have to do this instead:
print([trainset[i] for i in range(10)])
More Info
The main reason why you can index an instance of CIFAR10 class is because the class implements __getitem__() function.
So, when you ... | https://stackoverflow.com/questions/45225694/ |
Is there a way to use an external loss function in pytorch? | A typical skeleton of pytorch neural network has a forward() method, then we compute loss based on outputs of forward pass, and call backward() on that loss to update the gradients. What if my loss is determined externally (e.g. by running simulation in some RL environment). Can I still leverage this typical structure ... | In this case it appears easiest to me abstract the forward pass (your policy?) from the loss computation. This is because (as you note) in most scenarios, you will need to obtain a state (from your environment), then compute an action (essentially the forward pass), then feed that action back to the environment to obta... | https://stackoverflow.com/questions/45258655/ |
Numpy/PyTorch method for partial tiling | I seem to recall encountering a Numpy or PyTorch method similar to numpy.tile, except that it allowed partial tiling to reach specified dimensions. So if I had
a = np.array([[5, 6, 7, 8],
[1, 2, 3, 4]])
(or, correspondingly, t = torch.Tensor(a) if this is a PyTorch method),
then
a.mystery_method((3,... | You can use np.resize -
M = 3 # number of rows for output
np.resize(a,(M,a.shape[1]))
Another way with np.take or simply indexing along the first axis for performance -
np.take(a,np.arange(M)%a.shape[0],axis=0) # with np.take
a[np.arange(M)%a.shape[0]] # with indexing
Runtime test -
In [91]: a = n... | https://stackoverflow.com/questions/45298960/ |
pytorch: how to directly find gradient w.r.t. loss | In theano, it was very easy to get the gradient of some variable w.r.t. a given loss:
loss = f(x, w)
dl_dw = tt.grad(loss, wrt=w)
I get that pytorch goes by a different paradigm, where you'd do something like:
loss = f(x, w)
loss.backwards()
dl_dw = w.grad
The thing is I might not want to do a full backwards pro... | It turns out that this is reallyy easy. Just use torch.autograd.grad
Example:
import torch
import numpy as np
from torch.autograd import grad
x = torch.autograd.Variable(torch.from_numpy(np.random.randn(5, 4)))
w = torch.autograd.Variable(torch.from_numpy(np.random.randn(4, 3)), requires_grad=True)
y = torch.autogr... | https://stackoverflow.com/questions/45323240/ |
Running conv2d on tensor [batch, channel, sequence, H,W] in Pytorch | I am working on a video frame data where I am getting input data as tensor of the form [batch,channel,frame_sequence,height, weight] (let denote it by [B,C,S,H,W] for clarity. So each batch basically consists of a consecutive sequence of frame. What I basically want to do is run an encoder (consisting of several conv2d... |
What you are doing is completely fine. It will preserve the order. You can verify this by visualizing them.
I quickly built this for displaying the images stored in a 4d tensor (where dim=0 is batch) or a 5d tensor (where dim=0 is batch and dim=1 is sequence):
def custom_imshow(tensor):
if tensor.dim() == 4:
... | https://stackoverflow.com/questions/45353497/ |
Replace all nonzero values by zero and all zero values by a specific value | I have a 3d tensor which contains some zero and nonzero values. I want to replace all nonzero values by zero and zero values by a specific value. How can I do that?
|
Pretty much exactly how you would do it using numpy, like so:
tensor[tensor!=0] = 0
In order to replace zeros and non-zeros, you can just chain them together. Just be sure to use a copy of the tensor, since they get modified:
def custom_replace(tensor, on_zero, on_non_zero):
# we create a copy of the original... | https://stackoverflow.com/questions/45384684/ |
Tensor type mismatch when moving to GPU | I'm getting the following error when trying to move my network and tensors to GPU. I've checked that the network parameters are moved to the GPU and check each batch's tensor and move them if they're not already on the GPU. But I'm still getting this issue say that there's a mismatch in the tensor types - one is a torc... | This is happening because you are re-initializing self.input_layer in your forward() function.
The call self.network.cuda() moves all of the model parameters into cuda. Which means any and all the layers you initialize at the creation of your FeedForward object will be moved to cuda memory. But when you reinitialize ... | https://stackoverflow.com/questions/45446983/ |
TypeError: a float is required | l have a pytorch variable :
preds[4,4]
Out[305]:
Variable containing:
-96.7809
[torch.cuda.FloatTensor of size 1 (GPU 0)]
l want to do the following :
import math
x=preds[4,4]
y=maths.exp(x)
z= y / (y+1)
However when l do :
y=maths.exp(x)
l get the following error :
math.exp(preds[4,4])
TypeError: a... | Indexing a Variable object doesnt convert it into a scalar. Its still a Variable object. However indexing a numpy array does. So converting the Variable object into a numpy and then indexing the way you want it should do the trick.
But there are some small pitfalls when converting a Variable to numpy.
If preds is a Var... | https://stackoverflow.com/questions/45490215/ |
Regression loss functions incorrect | I'm trying a basic averaging example, but the validation and loss don't match and the network fails to converge if I increase the training time. I'm training a network with 2 hidden layers, each 500 units wide on three integers from the range [0,9] with a learning rate of 1e-1, Adam, batch size of 1, and dropout for 30... | It looks like you've misunderstood how layers in pytorch works, here are a few tips:
In your forward when you do nn.Linear(...) you are definining new layers instead of using those you pre-defined in your network __init__. Therefore, it cannot learn anything as weights are constantly reinitalized.
You shouldn't need ... | https://stackoverflow.com/questions/45490265/ |
Any pytorch tools to monitor neural network's training? | Are there any tools to monitor network's training in PyTorch? Like tensorboard in tensorflow.
| I am using tensorboardX. It supports most (if not all) of the features of TensorBoard. I am using the Scalar, Images, Distributions, Histograms and Text. I haven't tried the rest, like audio and graph, but the repo also contains examples for those use cases. The installation can be done easily with pip. It's all explai... | https://stackoverflow.com/questions/45519368/ |
Flatten layer of PyTorch build by sequential container | I am trying to build a cnn by sequential container of PyTorch, my problem is I cannot figure out how to flatten the layer.
main = nn.Sequential()
self._conv_block(main, 'conv_0', 3, 6, 5)
main.add_module('max_pool_0_2_2', nn.MaxPool2d(2,2))
self._conv_block(main, 'conv_1', 6, 16, 3)
main.add_module('max_pool_1_2_2', n... | This might not be exactly what you are looking for, but you can simply create your own nn.Module that flattens any input, which you can then add to the nn.Sequential() object:
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size()[0], -1)
The x.size()[0] will select the batch dim, and -1 ... | https://stackoverflow.com/questions/45584907/ |
Which deep learning library support the compression of the deep learning models to be used on the phones? | I want to build an advanced deep learning model (for example: a model that uses attention) and use it on android phones (without training of course) i will only use it for inference.
and i want a library that can do that and can compress the model size to be used on the phone or android.
and do you know any projects or... | There is a Caffe fork called Ristretto. It allows compressing neural nets for lower numerical precision (less than 32 bits per parameter), while keeping high accuracy. MXNet and Tensorflow also have this feature now. Pytorch doesn't have it yet.
These tools allow to reduce the memory required for storing the neural ne... | https://stackoverflow.com/questions/45605087/ |
KeyError when trying to modify pytorch-example | I'm trying to modify this pytorch-example (https://github.com/pytorch/examples/blob/master/mnist/main.py) to work with my own dataset.
I tried to feed my data into a dataloader. I encapsulated the data in two different ways: one time as an extension of torch.utils.data.Dataset and one time as torch.utils.data.TensorDa... | It seems that most operation are defined on FloatTensor and DoubleTensor (source), and your model gets a ByteTensor in model(data).
I would go ahead an make sure that my dataset object outputs FloatTensors. Debug the line before model(data) and see the tensor type of data. I would guess it's a ByteTensor, that would b... | https://stackoverflow.com/questions/45617017/ |
Axes don't match array error in pytorch | I was trying to run the vnet implementation in pytorch
(https://github.com/mattmacy/vnet.pytorch) and after normalising the scans with
x_max = 512
y_max = 512
z_max = 500
voxspacing = 0.7
when I call the tran function on the line where the for loop is enumerating through the data loader I get a
axes don't ... | comment the lines 417 and 418. the issue will get fixed
the issue is because of these 2 lines
if self.transform is not None:
img = self.transform(img)
| https://stackoverflow.com/questions/45618655/ |
Error importing PyTorch - Python | I have tried to install PyTorch using the following command in terminal:
pip install http://download.pytorch.org/whl/torch-0.2.0.post1-cp27-none-macosx_10_7_x86_64.whl
I then run the following code in python:
import torch
torch.__file__
and get the following error:
File "/Users/brian/anaconda/lib/python2.7/sit... | On http://pytorch.org/ With:
OS: OSX
Package Manager: pip
Python: 2.7
CUDA: None
I've got:
pip install http://download.pytorch.org/whl/torch-0.2.0.post1-cp27-none-macosx_10_7_x86_64.whl
pip install torchvision
# OSX Binaries dont support CUDA, install from source if CUDA is needed
Are you sure you select all ... | https://stackoverflow.com/questions/45673949/ |
PyTorch: How to get around the RuntimeError: in-place operations can be only used on variables that don't share storage with any other variables | With PyTorch I'm having a problem doing an operation with two Variables:
sub_patch : [torch.FloatTensor of size 9x9x32]
pred_patch : [torch.FloatTensor of size 5x5x32]
sub_patch is a Variable made by torch.zeros
pred_patch is a Variable of which I index each of the 25 nodes with a nested for-loop, and that I multi... | I've found the problem to be in
sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] += (sub_filt_patch * pred_patch[i,j]).sum(dim=3)
When separating this line into this:
sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] = sub_patch[i:(i + filter_sz), j:(j + filter_sz), :] + (sub_filt_patch * pred_patch[i,j... | https://stackoverflow.com/questions/45693586/ |
What is the first parameter (gradients) of the backward method, in pytorch? |
We have the following code from the pytorch documentation:
x = torch.randn(3)
x = Variable(x, requires_grad=True)
y = x * 2
while y.data.norm() < 1000:
y = y * 2
gradients = torch.FloatTensor([0.1, 1.0, 0.0001])
y.backward(gradients)
What exactly is the gradients parameter that we pass into the backward me... |
To fully answer your question, it'd require a somewhat longer explanation that evolves around the details of how Backprop or, more fundamentally, the chain rule works.
The short programmatic answer is that the backwards function of a Variable computes the gradient of all variables in the computation graph attached t... | https://stackoverflow.com/questions/45837547/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.