instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
nn.Linear should be mismatch, but it works successfully
I'm confused about the in-feature of nn.linear. For out-feature of the model VGG-19's last nn.MaxPool2d, the tensor size is (512, 7, 7). The model below uses pooling function and resizes the tensor to (512, 49), then uses nn.linear(512, 7) directly. Why can't it work successfully without mismatch problem? source '''...
Why is the assumption that this code works? I tested it, and got the following shapes, and the expected size mismatch error. def forward(self, x): out = self.features(x) # torch.Size([1, 512, 7, 7]) out = out.view(out.size(0), -1) # torch.Size([1, 25088]) out = F.dropout(out, p=0.5, training=self.training...
https://stackoverflow.com/questions/55462619/
Why does multi-class classification fails with sigmoid?
MNIST trained with Sigmoid fails while Softmax works fine I am trying to investigate how different activation affects the final results, so I implemented a simple net for MNIST with PyTorch. I am using NLLLoss (Negative log likelihood) as it implements Cross Entropy Loss when used with softmax. When I have softmax a...
Sigmoid + crossentropy can be used for multilabel classification (assume a picture with a dog and a cat, you want the model to return "dog and cat"). It works when the classes aren't mutually exclusive or the samples contain more than one object that you want to recognize. In your case MNIST has mutually exclusive cla...
https://stackoverflow.com/questions/55463251/
Applying Kullback-Leibler (aka kl divergence) element-wise in Pytorch
I have two tensors named x_t, x_k with follwing shapes NxHxW and KxNxHxW respectively, where K, is the number of autoencoders used to reconstruct x_t (if you have no idea what is this, assume they're K different nets aiming to predict x_t, this probably has nothing to do with the question anyways) N is batch size, H ma...
It's unclear to me what exactly constitutes a probability distribution in your model. With reduction='none', kl_div, given log(x_n) and y_n, computes kl_div = y_n * (log(y_n) - log(x_n)), which is the "summed" part of the actual Kullback-Leibler divergence. Summation (or, in other words, taking the expectation) is up t...
https://stackoverflow.com/questions/55466270/
Pytorch: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead
Calling tensor.numpy() gives the error: RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead. tensor.cpu().detach().numpy() gives the same error.
 Error reproduced import torch tensor1 = torch.tensor([1.0,2.0],requires_grad=True) print(tensor1) print(type(tensor1)) tensor1 = tensor1.numpy() print(tensor1) print(type(tensor1)) which leads to the exact same error for the line tensor1 = tensor1.numpy(): tensor([1., 2.], requires_grad=True) <class 'torch.Ten...
https://stackoverflow.com/questions/55466298/
How can I reduce a tensor's last dimension in PyTorch?
I have tensor of shape (1, 3, 256, 256, 3). I need to reduce one of the dimensions to obtain the shape (1, 3, 256, 256). How can I do it? Thanks!
If you intend to apply mean over the last dimension, then you can do so with: In [18]: t = torch.randn((1, 3, 256, 256, 3)) In [19]: t.shape Out[19]: torch.Size([1, 3, 256, 256, 3]) # apply mean over the last dimension In [23]: t_reduced = torch.mean(t, -1) In [24]: t_reduced.shape Out[24]: torch.Size([1, 3, 256, 2...
https://stackoverflow.com/questions/55471260/
Code conversion from python 2 to python 3
I'm setting up a new algorithm which combines an object detector(bounding box detector) which is in python 3 and a mask generator which is in python 2. The problem here is I have several python 2 files which is required for the mask generation algorithm. So I tried 2to3 to convert all my python 2 files to python 3. The...
I just resolved the issue by re-installing the torch(0.4.0) and torchvision(0.2.1) for my conda environment. I had to downgrade the versions of both of them. Finally I was successful in converting my python 2.7 code to python 3. Thanks to 2to3 library. Actually this error was happening in the image normalize function o...
https://stackoverflow.com/questions/55471459/
Error libtorch_python.so: cannot open shared object file: No such file or directory
I'm trying to implement fastai pretrain language model and it requires torch to work. After run the code, I got some problem about the import torch._C I run it on my linux, python 3.7.1, via pip: torch 1.0.1.post2, cuda V7.5.17. I'm getting this error: Traceback (most recent call last): File "pretrain_lm.py", line...
My problem is solved. I'm uninstalling my torch twice pip uninstall torch pip uninstall torch and then re-installing it back: pip install torch==1.0.1.post2
https://stackoverflow.com/questions/55476131/
Matrix-vector multiplication for only one dimension in a tensor
Is it possible to multiply only one (last) dimension in a tensor alone with other vectors? For example, assume a tensor T=[100, 20, 400] and a matrix M =[400, 400]. Is it possible to make the operation h_{transpose}*M*h, where h is the last dimension in the tensor T? In other words, is it possible to make use of (pos...
I think the easiest (certainly the shortest) solution is with einsum. import torch T = torch.randn(100, 20, 400) M = torch.randn(400, 400) res = torch.einsum('abc,cd,abd->ab', (T, M, T)).unsqueeze(-1) It basically says "for all (a, b, c, d) in bounds, multiply T[a, b, c] with M[c, d] and T[a, b, d] and accumula...
https://stackoverflow.com/questions/55476990/
Regarding number of epochs for torchvision models
I was trying to find, how many epochs was the pretrained Alexnet model (available from torchvision) trained for on Imagenet and also what learning rate was used? I tried checking the checkpoint keys to see if any epoch info was stored. Any suggestions on how to find it out?
According to this comment on GitHub by a PyTorch team member, most of the training was done with a variant of https://github.com/pytorch/examples/tree/master/imagenet. All the models were trained on Imagenet. According to the file: The default learning rate schedule starts at 0.1 and decays by a factor of 10 every 3...
https://stackoverflow.com/questions/55476998/
Pytorch - add rows of a 2D tensor element-wise
I have the following tensor : ts = torch.tensor([[1,2,3],[4,6,7],[8,9,10]]) > tensor([[ 1, 2, 3], [ 4, 6, 7], [ 8, 9, 10]]) I am looking for a pytorch generic operation that adds all rows element-wise like that: ts2 = ts[0]+ts[1]+ts[2] print(ts2) > tensor([13, 17, 20]) In reality, the number of...
You can sum over an axis/dimension like so: torch.sum(ts, dim=0)
https://stackoverflow.com/questions/55500527/
Pytorch loss function error in the last batch
Assume that I have 77 samples to train my CNN, and my batch size is 10. Then the last batch has a batch size of 7 instead of 10. Somehow when I pass it to the loss function such as nn.MSELoss(), it gives me the error: RuntimeError: The size of tensor a (10) must match the size of tensor b (7) at non-singleton dim...
The problem is not due to the batch size, but to a failure to broadcast properly between the 10 outputs of your CNN and the single label provided in each example. If you look at the model output and label tensor shapes during the batch where the error is thrown, print(outputs.shape, labels.shape) #out: torch.Size([7,...
https://stackoverflow.com/questions/55507391/
how to load the gpu trained model into the cpu?
I am using PyTorch. I am going to use the already trained model on multiple GPUs with CPU. how to do this task? I tried on Anaconda 3 and pytorch with cpu only i dont have gpu model = models.get_pose_net(config, is_train=False) gpus = [int(i) for i in config.GPUS.split(',')] model = torch.nn.DataParallel(model, dev...
To force load the saved model onto cpu, use the following command. torch.load('/path/to/saved/model', map_location='cpu') In your case change it to torch.load(config.MODEL.RESUME, map_location='cpu')
https://stackoverflow.com/questions/55511857/
How to dynamically index the tensor in pytorch?
For example, I got a tensor: tensor = torch.rand(12, 512, 768) And I got an index list, say it is: [0,2,3,400,5,32,7,8,321,107,100,511] I wish to select 1 element out of 512 elements on dimension 2 given the index list. And then the tensor's size would become (12, 1, 768). Is there a way to do it?
There is also a way just using PyTorch and avoiding the loop using indexing and torch.split: tensor = torch.rand(12, 512, 768) # create tensor with idx idx_list = [0,2,3,400,5,32,7,8,321,107,100,511] # convert list to tensor idx_tensor = torch.tensor(idx_list) # indexing and splitting list_of_tensors = tensor[:, i...
https://stackoverflow.com/questions/55529236/
Cannot Obtain Similar DL Prediction Result in Pytorch C++ API Compared to Python
I have trained a deep learning model using unet architecture in order to segment the nuclei in python and pytorch. I would like to load this pretrained model and make prediction in C++. For this reason, I obtained trace file(with pt extension). Then, I have run this code: #include <iostream> #include <torch/...
Even though the question is old it might be useful to some. This answer is based on pytorch 1.5.0 release (and first stable version of C++ frontend), the case might be a little different in previous versions (though 1.4.0+ would work the same IIRC). PyTorch C++ frontend code no need to explicitly create torch::Tenso...
https://stackoverflow.com/questions/55531432/
Understanding Gradient in Pytorch
I have some Pytorch code which demonstrates the gradient calculation within Pytorch, but I am thoroughly confused what got calculated and how it is used. This post here demonstrates the usage of it, but it does not make sense to me in terms of the back propagation algorithm. Looking at the gradient of in1 and in2 in th...
Backpropagation is based on the chain-rule for calculating derivatives. This means the gradients are computed step-by-step from tail to head and always passed back to the previous step ("previous" w.r.t. to the preceding forward pass). For scalar output the process is initiated by assuming a gradient of d (out1) / d (...
https://stackoverflow.com/questions/55543786/
How do I flatten a tensor in pytorch?
Given a tensor of multiple dimensions, how do I flatten it so that it has a single dimension? torch.Size([2, 3, 5]) ⟶ flatten ⟶ torch.Size([30])
TL;DR: torch.flatten() Use torch.flatten() which was introduced in v0.4.1 and documented in v1.0rc1: >>> t = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) >>> torch.flatten(t) tensor([1, 2, 3, 4, 5, 6, 7, 8]) >>> torc...
https://stackoverflow.com/questions/55546873/
4d Input Tensor vs 1d Input Tensor (aka vector) to a neural network
Reading about machine learning, I keep seeing references to the "input vector" or "feature vector", a 1d tensor that holds the input to the neural network. So for example a 28x28 grayscale image would be a 784 dimensional vector. Then I also keep seeing references to images being a 4 dimensional tensor with the dimens...
There are two main considerations. First is due to batching. Since we usually want to perform each optimization step based on gradient calculation for a number of training examples (and not just one), it is helpful to run the calculations for all of them at once. Therefore standard approach in many libraries is that t...
https://stackoverflow.com/questions/55547943/
Pytorch doesn't support one-hot vector?
I am very confused by how Pytorch deals with one-hot vectors. In this tutorial, the neural network will generate a one-hot vector as its output. As far as I understand, the schematic structure of the neural network in the tutorial should be like: However, the labels are not in one-hot vector format. I get the follow...
PyTorch states in its documentation for CrossEntropyLoss that This criterion expects a class index (0 to C-1) as the target for each value of a 1D tensor of size minibatch In other words, it has your to_one_hot_vector function conceptually built in CEL and does not expose the one-hot API. Notice that one-hot vectors ...
https://stackoverflow.com/questions/55549843/
Dict[str, Any] or Dict[str, Field] in pytext
I'm reading the document of pytext (NLP modeling framework built on PyTorch) and this simple method from_config, a factory method to create a component from a config, has lines like Dict[str, Field] = {ExtraField.TOKEN_RANGE: RawField()}. @classmethod def from_config(cls, config: Config, model_input_config, target_con...
What you're seeing are python type annotations. You can read about the syntax, design and rationale here and about the actual implementation (possible types, how to construct custom ones, etc) here. Note that here List and Dict are upper cased - Dict[str, Any] is meant to construct the type "a dictionary with string ke...
https://stackoverflow.com/questions/55556562/
How to import Python package (Pytorch-neat) that is not installable from pip/conda repositories?
I am trying to used Pytorch-neat package https://github.com/uber-research/PyTorch-NEAT but I don't understand the workflow of using it. I already installed python-neat package and I can import it using import neat in my Jupyter notebook. But what should I do with Pytroch-neat code? There is no pytorch-neat package in C...
To import from pytorch_neat you have to clone the repository and manually copy directory pytorch_neat into your site-packages (or any directory in sys.path).
https://stackoverflow.com/questions/55563322/
Pytorch. How does pin_memory work in Dataloader?
I want to understand how pin_memory in Dataloader works. According to the documentation: pin_memory (bool, optional) – If True, the data loader will copy tensors into CUDA pinned memory before returning them. Below is a self-contained code example. import torchvision import torch print('torch.cuda.is_available()', to...
The documentation is perhaps overly laconic, given that the terms used are fairly niche. In CUDA terms, pinned memory does not mean GPU memory but non-paged CPU memory. The benefits and rationale are provided here, but the gist of it is that this flag allows the x.cuda() operation (which you still have to execute as us...
https://stackoverflow.com/questions/55563376/
how to avoid split and sum of pieces in pytorch or numpy
I want to split a long vector into smaller unequal pieces, do a summation on each piece and gather the results into a new vector. I need to do this in pytorch but I am also interested to see how this is done with numpy. This can easily be accomplish by splitting the vector. sizes = [3, 7, 5, 9] X = torch.ones(sum(sizes...
index_add_ is your friend! # inputs sizes = torch.tensor([3, 7, 5, 9], dtype=torch.long) x = torch.ones(sizes.sum()) # prepare an index vector for summation (what elements of x are summed to each element of y) ind = torch.zeros(sizes.sum(), dtype=torch.long) ind[torch.cumsum(sizes, dim=0)[:-1]] = 1 ind = torch.cumsum(...
https://stackoverflow.com/questions/55567838/
1D correlation between 2 matrices
I want to find 1D correlation between two matrices. These two matrices are the output of a convolution operation on two different images. Let's call the first matrix as matrix A and the other one as matrix B. Both these matrices have the shape 100 x 100 x 64 (say). I've been following a research paper which basically ...
So they basically have 1 original image, which they treat as the left side view for the depth perception algorithm, but since you need stereo vision to calculate depth in a still image they use a neural structure to synthesise a right side view. 1 Dimensional Correlation takes 2 sequences and calculates the correlatio...
https://stackoverflow.com/questions/55574457/
Conv1D with kernel_size=1 vs Linear layer
I'm working on very sparse vectors as input. I started working with simple Linear (dense/fully connected layers) and my network yielded pretty good results (let's take accuracy as my metric here, 95.8%). I later tried to use a Conv1d with a kernel_size=1 and a MaxPool1d, and this network works slightly better (96.4% ac...
nn.Conv1d with a kernel size of 1 and nn.Linear give essentially the same results. The only differences are the initialization procedure and how the operations are applied (which has some effect on the speed). Note that using a linear layer should be faster as it is implemented as a simple matrix multiplication (+ addi...
https://stackoverflow.com/questions/55576314/
torch.nn.sequential vs. combination of multiple torch.nn.linear
I'm trying to create a multi layer neural net class in pytorch. I want to know if the following 2 pieces of code create the same network. Model 1 with nn.Linear class TestModel(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(TestModel, self).__init__() self.fc1 = nn.Linear(input_dim,...
Yes, these two pieces of code create the same network. One way to convince yourself that this is true is to save both models to ONNX. import torch.nn as nn class TestModel(nn.Module): def __init__(self, input_dim, hidden_dim, output_dim): super(TestModel, self).__init__() self.fc1 = nn.Linear(inpu...
https://stackoverflow.com/questions/55584747/
How do I update a tensor in Pytorch after indexing twice?
I know how to update a tensor after indexing into part of it like this: import torch b = torch.tensor([0, 1, 0, 1], dtype=torch.uint8) b[b] = 2 b # tensor([0, 2, 0, 2], dtype=torch.uint8) but is there a way I can update the original tensor after indexing into it twice? E.g. i = 1 b = torch.tensor([0, 1, 0, 1], dty...
I adopted another solution from here, and compared it to your solution: Solution: b[b.nonzero()[i]] = 2 Runtime comparison: import torch as t import numpy as np import timeit if __name__ == "__main__": np.random.seed(12345) b = t.tensor(np.random.randint(0,2, [1000]), dtype=t.uint8) # inconvenient w...
https://stackoverflow.com/questions/55584779/
PyTorch transforms on TensorDataset
I'm using TensorDataset to create dataset from numpy arrays. # convert numpy arrays to pytorch tensors X_train = torch.stack([torch.from_numpy(np.array(i)) for i in X_train]) y_train = torch.stack([torch.from_numpy(np.array(i)) for i in y_train]) # reshape into [C, H, W] X_train = X_train.reshape((-1, 1, 28, 28)).flo...
By default transforms are not supported for TensorDataset. But we can create our custom class to add that option. But, as I already mentioned, most of transforms are developed for PIL.Image. But anyway here is very simple MNIST example with very dummy transforms. csv file with MNIST here. Code: import numpy as np im...
https://stackoverflow.com/questions/55588201/
Fixed Gabor Filter Convolutional Neural Networks
I'm trying to build a CNN with some conv layers where half of the filters in the layer are fixed and the other half is learnable while training the model. But I didn't find anything about that. what I'm trying to do is similar to what they did in this paper https://arxiv.org/pdf/1705.04748.pdf Is there a way to do th...
Sure. In PyTorch you can use nn.Conv2d and set its weight parameter manually to your desired filters exclude these weights from learning A simple example would be: import torch import torch.nn as nn class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv_learning =...
https://stackoverflow.com/questions/55592324/
nvcc and clang are not working well together when installing pytorch-gpu
I am trying to install pytorch with gpu support on my MacBook Pro following official instructions. Things go smoothly until an error occurred: [ 70%] Building NVCC (Device) object caffe2/CMakeFiles/caffe2_gpu.dir/__/aten/src/THC/caffe2_gpu_generated_THCTensorMath.cu.o nvcc fatal : The version ('90000') of the host ...
I am answering my own question. Incorrect CUDA installation on macOS could be a nightmare. The versions of CUDA, Xcode, clang and macOS really matter. Here are some of the official tested ones: +------+--------------+------------+---------------------------------+--------+ | CUDA | Xcode | Apple LLVM | Mac OS...
https://stackoverflow.com/questions/55594309/
How to visualise filters in a CNN with PyTorch
I'm new to deep learning and Pytorch. I want to visual my filter in my CNN model so that I can iterate layer in the CNN model that I define. But I meet error like below. error: 'CNN' object is not iterable The CNN object is my model. My iteration code is like below: for index, layer in enumerate(self.model): ...
Essentially, you will need to access the features in your model and transpose those matrices into the right shape first, then you can visualise the filters import numpy as np import matplotlib.pyplot as plt from torchvision import utils def visTensor(tensor, ch=0, allkernels=False, nrow=8, padding=1):...
https://stackoverflow.com/questions/55594969/
How to do numerical integration with pytorch similar to numpy's trapz function?
Title says it all. Is there a convenient function in pytorch that can do something like np.trapz(y, x) (integrating over the the points in x and y via trapezoidal rule)?
There is no built-in tool for that, but it should not be difficult to implement it yourself, especially using the numpy code as a guideline.
https://stackoverflow.com/questions/55605577/
Why is the derivative of f(x) with respect to 'x' 'x' and not 1 in pytorch?
I am trying to understand pytorch's autograd in full and I stumbled with this: let f(x)=x, from basic maths we know that f'(x)=1, however when I do that exercise in pytorch I get that f'(x) = x. z = torch.linspace(-1, 1, steps=5, requires_grad=True) y = z y.backward(z) print("Z tensor is: {} \n Gradient of y with resp...
First of all, given z = torch.linspace(-1, 1, steps=5, requires_grad=True) and y = z, the function is a vector-valued function, so the derivative of y w.r.t z is not as simple as 1 but a Jacobian matrix. Actually in your case z = [z1, z2, z3, z4, z5]T , the upper case T means z is a row vector. Here is what the officia...
https://stackoverflow.com/questions/55613439/
Why isn't there inplace flag in F.sigmoid in pytorch?
Both relu, leakyrelu have inplace flag, so why not sigmoid? Signature: F.sigmoid(input) F.relu(input, inplace=False)
According to docs: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead. If you need in-place version, use sigmoid_: import torch torch.manual_seed(0) a = torch.randn(5) print(a) a.sigmoid_() print(a) tensor([ 1.5410, -0.2934, -2.1788, 0.5684, -1.0845]) tensor([0.8236, 0.4272, 0.1017, 0.6384, 0.2527])...
https://stackoverflow.com/questions/55615813/
Why is torch.nn.Sigmoid a class instead of a method?
I'm trying to understand how pytorch works a little bit better. Usually, when defining a neural network class, in the init() constructor, people write self.sigmoid = nn.Sigmoid(), so that in the forward() method they can call the sigmoid function multiple times with having to reinstantiate nn.Sigmoid() every time. But...
My understanding is that the nn.Sigmoid exists to be composable with other nn layers, like this: net = nn.Sequential( nn.Linear(3, 4), nn.Sigmoid()) If you don't need this, you can just use torch.sigmoid function.
https://stackoverflow.com/questions/55621322/
Evaluating pytorch models: `with torch.no_grad` vs `model.eval()`
When I want to evaluate the performance of my model on the validation set, is it preferred to use with torch.no_grad: or model.eval()?
TL;DR: Use both. They do different things, and have different scopes. with torch.no_grad - disables tracking of gradients in autograd. model.eval() changes the forward() behaviour of the module it is called upon eg, it disables dropout and has batch norm use the entire population statistics with torch.no_grad The to...
https://stackoverflow.com/questions/55627780/
Indexing a 3d tensor using a 2d tensor
I have a 3d tensor, source of shape (bsz x slen1 x nhd) and a 2d tensor, index of shape (bsz x slen2). More specifically, I have: source = 32 x 20 x 768 index = 32 x 16 Each value in the index tensor is in between [0, 19] which is the index of the desired vector according to the 2nd dim of the source tensor. After...
Update: source[torch.arange(source.shape[0]).unsqueeze(-1), index] Note that torch.arange(source.shape[0]).unsqueeze(-1) gives: tensor([[0], [1]]) # 2 x 1 and index is: tensor([[0, 1, 2, 3], [1, 2, 3, 4]]) # 2 x 4 The arange indexes the batch dimension while index simultaneously indexes the ...
https://stackoverflow.com/questions/55628014/
Shape of tensor
I came across this piece of code (x_train, y_train), (x_test, y_test) = mnist.load_data() print("Shape of x_train: " + str(x_train.shape)) print("Shape of y_train: " + str(y_train.shape)) And found that the output looks like this (60000, 28, 28) (60000,) For the first line of output So far my understanding, does i...
You are right the first line gives 60K items of 28x28 size data thus (60000, 28, 28). The y_train are labels of the x_train. Thus they are a one dimensional and 60k in number. For example: If the first item of the x_train is a handwritten image of 3, then the first item of y_train will be '3' which is the label.
https://stackoverflow.com/questions/55629163/
Issues converting Keras code into PyTorch code (shaping)
I have some keras code that I need to convert to Pytorch. I am new to pytorch and I am having trouble wrapping my head around how to take in input the same way that I did in keras. I have spent many hours on this any tips or help is very appreciated. Here is the keras code I am dealing with. The input shape is (5000,...
I think your fundamental problem is that you confuse in_channels and out_channels with Keras shapes. Let's just take the first convolutional layer as an example. In Keras you have: Conv1D(filters=32, kernel_size=8, input_shape=(5000,1), strides=1, padding='same') The PyTorch equivalent should be (changing the kernel...
https://stackoverflow.com/questions/55636138/
Preventing PyTorch Dataset iteration from exceeding length of dataset
I am using a custom PyTorch Dataset with the following: class ImageDataset(Dataset): def __init__(self, input_dir, input_num, input_format, transform=None): self.input_num = input_num # etc def __len__ (self): return self.input_num def __getitem__(self,idx): targetnum = idx ...
Dataset class doesn't have implemented StopIteration signal. The for loop listens for StopIteration. The purpose of the for statement is to loop over the sequence provided by an iterator and the exception is used to signal that the iterator is now done... More: Why does next raise a 'StopIteration', but 'for' do ...
https://stackoverflow.com/questions/55637271/
Cuda Runtime/Driver incompatibility in docker container
I'm trying to run this simple line of code in a docker container that comes with Pytorch. import torch torch.cuda.set_device(0) I get this error: RuntimeError: cuda runtime error (35) : CUDA driver version is insufficient for CUDA runtime version at torch/csrc/cuda/Module.cpp:32 Running torch.cuda.is_available() ...
The problem was that I was running the container with docker, not nvidia-docker. Running the docker container with nvidia-docker fixed the problem.
https://stackoverflow.com/questions/55641418/
Compute Optical Flow corresponding to data in the torch.utils.data.DataLoader
I have built a CNN model for action recognition in videos in PyTorch. I'm loading the data for training using the torch dataloader module. train_loader = torch.utils.data.DataLoader( training_data, batch_size=8, shuffle=True, num_workers=4, pin_memory=True) ...
You have to use an own data loader class to compute optical flow on the fly. The idea is that this class get a list of filename tuples (curr image, next image) containing the current and next frame filenames of the video sequence instead of simple filename list. This allows to get the correct image pairs after suffling...
https://stackoverflow.com/questions/55651427/
How to iterate over a group of tensor and pass the elements from each group to a function?
Suppose you have 3 tensors of the same size: a = torch.randn(3,3) a = ([[ 0.1945, 0.8583, 2.6479], [-0.1000, 1.2136, -0.3706], [-0.0094, 0.4279, -0.6840]]) b = torch.randn(3, 3) b = ([[-1.1155, 0.2106, -0.2183], [ 1.6610, -0.6953, 0.0052], [-0.8955, 0.0953, -0.7737]])...
You can use Python's map function similar to what you have mentioned. Like this: >>> tensor_list = [torch.tensor([i, i, i]) for i in range(3)] >>> list(map(lambda x: x**2, tensor_list)) [tensor([0, 0, 0]), tensor([1, 1, 1]), tensor([4, 4, 4])] >>> EDIT: For a PyTorch only approach you can...
https://stackoverflow.com/questions/55652321/
Keras learning rate decay in pytorch
I have a question concerning learning rate decay in Keras. I need to understand how the option decay works inside optimizers in order to translate it to an equivalent PyTorch formulation. From the source code of SGD I see that the update is done this way after every batch update: lr = self.lr * (1. / (1. + self.decay...
Based on the implementation in Keras I think your first formulation is the correct one, the one that contain the initial learning rate (note that self.lr is not being updated). However I think your calculation is probably not correct: since the denominator is the same, and lr_0 >= lr since you are doing decay, the fir...
https://stackoverflow.com/questions/55663375/
I change the expected object of scalar type float but still got Long in Pytorch
To do the binary class classification. I use binary cross entropy to be the loss function(nn.BCEloss()), and the units of last layer is one. Before I put (input, target) into loss function, I cast target from Long to float. Only the final step of the DataLoader comes the error messages, and the error message is as be...
It appears that the type is correctly being changed, as you state that you observe the change when printing the types and from Pytorch: Returns a Tensor with the specified device and (optional) dtype. If dtype is None it is inferred to be self.dtype. When non_blocking, tries to convert asynchronously with respect to t...
https://stackoverflow.com/questions/55665689/
What's the fastest way to copy values from one tensor to another in PyTorch?
I am experimenting with dilation in convolution where I am trying to copy data from one 2D tensor to another 2D tensor using PyTorch. I'm copying values from tensor A to tensor B such that every element of A that is copied into B is surrounded by n zeros. I have already tried using nested for loops, which is a very n...
If I understand your question correctly, here is a faster alternative, without any loops: # sample `n` In [108]: n = 2 # sample tensor to work with In [102]: A = torch.arange(start=1, end=5*4 + 1).view(5, -1) In [103]: A Out[103]: tensor([[ 1, 2, 3, 4], [ 5, 6, 7, 8], [ 9, 10, 11, 12], ...
https://stackoverflow.com/questions/55669625/
Why is an OOM happening on my model init()?
A single line in my model, tr.nn.Linear(hw_flat * num_filters*8, num_fc), is causing an OOM error on initialization of the model. Commenting it out removes the memory issue. import torch as tr from layers import Conv2dSame, Flatten class Discriminator(tr.nn.Module): def __init__(self, cfg): super(Discrimi...
Your linear layer is quite large - it does, in fact, need at least 18GB of memory. (Your estimate is off for two reasons: (1) a float32 takes 4 bytes of memory, not 32, and (2) you didn't multiply by the output size.) From the PyTorch documentation FAQs: Don’t use linear layers that are too large. A linear layer n...
https://stackoverflow.com/questions/55670244/
Loss is 'nan' all the time when training the neural network in PyTorch
I assigned different weight_decayfor the parameters, and the training loss and testing loss were all nan. I printed the prediction_train,loss_train,running_loss_train,prediction_test,loss_test,and running_loss_test ,they were all nan. And I have checked the data with numpy.any(numpy.isnan(dataset)), it returned Fals...
Weight decay applies L2 regularization to the learned parameters, taking a quick glance at your code, you are using the a1 weights as denomenators here x=(x-self.b1)/self.a1 with a weight decay of .01, this could lead to eliminating some of those a1 weights to be zero, and what are the results of a division by zero ?
https://stackoverflow.com/questions/55671735/
Adam optimizer error: one of the variables needed for gradient computation has been modified by an inplace operation
I am trying to implement Actor-Critic learning atuomation algorithm that is not same as basic actor-critic algorithm, it's little bit changed. Anyway, I used Adam optimizer and implemented with pytorch when i backward TD-error for Critic first, there's no error. However, i backward loss for Actor, the error occured. ...
I think the problem is that you zero the gradients right before calling backward, after the forward propagation. Note that for automatic differentiation you need the computation graph and the intermediate results that you produce during your forward pass. So zero the gradients before your TD error and target calculati...
https://stackoverflow.com/questions/55673412/
Should I use softmax as output when using cross entropy loss in pytorch?
I have a problem with classifying fully connected deep neural net with 2 hidden layers for MNIST dataset in pytorch. I want to use tanh as activations in both hidden layers, but in the end, I should use softmax. For the loss, I am choosing nn.CrossEntropyLoss() in PyTOrch, which (as I have found out) does not want to t...
As stated in the torch.nn.CrossEntropyLoss() doc: This criterion combines nn.LogSoftmax() and nn.NLLLoss() in one single class. Therefore, you should not use softmax before.
https://stackoverflow.com/questions/55675345/
Label Smoothing in PyTorch
I'm building a ResNet-18 classification model for the Stanford Cars dataset using transfer learning. I would like to implement label smoothing to penalize overconfident predictions and improve generalization. TensorFlow has a simple keyword argument in CrossEntropyLoss. Has anyone built a similar function for PyTorch t...
The generalization and learning speed of a multi-class neural network can often be significantly improved by using soft targets that are a weighted average of the hard targets and the uniform distribution over labels. Smoothing the labels in this way prevents the network from becoming over-confident and label smoothing...
https://stackoverflow.com/questions/55681502/
How downsample work in ResNet in pytorch code?
In this pytorch ResNet code example they define downsample as variable in line 44. and line 58 use it as function. How this downsample work here as CNN point of view and as python Code point of view. code example : pytorch ResNet i searched for if downsample is any pytorch inbuilt function. but it is not. class Basi...
In this ResNet example, Here when we define BasicBlock class we pass downsample as constructor parameter. def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, norm_layer=None): if we pass nothing to class then downsample = None , as result identity will not changed. When we pass downsample = "s...
https://stackoverflow.com/questions/55688645/
Why does dim=1 return row indices in torch.argmax?
I am working on argmax function of PyTorch which is defined as: torch.argmax(input, dim=None, keepdim=False) Consider an example a = torch.randn(4, 4) print(a) print(torch.argmax(a, dim=1)) Here when I use dim=1 instead of searching column vectors, the function searches for row vectors as shown below. print(a) ...
It's time to correctly understand how the axis or dim argument work in PyTorch: The following example should make sense once you comprehend the above picture: | v dim-0 ---> -----> dim-1 ------> -----> --------> dim-1 | [[-1.7739, 0.8073, 0.0472, -0.4084], v [ 0.6378, 0....
https://stackoverflow.com/questions/55691819/
How to create a Pytorch Dataset from .pt files?
I have transformed MNIST images saved as .pt files in a folder in Google drive. I'm writing my Pytorch code in Colab. I would like to use these files, and create a Dataset that stores these images as Tensors. How can I do this? Transforming images during training took too long. Hence, transformed them and saved them...
The approach you are following to save images is indeed a good idea. In such a case, you can simply write your own Dataset class to load the images. from torch.utils.data import Dataset, DataLoader from torch.utils.data.sampler import RandomSampler class ReaderDataset(Dataset): def __init__(self, filename): ...
https://stackoverflow.com/questions/55693363/
How to fix "TypeError: data type not understood" in numpy when creating transformer no peak mask
I'm trying to implement and train a transformer for NMT via a blog post, everything works except I can't create the no peaking mask as I get this error: "TypeError: data type not understood" Code: target_seq = batch.Python.transpose(0,1) target_pad = PY_TEXT.vocab.stoi['<pad>'] target_msk = (target_seq != tar...
The first input to np.triu should be a tuple of desired sizes instead of a numpy array. Try: np.triu((1, size, size), k=1).astype("uint8")
https://stackoverflow.com/questions/55694263/
How can I simplify a nested loop into torch tensor operations?
I'm trying to convert some code I have written in numpy which contains a nested-loop into tensor operations found in PyTorch. However, after trying to implement my own version I'm not getting the same value on the output. I have managed to do the same with a single loop, so I'm not entirely sure what I'm doing wrong. ...
The problem is in the shapes. You have kp_values and wavef in (1000, 1) which needs to be converted to (1000, ) before the multiplications. The outcome of (kp_values.pow(2)).mul(wavef).mul(MTV[i,:]) is a matrix but you asummed it is a vector. So, the following should work. summation += ((k_values[i].pow(2)).mul(wavef...
https://stackoverflow.com/questions/55694676/
What do * and mean stand for in this PyTorch expression?
I do not understand how to evaluate this expression: x.view(*(x.shape[:-2]),-1).mean(-1)`, if x.shape == (N, C, H, W). What does the asterisk * stand for? And what is mean(-1) ?
What is *? For .view() pytorch expects the new shape to be provided by individual int arguments (represented in the doc as *shape). The asterisk (*) can be used in python to unpack a list into its individual elements, thus passing to view the correct form of input arguments it expects. So, in your case, x.shape is (N...
https://stackoverflow.com/questions/55718119/
Creating a Simple 1D CNN in PyTorch with Multiple Channels
The dimensionality of the PyTorch inputs are not what the model expects, and I am not sure why. To my understanding... in_channels is first the number of 1D inputs we would like to pass to the model, and is the previous out_channel for all subsequent layers. out_channels is the desired number of kernels (filters). ...
You are forgetting the "minibatch dimension", each "1D" sample has indeed two dimensions: the number of channels (7 in your example) and length (10 in your case). However, pytorch expects as input not a single sample, but rather a minibatch of B samples stacked together along the "minibatch dimension". So a "1D" CNN in...
https://stackoverflow.com/questions/55720464/
TypeError: can't convert np.ndarray of type numpy.object_
How to convert a numpy array of dtype=object to torch Tensor? array([ array([0.5, 1.0, 2.0], dtype=float16), array([4.0, 6.0, 8.0], dtype=float16) ], dtype=object)
It is difficult to answer properly since you do not show us how you try to do it. From your error message I can see that you try to convert a numpy array containing objects to a torch tensor. This does not work, you will need a numeric data type: import torch import numpy as np # Your test array without 'dtype=object'...
https://stackoverflow.com/questions/55724123/
Pytorch: multiple datasets with multiple losses
I am using multiple datasets. I have multiple losses, each of which must be evaluated on a subset of these datasets. I want to generate a batch from each dataset, and evaluate each loss on all of its appropriate batches. Some of the losses are pairwise (need to load pairs of corresponding datapoints) whereas others are...
It's not clear from your question what exactly your settings are. However, you can have multiple Datasets instances, one for each of your datasets. On top of your datasets, you can implement a "tagged dataset", a dataset that adds a "tag" for all samples: class TaggedDataset(data.Dataset): def __init__(dataset, tag)...
https://stackoverflow.com/questions/55725798/
Which python deep learning libraries compile at runtime?
I am trying to wrap my head around C-optimized code in python. I have read a couple of times now that python achieves high-speed computing through C-extensions. In other words, whenever I work with libraries such as numpy, it basically calls a C-extension that calculates the result and returns it. C-extensions using n...
C extensions in python numpy uses C-extensions a lot. For instance, you can take a look at the C implementation of the sort() function [1] here [2]. [1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html [2] https://github.com/numpy/numpy/blob/master/numpy/core/src/npysort/quicksort.c.src Deep le...
https://stackoverflow.com/questions/55733736/
Stretch the values of a pytorch tensor
I wish to 'stretch' the last two dimensions of a pytorch tensor to increase the spatial resolution of a (batch, channels, y, x) tensor. Minimal example (I need 'new_function') a = torch.tensor([[1, 2], [3, 4]]) b = new_function(a, (2, 3)) print(b) tensor([[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [3, 3,...
Use torch.nn.functional.interpolate (thanks to Shai) torch.nn.functional.interpolate(input_tensor.float(), size=(4, 6)) My original idea was to use a variety of view and repeat methods: def stretch(e, sdims): od = e.shape return e.view(od[0], od[1], -1, 1).repeat(1, 1, 1, sdims[-1]).view(od[0], od[1], od[2]...
https://stackoverflow.com/questions/55734651/
What is the desired behavior of average pooling with padding?
Recently I've trained a neural network using pytorch and there is an average pooling layer with padding in it. And I'm confused about the behavior of it as well as the definition of average pooling with padding. For example, if we have a input tensor: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] When padding is one and kern...
It's basically up to you to decide how you want your padded pooling layer to behave. This is why pytorch's avg pool (e.g., nn.AvgPool2d) has an optional parameter count_include_pad=True: By default (True) Avg pool will first pad the input and then treat all elements the same. In this case the output of your example wou...
https://stackoverflow.com/questions/55738420/
Getting gradient of vectorized function in pytorch
I am brand new to PyTorch and want to do what I assume is a very simple thing but am having a lot of difficulty. I have the function sin(x) * cos(x) + x^2 and I want to get the derivative of that function at any point. If I do this with one point it works perfectly as x = torch.autograd.Variable(torch.Tensor([4])...
Here you can find relevant discussion about your error. In essence, when you call backward() without arguments it is implicitly converted to backward(torch.Tensor([1])), where torch.Tensor([1]) is the output value with respect to which gradients are calculated. If you pass 4 (or more) inputs, each needs a value with ...
https://stackoverflow.com/questions/55749202/
Extract elements from .npy file, convert them to PyTorch tensors
I read a .npy file that contains just the labels for images. The labels are stored in dictionary format. I need to convert this to an array of Tensors. But I'm unable to extract elements one of the other from the object the file returns, which is numpy.ndarray type. import numpy as np data = np.load('/content/drive/M...
The below worked for me, with guidance by @kmario23 import numpy as np data = np.load('/content/drive/My Drive/targets.npy') print(data.item()) {0: array(5), 1: array(0), 2: array(4), 3: array(1), 4: array(9), 5: array(2), 6: array(1), 7: array(3)} # data is a 0-d numpy.ndarray that contains a dictionary. print(lis...
https://stackoverflow.com/questions/55754400/
Replicate subtensors in PyTorch
I have a tensor “image_features” having shape torch.Size([100, 1024, 14, 14]). I need to replicate each subtensor (1024, 14, 14) 10 times, obtaining a tensor having shape torch.Size([1000, 1024, 14, 14]). Basically, the first ten rows of the resulting tensor should correspond to the first row of the original one, the...
Another approach that would solve your problem is: orig_shape = (100, 1024, 14, 14) new_shape = (100, 10, 1024, 14, 14) input = torch.randn(orig_shape) # [100, 1024, 14, 14] input = input.unsqueeze(1) # [100, 1, 1024, 14, 14] input = input.expand(*new_shape) # [100, 10, 1024, 14, 14] input = input.transpose(0, 1).cont...
https://stackoverflow.com/questions/55757255/
RuntimeError: cuda runtime error (35) : CUDA driver version is insufficient for CUDA runtime version at torch/csrc/cuda/Module.cpp:51
When I try to load a pytorch checkpoint: checkpoint = torch.load(pathname) I see: RuntimeError: cuda runtime error (35) : CUDA driver version is insufficient for CUDA runtime version at torch/csrc/cuda/Module.cpp:51 I created the checkpoint with a GPU available, but now only have CPU available. How do I load ...
Load the checkpoint data to the best currently available location: if torch.cuda.is_available(): map_location=lambda storage, loc: storage.cuda() else: map_location='cpu' checkpoint = torch.load(pathname, map_location=map_location)
https://stackoverflow.com/questions/55759311/
Expected object of scalar type Long but got scalar type Byte for argument #2 'target'
I am running a nn on colab and came across this error which was not there when i ran the same code on my local system. I have tried with reduced batch size too but the error still persists. Loading dataset Start training --------------------------------------------------------------------------- RuntimeError ...
The title of your question is telling what is causing this error. The target should have type torch.LongTensor, but it is instead torch.ByteTensor. Before calling nll_loss do: target = target.type(torch.LongTensor)
https://stackoverflow.com/questions/55762581/
How to load pretrained googlenet model in pytorch
I'm trying to finetune a GoogleNet network over a specific dataset but I'm having trouble loading it. What I try now is: model = torchvision.models.googlenet(pretrained=True) However I get an error: AttributeError: module 'torchvision.models' has no attribute 'googlenet' I have the latest version of torchvision ...
You can instead use the GoogLeNet inception_v3 model ("Rethinking the Inception Architecture for Computer Vision"): import torchvision google_net = torchvision.models.inception_v3(pretrained=True)
https://stackoverflow.com/questions/55762706/
Got Very Different Scores After Translating Simple Test Model from Keras to PyTorch
I'm trying to transition from Keras to PYTorch. After reading tutorials and similar questions, I came up with the following simple models to test. However, the two models below gives me very different scores: Keras (0.9), PyTorch (0.03). Could someone give me guidance? Basically my dataset has 120 features and multi...
You need to call optimizer.zero_grad() at the start of each iteration, otherwise the gradients from different batches just keep getting accumulated.
https://stackoverflow.com/questions/55763984/
Pytorch custom activation functions?
I'm having issues with implementing custom activation functions in Pytorch, such as Swish. How should I go about implementing and using custom activation functions in Pytorch?
There are four possibilities depending on what you are looking for. You will need to ask yourself two questions: Q1) Will your activation function have learnable parameters? If yes, you have no choice but to create your activation function as an nn.Module class because you need to store those weights. If no, you are fr...
https://stackoverflow.com/questions/55765234/
Neural networks fails to approximate simple multiplication and division
I am trying to fit simple feedforward neural networks on simple data where my goal is to just approximate (abc)/d max_a=2 max_b = 3000 max_c=10 max_d=1 def generate_data(no_elements=10000): a = np.random.uniform(0,max_a,no_elements) b = np.random.uniform(1,max_b,no_elements) c=np.random.uniform(0.001,max_...
Looks like neural networks are bad in multiplication and division. check out this for details. So basically I have to log transform my data, in the above case to approximate ((abc)/d)=e neural network has to figure out simple addition and subtraction.As per this question complicated multiplication and division become...
https://stackoverflow.com/questions/55774902/
Size mismatch for DNN for the MNIST dataset in pytorch
I have to find a way to create a neural network model and train it on the MNIST dataset. I need there to be 5 layers, with 100 neurons each. However, when I try to set this up I get an error that there is a size mismatch. Can you please help? I am hoping that I can train on the model below: class Mnist_DNN(nn.Module):...
You setup your layer to get a batch of 1D vectors of dim 784 (=28*28). However, in your forward function you view the input as a batch of 2D matrices of size 28*28. try viewing the input as a batch of 1D signals: xb = xb.view(-1, 784)
https://stackoverflow.com/questions/55777588/
PyTorch: apply mapping over singleton dimension of tensor
I'm afraid the title is not very descriptive but I could not think of a better one. Essentially my problem is the following: I have a pytorch tensor of shape (n, 1, h, w) for arbitrary integers n, h and w (in my specific case this array represents a batch of grayscale images of dimension h x w). I also have another t...
Here is one way using slicing, stacking, and view-based reshape: In [239]: half_way = b.shape[0]//2 In [240]: upper_half = torch.stack((b[:half_way, :][:, 0], b[:half_way, :][:, 1]), dim=0).view(-1, 3, 3) In [241]: lower_half = torch.stack((b[half_way:, :][:, 0], b[half_way:, :][:, 1]), dim=0).view(-1, 3, 3) In [242...
https://stackoverflow.com/questions/55778000/
What does "RuntimeError: CUDA error: device-side assert triggered" in PyTorch mean?
I have seen a lot of specific posts to particular case-specific problems, but no fundamental motivating explanation. What does this error: RuntimeError: CUDA error: device-side assert triggered mean? Specifically, what is the assert that is being triggered, why is the assert there, and how do we work backwards to de...
When a device-side error is detected while CUDA device code is running, that error is reported via the usual CUDA runtime API error reporting mechanism. The usual detected error in device code would be something like an illegal address (e.g. attempt to dereference an invalid pointer) but another type is a device-side ...
https://stackoverflow.com/questions/55780923/
How to free gpu memory by deleting tensors?
Suppose I create a tensor and put it on the GPU and don't need it later and want to free the GPU memory allocated to it; How do I do it? import torch a=torch.randn(3,4).cuda() # nvidia-smi shows that some mem has been allocated. # do something # a does not exist and nvidia-smi shows that mem has been freed. I have t...
Running del tensor frees the memory from the GPU but does not return it to the device which is why the memory still being shown as used on nvidia-smi. You can create a new tensor and that would reuse that memory. Sources https://discuss.pytorch.org/t/how-to-delete-pytorch-objects-correctly-from-memory/947 https://discu...
https://stackoverflow.com/questions/55788093/
In pytorch data parallel mode, how to use the global tensor?
In this example, I wish the z_proto could be global for different GPUs. However, in the data parallel mode, it is split into different GPUs as well. How to solve such a problem? Thank you. class SequencePrototypeTokenClassification(nn.Module): def __init__(self,seq_model, label_num): super(SequencePrototyp...
It turns out the DataParallel would only replicate the nn.Parameter of the nn.Module. So I random initialized a nn.Parameter named z_proto in the module and copy the value of tensor z_proto into the parameter. Then the parameter is replicated into 4 GPUs.
https://stackoverflow.com/questions/55792837/
TypeError: view() takes at most 2 arguments (3 given)
I try to use view() in pytorch but i can't input 3 arguments.I don't know why it keep giving this error? Can anyone help me with this? def forward(self, input): lstm_out, self.hidden = self.lstm(input.view(len(input), self.batch_size, -1))
It looks like your input is a numpy array, not torch tensor. You need to convert it first, like input = torch.Tensor(input).
https://stackoverflow.com/questions/55805242/
Common variable name acronym for Pytorch or Tensorflow?
I have seen var name like ninp (num_input), nhid (num_hidden), emsize (embedding size) in pytorch example github repo. What are some of other common acronyms and their meaning/context?
These are common terminologies used in Sequence Models (e.g. RNNs, LSTMs, GRUs etc.,) Here is a description of what those terms mean: ninp (num_input) : Dimension of the vectors in the embedding matrix emsize (embedding size): Dimension of the vectors in the embedding matrix nhid (num_hidden): how many "hidden" unit...
https://stackoverflow.com/questions/55806201/
How can I run pytorch with multiple graphic cards?
I have 4 graphic cards which I want to utilize to pytorch. I have this net: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5, 1) self.conv2 = nn.Conv2d(20, 50, 5, 1) self.fc1 = nn.Linear(4*4*50, 500) self.fc2 = nn.Linear(5...
You may use torch.nn.DataParallel to distribute your model among many workers. Just pass your network (torch.nn.Module) to it's constructor and use forward as you would normally. You may also specify on which GPUs it is supposed to run by providing device_ids with List[int] or torch.device. Just for the sake of code:...
https://stackoverflow.com/questions/55812514/
How to sum based off index vector
I have 3 vectors - a sum vector, a contribution vector, and a value vector. I want to sum the value vectors according to their contribution vector and place them in their corresponding index in the sum vector. An example is: A = [0;0] (sum vector), B = [0,0,1,1] (contribution vector) C=[20,30,40,10] (value vector) Ou...
You are looking for index_add_() A.index_add_(0, B, C) Note that B should be of type torch.long (it is an index vector), and C should be of type torch.float, same as the type of A. Moreover, you can use the first dim argument to do this summation along different dimensions in case A and C are multi-dimensional tenso...
https://stackoverflow.com/questions/55819027/
Fixing the seed for torch random_split()
Is it possible to fix the seed for torch.utils.data.random_split() when splitting a dataset so that it is possible to reproduce the test results?
You can use torch.manual_seed function to seed the script globally: import torch torch.manual_seed(0) See reproducibility documentation for more information. If you want to specifically seed torch.utils.data.random_split you could "reset" the seed to it's initial value afterwards. Simply use torch.initial_seed() li...
https://stackoverflow.com/questions/55820303/
Log-likelihood function in NumPy
I followed this tutorial and I was confused with the part where the author defines the negative-loglikelihood lost function. def nll(input, target): return -input[range(target.shape[0]), target].mean() loss_func = nll Here, target.shape[0] is 64 and target is a vector with length 64 tensor([5, 0, 4, 1, 9, 2, 1...
In the tutorial, both input and target are torch.tensor. The negative log likelihood loss is computed as below: nll = -(1/B) * sum(logPi_(target_class)) # for all sample_i in the batch. Where: B: The batch size C: The number of classes Pi: of shape [num_classes,] the probability vector of prediction for sampl...
https://stackoverflow.com/questions/55820628/
Pytorch 1.0: what does net.to(device) do in nn.DataParallel?
The following code from the tutorial to pytorch data paraleelism reads strange to me: device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") model = Model(input_size, output_size) if torch.cuda.device_count() > 1: print("Let's use", torch.cuda.device_count(), "GPUs!") # dim = 0 [30, xxx] ->...
They add few lines in the tutorial to explain nn.DataParallel. DataParallel splits your data automatically, and send job orders to multiple models on different GPUs using the data. After each model finishes their job, DataParallel collects and merges the results for you. The above quote can be understood that nn...
https://stackoverflow.com/questions/55828687/
How to run perticular code in gpu using PyTorch?
I am using an image processing code in python opencv. Since that process is taking a lot of time to process say 30 images. I tried to process these image parallel using Multiprocessing. The multiprocessing part is working good in CPU but I want to use that multiprocessing thing in GPU(cuda). I use torch.multiprocessi...
Your class RoadShoulderWidth is a nn.Module subclass which lets you use .to(device). This only means that all other nn.Module objects or nn.Parameters that are members of your RoadShoulderWidth object are moved to the device. As from your example, there are none, so nothing happens. In general PyTorch does not move co...
https://stackoverflow.com/questions/55830960/
GPU out of memory when initializing network
I am trying to initialize a CNN and then put it on my GPU for training. When I put it on GPU I get the error: (CUDA error: out of memory). I have run similar networks with no such problems. This is the only thing in cuda as I have not loaded any images as of yet. Any ideas as to what is going wrong? I am using pytorch...
This issue happened to me once when a GPU driver was out of date. My GPU was a 1070 4 gig. I'd recommend a reinstall of drivers and restart.
https://stackoverflow.com/questions/55836293/
TypeError when adding cuda device
I'm running a simple demo of Pytorch 1.0, and get stuck when trying cuda settings.(vscode 1.33.1, Python 3.6) My pytorch code is as followed. import torch from torch import cuda if cuda.is_available(): devic=cuda.device(0) layer=torch.rand([5,3,2],requires_grad=True) Everything worked fine...But when I trie...
Just exchange devic=cuda.device(0) to devic=torch.device('cuda:0'). The - confusing - reason that torch.device is what's used to allocate a tensor to a physical device, while torch.cuda.device is a context manager to tell torch on which gpu to compute stuff. so if you do torch.zeros(1, device=torch.device('cuda:0')...
https://stackoverflow.com/questions/55852727/
Tensor reduction based off index vector
As an example, I have 2 tensors: A = [1;2;3;4;5;6;7] and B = [2;3;2]. The idea is that I want to reduce A based off B - such that B's values represent how to sum A's values- such that B = [2;3;2] means the reduced A shall be the sum of the first 2 values, next 3, and last 2: A' = [(1+2);(3+4+5);(6+7)]. It is apparent t...
Here is the solution. First, we create an array of indices B_idx with the same size of A. Then, accumulate (add) all elements in A based on the indices B_idx using index_add_. A = torch.arange(1, 8) B = torch.tensor([2, 3, 2]) B_idx = [idx.repeat(times) for idx, times in zip(torch.arange(len(B)), B)] B_idx = to...
https://stackoverflow.com/questions/55854761/
Computational graph vs (computer algebra) symbolic expression
I was reading Baydin et al, Automatic Differentiation in Machine Learning: a Survey, 2018 (Arxiv), which differentiates between symbolic differentiation and automatic differentiation (AD). It then says: AD Is Not Symbolic Differentiation. Symbolic differentiation is the automatic manipulation of [symbolic] expres...
This is a nice question, which gets at some fundamental differences in AD and also some fundamental design differences between big ML libraries like PyTorch and TensorFlow. In particular, I think understanding the difference between define-by-run and define-and-run AD is confusing and takes some time to appreciate. B...
https://stackoverflow.com/questions/55868135/
Does Google-Colab continue running the script when "Runtime disconnected"?
I am training a neural network for Neural Machine Traslation on Google Colaboratory. I know that the limit before disconnection is 12 hrs, but I am frequently disconnected before (4 or 6 hrs). The amount of time required for the training is more then 12 hrs, so I add some savings each 5000 epochs. I don't understand i...
Yes, for ~1.5 hours after you close the browser window. To keep things running longer, you'll need an active tab.
https://stackoverflow.com/questions/55874473/
tuple object not callable when building a CNN in Pytorch
I am new to neural networks and currently trying to build a CNN with 2 conv layers. class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Conv2d(in_channels = 1, out_channels = 16, kernel_size = 3, stride = 1, padding = 1), self.maxp1 = nn.MaxPool2d(2), self.conv2 = n...
You may change nn.ReLU to F.relu. If you want to use nn.ReLU(), you may better to declare it as part of __init__ method, and call it later in forward(): class CNN(nn.Module): def __init__(self): super(CNN, self).__init__() self.conv1 = nn.Conv2d(in_channels = 1, out_channels = 16, kernel_size = 3, strid...
https://stackoverflow.com/questions/55874539/
How to get an output dimension for each layer of the Neural Network in Pytorch?
class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.net = nn.Sequential( nn.Conv2d(in_channels = 3, out_channels = 16), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(in_channels = 16, out_channels = 16), nn.ReLU(), Flatten(), nn.Linear(4096, 64),...
A simple way is: Pass the input to the model. Print the size of the output after passing every layer. class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.net = nn.Sequential( nn.Conv2d(in_channels = 3, out_channels = 16), nn.ReLU(), nn.MaxPool2d(2), nn....
https://stackoverflow.com/questions/55875279/
Pytorch tensor indexing: How to gather rows by tensor containing indices
I have the tensors: ids: shape (7000,1) containing indices like [[1],[0],[2],...] x: shape(7000,3,255) ids tensor encodes the index of bold marked dimension of x which should be selected. I want to gather the selected slices in a resulting vector: result: shape (7000,255) Background: I have some scores (shape = (7000,3...
Here is a solution you may look for ids = ids.repeat(1, 255).view(-1, 1, 255) An example as below: x = torch.arange(24).view(4, 3, 2) """ tensor([[[ 0, 1], [ 2, 3], [ 4, 5]], [[ 6, 7], [ 8, 9], [10, 11]], [[12, 13], [14, 15], [16, 17]], ...
https://stackoverflow.com/questions/55881002/
How to generate burst of images from a single image by adding misalignment?
I'm learning about image denoising and Pytorch.I want to get burst of images generated from a single image. For example, I have an image, then random crop a patch of specific size from it. Then I want to add an 1 or 2 pixels shift on it to get a new image with tiny difference. What could I do? Is it better to use some ...
You should use the transforms to do some image augmentation for your problem. As I read your comment, you can restrict translate = (a, b) to do some tiny random shifts in both dimensions. import torchvision.transforms as transforms transform = transforms.RandomAffine(degrees, translate=None, scale=None, shear=None,...
https://stackoverflow.com/questions/55881517/
How can I optimize gradient flow in LSTM with Pytorch?
I'm working in lstm with time-series data and I've observed a problem in the gradients of my network. I've one layer of 121 lstm cells. For each cell I've one input value and I get one output value. I work with a batch size of 121 values and I define lstm cell with batch_first = True, so my outputs are [batch,timestep,...
I have been dealing with these problems several times. And here is my advice: Use smaller number of timesteps The hidden output of the previous timestep is passed to the current steps and multiplied by the weights. When you multiply several times, the gradient will explode or vanish exponentially with the number ...
https://stackoverflow.com/questions/55883197/
The `device` argument should be set by using `torch.device` or passing a string as an argument
My data iterator currently runs on the CPU as device=0 argument is deprecated. But I need it to run on the GPU with the rest of the model etc. Here is my code: pad_idx = TGT.vocab.stoi["<blank>"] model = make_model(len(SRC.vocab), len(TGT.vocab), N=6) model = model.to(device) criterion = LabelSmoothing(size=l...
pad_idx = TGT.vocab.stoi["<blank>"] model = make_model(len(SRC.vocab), len(TGT.vocab), N=6) model = model.to(device) criterion = LabelSmoothing(size=len(TGT.vocab), padding_idx=pad_idx, smoothing=0.1) criterion = criterion.to(device) BATCH_SIZE = 12000 train_iter = MyIterator(train, batch_size=BATCH_SIZE, device ...
https://stackoverflow.com/questions/55883389/
pytorch compute pairwise difference: Incorrect result in NumPy vs PyTorch and different PyTorch versions
Suppose I have two arrays, and I want to calculate row-wise differences between every two rows of two matrices of the same shape as follows. This is how the procedure looks like in numpy, and I want to replicate the same thing in pytorch. >>> a = np.array([[1,2,3],[4,5,6]]) >>> b = np.array([[3,4,5],...
The issue arises because of using PyTorch 0.1. If using PyTorch 1.0.1, the same operation of NumPy generalize to PyTorch without any modifications and issues. Here is a snapshot of the run in Colab. As we can see, we indeed get the same results. Here is an attempt to reproduce the error you faced of getting incor...
https://stackoverflow.com/questions/55884299/
pytorch: how can I use picture as label in dataloader?
I want to do some image reconstruction using autoencoders in pytorch, however, I didn't find a way to use image as label for an input image.(the label image is different from original ones) I've tried the image folder method, but I think that's for classfication and I am currently unable to come up with one solution. ...
Write your custom Dataset, below is a simple example. import torch.utils.data.Dataset as Dataset class CustomDataset(Dataset): def __init__(self, input_imgs, label_imgs, transform): self.input_imgs = input_imgs self.label_imgs = label_imgs self.transform = transform def __len__(sel...
https://stackoverflow.com/questions/55886306/
Understanding PyTorch einsum
I'm familiar with how einsum works in NumPy. A similar functionality is also offered by PyTorch: torch.einsum(). What are the similarities and differences, either in terms of functionality or performance? The information available at PyTorch documentation is rather scanty and doesn't provide any insights regarding this...
Since the description of einsum is skimpy in torch documentation, I decided to write this post to document, compare and contrast how torch.einsum() behaves when compared to numpy.einsum(). Differences: NumPy allows both small case and capitalized letters [a-zA-Z] for the "subscript string" whereas PyTorch allows ...
https://stackoverflow.com/questions/55894693/
How to load tfrecord in pytorch?
How to use tfrecord with pytorch? I have downloaded "Youtube8M" datasets with video-level features, but it is stored in tfrecord. I tried to read some sample from these file to convert it to numpy and then load in pytorch. But it failed. reader = YT8MAggregatedFeatureReader() files = tf.gfile.Glob("/Data/yout...
Maybe this can help you: TFRecord reader for PyTorch
https://stackoverflow.com/questions/55896083/
Pytorch equivalent of `tf.reverse_sequence`?
I would like to do backward-direction LSTM on a padded sequence, which requires reversing the input sequence without the padding. For a batch like this (where _ stands for padding): a b c _ _ _ d e f g _ _ h i j k l m if would like to get: c b a _ _ _ g f e d _ _ m l k j i h TensorFlow has a function tf.reverse_...
Unfortunately, there is no direct equivalent yet, although it has been requested. I also looked into the whole PackedSequence object, but it has no .flip() operation defined on it. Assuming you already have the necessary data to provide the lengths, as you suggested, you could implement it with this function: def fli...
https://stackoverflow.com/questions/55904997/