prompt
stringlengths
15
2.05k
response
stringlengths
0
2.05k
extracting the top-k value-indices from a 1-d tensor
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...
how to display custom images in tensorboard (e.g. matplotlib plots)?
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...
python wheels: cp27mu not supported
this is exactly that. recompile python under slack with --enable-unicode=ucs4 and you can then install the whl.
loading torch7 trained models (.t7) in pytorch
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 ...
pytorch: how to use dataloaders for custom datasets
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...
what does .view() do in pytorch?
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...
how do i print the model summary in pytorch?
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...
how do i save a trained model in pytorch?
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...
l1/l2 regularization in pytorch
see the documentation. add a weight_decay parameter to the optimizer for l2 regularization.
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.
what is the difference between view() and unsqueeze() in torch?
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...
why tensor.view() is not working in pytorch?
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 ...
how to convert a list or numpy array to a 1d torch tensor?
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)
attributeerror: module 'torch' has no attribute 'cmul'
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.
performing convolution (not cross-correlation) in pytorch
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...
attributeerror: cannot assign module before module.__init__() call
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...
how to count the amount of layers in a cnn?
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...
ide autocomplete for pytorch
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...
pytorch reshape tensor dimension
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]
pytorch, what are the gradient arguments
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...
error when compiling pytorch: 'cstdint' file not found
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
how to use the bceloss in pytorch?
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 ...
pytorch network.parameters() missing 1 required positional argument: 'self'
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...
pytorch, typeerror: object() takes no parameters
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...
how to run pytorch 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...
fixing a subset of weights in neural network during training
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...
accuracy score in pytorch lstm
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...
can i slice tensors with logical indexing or lists of indices?
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
pytorch: how to convert pretrained fc layers in a cnn to conv layers
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...
how does the pytorch autograd work?
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...
convolutional nn for text input in pytorch
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...
overflowerror: (34, 'numerical result out of range') in pytorch
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']...
keyerror: 'unexpected key "module.encoder.embedding.weight" in state_dict'
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...
backward, grad function in pytorch
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...
why should be the function backward be called only on 1 element tensor or with gradients w.r.t to variable?
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 ...
pytorch: access weights of a specific module in nn.sequential()
from the pytorch forum, this is the recommended way: model_2.layer[0].weight
deep learning: save and load a universal machine model through different libraries
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 ...
how to get a uniform distribution in a 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...
how can i install python modules in a docker image?
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...
how to convert pytorch autograd.variable to numpy?
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 ...
pytorch linear layer input dimension mismatch
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)
what is the relationship between pytorch and 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 ...
handling c++ arrays in cython (with numpy and pytorch)
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...
implementing adagrad in python
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...
pytorch custom layer "is not a module subclass"
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...
when is a pytorch custom function needed (rather than only a module)?
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...
how to load a list of numpy arrays to pytorch dataset loader?
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...
creating one hot vector from indices given as a tensor
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...
tensor division in pytorch. assertion error
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()
how do i multiply matrices in pytorch?
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...
python child process exit unexpectedly with exit code -9
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...
cuda vs. dataparallel: why the difference?
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
custom loss function in pytorch
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...
is torch7 defined-by-run like pytorch?
no, torch7 use static computational graphs, as in tensorflow. it is one of the major differences between pytorch and torch7.
subtraction of scalar from tensor yields 'inconsistent tensor size' in pytorch
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...
convert 'int' to pytorch 'variable' makes problems
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...
pytorch: how to add l1 regularizer to activations?
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...
how do you implement variable-length recurrent neural networks?
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 ...
how do you use pytorch packedsequence in code?
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...
pytorch: convert floattensor into doubletensor
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 ...
why do we need to explicitly call zero_grad()?
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...
pytorch: extract learned weights correctly
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
re-weight the input to a neural network
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 = ...
torch sum a tensor along an axis
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...
apply json config file using parse_args() in pycharm
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...
how to append a singleton numpy array item into a list?
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)
no n-dimensional tranpose in pytorch
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...
how to debug(monitoring value of object in other class' function) in pycharm
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...
how do you alter the size of a pytorch dataset?
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 ...
find number of non-zero elements in a tensor along an aixs
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.
pytorch - element-wise multiplication between a variable and a tensor?
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_...
pytorch nn.functional.batch_norm for 2d input
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...
requires_grad relation to leaf nodes
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 ...
how two rows can be swapped in a torch tensor?
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],...
how padded sequences given as packed sequences are dealt by rnn in pytorch?
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)...
backpropagation without updating weights (dcgan)
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...
why does an attribute has a method?
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
why rnn need two bias vectors?
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)
include .whl installation in requirements.txt
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...
understanding a simple lstm pytorch
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...
how to simplify dataloader for autoencoder in pytorch
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 ...
indexing second dimension of tensor using indices
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 ...
pytorch runtimeerror : gradients are not cuda tensors
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...
is torchvision.datasets.cifar.cifar10 a list or not?
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 ...
is there a way to use an external loss function in pytorch?
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...
numpy/pytorch method for partial tiling
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...
pytorch: how to directly find gradient w.r.t. loss
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...
running conv2d on tensor [batch, channel, sequence, h,w] in pytorch
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: ...
replace all nonzero values by zero and all zero values by a specific value
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...
tensor type mismatch when moving to gpu
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 ...
typeerror: a float is required
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...
regression loss functions incorrect
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 ...
any pytorch tools to monitor neural network's training?
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...
flatten layer of pytorch build by sequential container
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 ...
which deep learning library support the compression of the deep learning models to be used on the phones?
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...
keyerror when trying to modify pytorch-example
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...
axes don't match array error in pytorch
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)
error importing pytorch - python
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 ...
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
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...
what is the first parameter (gradients) of the backward method, in pytorch?
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...