instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
Full Page Text Recognition Dataset Creation | I have been reading OCR papers such as this one https://arxiv.org/pdf/1704.08628.pdf , and I am have trouble finding out how these datasets are actually generated.
In the linked paper, they use a regressor to predict the start location (a point) and height of a line of text. Then, based on that starting point and heig... | So after submitting this, the related threads window showed me many threads that my googling did not turn up. This http://www.prima.cse.salford.ac.uk/tools software seems to be what I was looking for, but I would still love to hear other ideas.
| https://stackoverflow.com/questions/50456692/ |
PyTorch : How to properly create a list of nn.Linear() | I have created a class that has nn.Module as subclass.
In my class, I have to create N number of linear transformation, where N is given as class parameters.
I therefore proceed as follow :
self.list_1 = []
for i in range(N):
self.list_1.append(nn.Linear(self.x, 1, bias=mlp_bias))
In the forward m... | You can use nn.ModuleList to wrap your list of linear layers as explained here
self.list_1 = nn.ModuleList(self.list_1)
| https://stackoverflow.com/questions/50463975/ |
Input 3 and 1 channel input to the network in pytorch? | My dataset consists mostly of 3 channel images, but i also have a few 1 channel images,Is it possible to train a network that takes in both 3 channels and 1 channels as inputs?
Any suggestions are welcome,Thanks in advance,
| You can detect the grayscale images by checking the size and apply some transformation to have 3 channels.
It seems to be better to convert images from grayscale to RGB than simply copying the image three times on the channels.
You can do that by cv2.cvtColor(gray_img, cv.CV_GRAY2RGB) if you have opencv-python instal... | https://stackoverflow.com/questions/50471053/ |
PyTorch - Torchvision - BrokenPipeError: [Errno 32] Broken pipe | I'm trying to carry out the tutorial named "Training a classifier" with PyTorch.
WHen trying to debug this part of the code :
import matplotlib.pyplot as plt
import numpy as np
# functions to show an image
def imshow(img):
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpos... | This doesn't look to be a PyTorch problem. Try executing the code in Jupyter notebooks and other environment troubleshooting.
| https://stackoverflow.com/questions/50480689/ |
Can't install torch on linux box using pip | As the title states I am trying to install torch on linux using pip.
I run the command pip install torch==0.3.1
And I get the following output:
Collecting torch==0.3.1
Could not find a version that satisfies the requirement torch==0.3.1 (from versions: 0.1.2, 0.1.2.post1)
No matching distribution found for torch=... | Try update pip itself, using
pip install --upgrade pip
then,
pip install torch==0.3.1
| https://stackoverflow.com/questions/50488869/ |
If I'm not specifying to use CPU/GPU, which one is my script using? | In pytorch, if I'm not writing anything about using CPU/GPU, and my machine supports CUDA (torch.cuda.is_available() == True):
What is my script using, CPU or GPU?
If CPU, what should I do to make it run on GPU? Do I need to rewrite everything?
If GPU, will this script crash if torch.cuda.is_available() == False?
Doe... | My way is like this (below pytorch 0.4):
dtype = torch.cuda.float if torch.cuda.is_available() else torch.float
torch.zeros(2, 2, dtype=dtype)
UPDATE pytorch 0.4:
device = torch.device("cuda" if use_cuda else "cpu")
model = MyRNN().to(device)
from PyTorch 0.4.0 Migration Guide.
| https://stackoverflow.com/questions/50495053/ |
Tips or patterns for reshaping 4D/5D arrays, (videos to frames) | I find it really hard to visualize reshaping 4D 5D arrays in numpy/pytorch. (I assume both reshape in similar patter, I am using pytorch currently!).
Like suppose I have videos with dimension [N x C x D x H x W]
(num videos x channels video x frames video x height video x width video)
Suppose I want to reshape vide... | Simply swap the second and third axes, and then merge the new second axis (old third one) with the first one with reshaping -
output = input_array.swapaxes(1,2).reshape(N*D,C,H,W)
We can also use transpose : input_array.transpose(0,2,1,3,4) to get the same swapping axes effect.
For a general intuitive method, pleas... | https://stackoverflow.com/questions/50502700/ |
Pytorch simple text generator not working and loss keeps diverging | I am new to pytorch and deep learning in general , and am trying to build a simple text generator. For reasons I don't understand, the loss keeps diverging and the model doesn't. Here's the code.
class RNN(nn.Module):
def __init__(self, embed_size, hidden_size):
super(RNN, self).__init__()
self.emb... |
Are you trying to implement an RNN? Because I see you are naming your model as RNN but the implementation doesn't seem to take signals from previous time steps.
It seems that you are not implementing batches and are training based on inputting 1 character and then backpropagating on that. This is known to cause instab... | https://stackoverflow.com/questions/50511212/ |
How to do softmax for pixelwise classification | My goal is to do grey scale image segmentation using pixelwise classification. So I have two labels 0 and 1. I made a network in pytorch which looks like the following.
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.up = nn.Upsample(scale_factor=2, mode='nearest')
self.con... | Please check last line of my code .. basically your dimension for softmax was wrong.
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.up = nn.Upsample(scale_factor=2, mode='nearest')
self.conv11 = nn.Conv2d(1, 128, kernel_size=3, padding=1)
self.conv12 = n... | https://stackoverflow.com/questions/50534515/ |
How to do CIFAR-10 with PyTorch on CUDA? | I'm following the CIFAR-10 PyTorch tutorial at this pytorch page , and can't get PyTorch running on the GPU. The code is exactly as in the tutorial.
The error I get is
Traceback (most recent call last):
File "(file path)/CIFAR10_tutorial.py", line 116, in <module>
outputs = net(images)
File "/usr/local/l... | I'm leaving an answer, in case anyone else is stuck on the same.
First, configure Pytorch to use the GPU if available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print(device)
Then, in the init function, cast to gpu by calling .cuda() on every element of the NN, e.g.
self.conv1 = nn.Con... | https://stackoverflow.com/questions/50539641/ |
Getting multiprocessing lock error when running vizdoom and pytorch program on Windows Subsystem for Linux | whenever I try to run my program on WSL, I get the following error. I'm pretty new to pytorch and vizdoom, so I don't know how to solve this problem.
Setup
- Windows 10 x64
- Ubuntu 14 (on WSL)
- Python 2.7.14 (Anaconda 2)
- OpenAI Gym 0.9.5
- Vizdoom 1.1.4
- doom-py 0.0.14
- ppaquette/gym-doom
- pytorch 0.0.12
(... | Upgrading the Ubuntu on WSL to the latest version (18.04) solved the problem for me.
For me it was running the following commands on WSL.
sudo -S env RELEASE_UPGRADER_NO_SCREEN=1 do-release-upgrade
sudo apt-get update
sudo apt-get upgrade -y
| https://stackoverflow.com/questions/50541672/ |
Is there a function in google.colab module to close the runtime | Sometimes when I give run in google.colab I cant stay infront of the computer to manually disconnect from the server when the run is complete and the connection stays on even when my run is complete occupying the node for no reason.
Is there a function in google.colab so that say I can insert the function to close the... | import sys
sys.exit()
This will end the runtime, freeing up the GPU.
EDIT: Apparently my last answer doesn't work any more.
The thing to do now is !kill -9 -1.
| https://stackoverflow.com/questions/50541851/ |
How do I split a custom dataset into training and test datasets? | import pandas as pd
import numpy as np
import cv2
from torch.utils.data.dataset import Dataset
class CustomDatasetFromCSV(Dataset):
def __init__(self, csv_path, transform=None):
self.data = pd.read_csv(csv_path)
self.labels = pd.get_dummies(self.data['emotion']).as_matrix()
self.height = 48... | Using Pytorch's SubsetRandomSampler:
import torch
import numpy as np
from torchvision import datasets
from torchvision import transforms
from torch.utils.data.sampler import SubsetRandomSampler
class CustomDatasetFromCSV(Dataset):
def __init__(self, csv_path, transform=None):
self.data = pd.read_csv(csv_p... | https://stackoverflow.com/questions/50544730/ |
Do I need to make multiple instances of a neural network in PyTorch to test multiple loss functions? | I have written out a neural network in PyTorch and I would like to compare the results of two different loss functions on this one network
Should I go about making two different instances of the network and test one loss function per network like this
network_w_loss_1 = ANN().cuda()
network_w_loss_2 = ANN().cuda()
c... | You have to make 2 different instances. Otherwise you are just training one network alternating between 2 losses (both losses would update its parameters).
| https://stackoverflow.com/questions/50546862/ |
Issue with torch.cuda() function | I'm new to PyTorch. It is working when I use gpu running my program with TensorFlow. But this is a problem with PyTorch.
I search a lot, but cannot find any useful answer. Who can help me?
Error:
My environment:
windows10 64bit
python3.6
cuda9.0
cudnn64
gpu:GTX965m
| As you can see for yourself in the release notes here, the PyTorch developers have decided to deprecate compute capability 3.0 and 5.0 devices from their builds starting with PyTorch 0.3.1.
Your device is a compute 5.0 device and is, therefore, not supported in the most recent versions of PyTorch.
You can read about wh... | https://stackoverflow.com/questions/50562552/ |
Fast way to multiple 3D tensors of shape (1, 1, 256) and (10, 1, 256) in PyTorch and Numpy | I am trying to adapt the seq2seq model for my own task, https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/seq2seq-translation.ipynb
I have two tensors at the decoder stage
rnn_output: (1, 1, 256) # time_step x batch_size x hidden_dimension
encoder_inputs: (10, 1, 256) # seq_len x batc... | Example using torch.bmm():
import torch
from torch.autograd import Variable
import numpy as np
seq_len = 10
rnn_output = torch.rand((1, 1, 256))
encoder_outputs = torch.rand((seq_len, 1, 256))
# As computed in the tutorial:
attn_score = Variable(torch.zeros(seq_len))
for i in range(seq_len):
attn_score[i] = rnn_... | https://stackoverflow.com/questions/50570697/ |
Implementing Luong Attention in PyTorch | I am trying to implement the attention described in Luong et al. 2015 in PyTorch myself, but I couldn't get it work. Below is my code, I am only interested in the "general" attention case for now. I wonder if I am missing any obvious error. It runs, but doesn't seem to learn.
class AttnDecoderRNN(nn.Module):
def... | This version works, and it follows the definition of Luong Attention (general), closely. The main difference from that in the question is the separation of embedding_size and hidden_size, which appears to be important for training after experimentation. Previously, I made both of them the same size (256), which creates... | https://stackoverflow.com/questions/50571991/ |
Why pytorch isn't minimizing x*x for me? | I expect x to converge to 0, which is minimum of x*x. But this doesn't happen. What am I doing wrong in this small sample code:
import torch
from torch.autograd import Variable
tns = torch.FloatTensor([3])
x = Variable(tns, requires_grad=True)
z = x*x
opt = torch.optim.Adam([x], lr=.01, betas=(0.5, 0.999))
for i in ra... | The problem you have is that you don't zero the gradients when you are calculating each loop. Instead, by setting retain_graph=True and not calling opt.zero_grad() at each step of the loop you are actually adding the gradients calculated to ALL previous gradients calculated. So instead of taking a step in gradient desc... | https://stackoverflow.com/questions/50588958/ |
PyTorch equivalent of index_add_ that takes the maximum instead | In PyTorch, the index_add_ method of a Tensor does a summation using a provided index tensor:
idx = torch.LongTensor([0,0,0,0,1,1])
child = torch.FloatTensor([1, 3, 5, 10, 8, 1])
parent = torch.FloatTensor([0, 0])
parent.index_add_(0, idx, child)
The first four child values sum into parent[0] and the next two go int... | A solution playing with the indices:
def index_max(child, idx, num_partitions):
# Building a num_partition x num_samples matrix `idx_tiled`:
partition_idx = torch.range(0, num_partitions - 1, dtype=torch.long)
partition_idx = partition_idx.view(-1, 1).expand(num_partitions, idx.shape[0])
idx_tiled = i... | https://stackoverflow.com/questions/50605205/ |
Variational Autoencoder gives same output image for every input mnist image when using KL divergence | When not using KL divergence term, the VAE reconstructs mnist images almost perfectly but fails to generate new ones properly when provided with random noise.
When using KL divergence term, the VAE gives the same weird output both when reconstructing and generating images.
Here's the pytorch code for the loss fun... | A possible reason is the numerical unbalance between the two losses, with your BCE loss computed as an average over the batch (c.f. size_average=True) while the KLD one is summed.
| https://stackoverflow.com/questions/50607516/ |
How can I assign pytorch tensor a matrix from numpy? | Create WxW tensor:
x = Variable(torch.FloatTensor(W,W).zero_(), requires_grad=True)
Do some calculations:
x_copy = x0=np.copy(x.data.numpy())
x_upd = handleArray(x_copy)
How can I assign x data from x_upd ?
| Ok, the solution was to do:
x.data.from_numpy(x_upd)
| https://stackoverflow.com/questions/50611420/ |
Overflow when unpacking long - Pytorch | I am running the following code
import torch
from __future__ import print_function
x = torch.empty(5, 3)
print(x)
on an Ubuntu machine in CPU mode, which gives me following error, what would be the reason and how to fix
x = torch.empty(5, 3)
----> print(x)
/usr/local/lib/python3.6/dist-packages/torch/ten... | Since, torch.empty() gives uninitialized memory, so you may or may not get a large value from it. Try
x = torch.rand(5, 3)
print(x)
this would give the response.
| https://stackoverflow.com/questions/50617917/ |
Custom convolution kernel and toroidal convolution in PyTorch | I want to do two things with a PyTorch convolution which aren't mentioned in the documentation or code:
I want to create a convolution with a fixed kernel like this:
000010000
000010000
100010001
000010000
000010000
The horizontal aspect is like dilation, I guess, but the vertical part is different. I see that dil... |
Unlike torch.nn.conv2d() (which instantiates its own trainable kernel), torch.nn.functional.conv2d() takes as parameters both your matrix and kernel, so you can pass it whatever custom kernel you want.
As suggested by @zou3519 in a Github issue (linked to the issue you mentioned yourself), you could implement yourself... | https://stackoverflow.com/questions/50635736/ |
Convert image to proper dimension PyTorch | I have an input image, as numpy array of shape [H, W, C] where H - height, W - width and C - channels.
I want to convert it into [B, C, H, W] where B - batch size, which should be equal to 1 every time, and changing the place for C.
_image = np.array(_image)
h, w, c = _image.shape
image = torch.from_numpy(_image).unsq... |
I'd prefer the following, which leaves the original image unmodified and simply adds a new axis as desired:
_image = np.array(_image)
image = torch.from_numpy(_image)
image = image[np.newaxis, :]
# _unsqueeze works fine here too
Then to swap the axes as desired:
image = image.permute(0, 3, 1, 2)
# permutation ap... | https://stackoverflow.com/questions/50657449/ |
Finding euclidean distance given an index array and a pytorch tensor | I got a pytorch tensor:
Z = np.random.rand(100,2)
tZ = autograd.Variable(torch.cuda.FloatTensor(Z), requires_grad=True)
and an index array:
idx = (np.array([0, 0, 0, 4, 3, 8], dtype="int64"),
np.array([0, 1, 2, 3, 7, 4], dtype="int64"))
I need to find the distances of all the pairs of points in my tZ ten... | Using torch.index_select():
Z = np.random.rand(100,2)
tZ = autograd.Variable(torch.cuda.FloatTensor(Z), requires_grad=True)
idx = (np.array([0, 0, 0, 4, 3, 8], dtype="int64"),
np.array([0, 1, 2, 3, 7, 4], dtype="int64"))
tZ_gathered = [torch.index_select(tZ, dim=0,
index=torc... | https://stackoverflow.com/questions/50658111/ |
Training on minibatches of varying size | I'm trying to train a deep learning model in PyTorch on images that have been bucketed to particular dimensions. I'd like to train my model using mini-batches, but the mini-batch size does not neatly divide the number of examples in each bucket.
One solution I saw in a previous post was to pad the images with addition... | Do you have 2 networks for each of the samples(A cnn kernel size has to be fix). If yes just pass the above custom_sampler to the batch_sampler args of DataLoader class. That would fix the issue.
| https://stackoverflow.com/questions/50663803/ |
Converting a scipy coo_matrix to pytorch sparse tensor | I have a coo_matrix:
from scipy.sparse import coo_matrix
coo = coo_matrix((3, 4), dtype = "int8")
That I want converted to a pytorch sparse tensor. According to the documentation https://pytorch.org/docs/master/sparse.html it should follow the coo format, but I cannot find a simple way to do the conversion. Any help... |
Using the data as in the Pytorch docs, it can be done simply using the attributes of the Numpy coo_matrix:
import torch
import numpy as np
from scipy.sparse import coo_matrix
coo = coo_matrix(([3,4,5], ([0,1,1], [2,0,2])), shape=(2,3))
values = coo.data
indices = np.vstack((coo.row, coo.col))
i = torch.LongTensor... | https://stackoverflow.com/questions/50665141/ |
Google Colab: "Unable to connect to the runtime" after uploading Pytorch model from local | I am using a simple (not necessarily efficient) method for Pytorch model saving.
import torch
from google.colab import files
torch.save(model, filename) # save a trained model on the VM
files.download(filename) # download the model to local
best_model = files.upload() # select the model just downloaded
best_model[... | (I wrote this answer before reading your update. Think it may help.)
files.upload() is just for uploading files. We have no reason to expect it to return some pytorch type/model.
When you call a = files.upload(), a is a dictionary of filename - a big bytes array.
{'my_image.png': b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIH... | https://stackoverflow.com/questions/50675219/ |
Beta Distribution in PyTorch for a, b>1? | PyTorch supports Beta distributions however, when alpha or beta is greater than 1, it doesn't work:
m = Beta(torch.tensor([2]), torch.tensor([2]))
m.sample()
|
It works as expected using FloatTensor with torch==0.4.0:
import torch
from torch.distributions import Beta
m = Beta(torch.FloatTensor([2]), torch.FloatTensor([2]))
m.sample()
| https://stackoverflow.com/questions/50686080/ |
Missing Weight Vectors when converting from PyTorch to CoreML via ONNX | I am trying to convert a PyTorch model to CoreML via ONNX, but the ONNX-->CoreML conversion is missing weight vectors?
I am following the tutorial here which makes this statement:
Step 3: Converting the model to CoreML
It's as easy as running the convert function. The resulting object is a coremltools MLModel... | You are calling torch.onnx.export with export_params=False, which, as the 0.3.1 doc reads, is saving the model architecture without the actual parameter tensors. The more recent documentation doesn't specify this, but we can assume that due to the Weight tensor not found error that you are getting.
Try it with export_... | https://stackoverflow.com/questions/50689203/ |
PyTorch Tutorial Error Training a Classifier | I just started the PyTorch-Tutorial Deep Learning with PyTorch: A 60 Minute Blitz and I should add, that I haven't programmed any python (but other languages like Java) before.
Right now, my Code looks like
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
imp... | Check out the documentation for multiprocessing: programming guidelines for windows. You should wrap all operations in functions and then call them inside an if __name__ == '__main__' clause:
# required imports
def load_datasets(...):
# Code to load the datasets with multiple workers
def train(...):
# Code t... | https://stackoverflow.com/questions/50701690/ |
How reshape 3D tensor of shape (3, 1, 2) to (1, 2, 3) | I intended
(Pdb) aa = torch.tensor([[[1,2]], [[3,4]], [[5,6]]])
(Pdb) aa.shape
torch.Size([3, 1, 2])
(Pdb) aa
tensor([[[ 1, 2]],
[[ 3, 4]],
[[ 5, 6]]])
(Pdb) aa.view(1, 2, 3)
tensor([[[ 1, 2, 3],
[ 4, 5, 6]]])
But what I really want is
tensor([[[ 1, 3, 5],
[ 2, 4, 6]]]... | You can permute the axes to the desired shape. (This is similar to numpy.moveaxis() operation).
In [90]: aa
Out[90]:
tensor([[[ 1, 2]],
[[ 3, 4]],
[[ 5, 6]]])
In [91]: aa.shape
Out[91]: torch.Size([3, 1, 2])
# pass the desired ordering of the axes as argument
# assign the result back to some ten... | https://stackoverflow.com/questions/50710037/ |
CIFAR-10 Meaningless Normalization Values | I tried to build a neural network for a CIFAR-10 database. I used Pytorch Framework.
I have a question about of data loading step.
transform_train = T.Compose([
T.RandomCrop(32, padding=4),
T.RandomHorizontalFlip(),
T.ToTensor(),
T.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
])
t... | I think you can have a look here:
The first three values are the means over each channel, while the second triple are the standard deviations.
| https://stackoverflow.com/questions/50710493/ |
Resize PyTorch Tensor | I am currently using the tensor.resize() function to resize a tensor to a new shape t = t.resize(1, 2, 3).
This gives me a deprecation warning:
non-inplace resize is deprecated
Hence, I wanted to switch over to the tensor.resize_() function, which seems to be the appropriate in-place replacement. However, this l... | You can instead choose to go with tensor.reshape(new_shape) or torch.reshape(tensor, new_shape) as in:
# a `Variable` tensor
In [15]: ten = torch.randn(6, requires_grad=True)
# this would throw RuntimeError error
In [16]: ten.resize_(2, 3)
---------------------------------------------------------------------------
Ru... | https://stackoverflow.com/questions/50718045/ |
How to share a list of tensors in PyTorch multiprocessing? | I am programming with PyTorch multiprocessing. I want all the subprocesses can read/write the same list of tensors (no resize). For example the variable can be
m = list(torch.randn(3), torch.randn(5))
Because each tensor has different sizes, I cannot organize them into a single tensor.
A python list has no share_me... | I find the solution by myself. It is pretty straightforward. Just call share_memory_() for each list elements. The list itself is not in the shared memory, but the list elements are.
Demo code
import torch.multiprocessing as mp
import torch
def foo(worker,tl):
tl[worker] += (worker+1) * 1000
if __name__ == '__m... | https://stackoverflow.com/questions/50735493/ |
PyTorch how to implement disconnection (connections and corresponding gradients are masked)? | I try to implement the following graph. As you can see, the neurons are not fully connected, i.e., the weights are masked and so are their corresponding gradients.
import torch
import numpy as np
x = torch.rand((3, 1))
# tensor([[ 0.8525],
# [ 0.1509],
# [ 0.9724]])
weights = torch.rand((2, 3), req... | Actually, the above method is correct. The disconnections essentially block feed-forward and back-propogation on corresponding connections. In other words, weights and gradients are masked. The codes in question reveal the first while this answer reveals the latter.
mask_weights.register_hook(print)
z = torch.Tensor(... | https://stackoverflow.com/questions/50740557/ |
PyTorch: When using backward(), how can I retain only part of the graph? | I have a PyTorch computational graph, which consists of a sub-graph performing some calculation, and the result of this calculation (let's call it x) is then branched into two other sub-graphs. Each of these two sub-graphs yields some scalar results (lets call them y1 and y2). I want to do a backward pass for each of t... | The argument retain_graph will retain the entire graph, not just a sub-graph. However, we can use garbage collection to free unneeded parts of the graph. By removing all references to the sub-graph from x to y1, this sub-graph will be freed:
import torch
w = torch.tensor(1.0)
w.requires_grad_(True)
# sub-graph for... | https://stackoverflow.com/questions/50741344/ |
Gradient error when calculating - pytorch | I am learning to use pytorch (0.4.0) to automate the gradient calculation, however I did not quite understand how to use the backward () and grad, as I'm doing an exercise I need to calculate df / dw using pytorch and
making the derivative analytically, returning respectively auto_grad, user_grad, but I did not quite ... | I think you computed the gradients in the wrong way. Try this.
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn.functional as F
def sigmoid(x):
return 1.0 / (1.0 + np.exp(-x))
def graph2(W_np, x_np, b_np):
W = Variable(torch.Tensor(W_np), requires_grad=True)
x = torch.t... | https://stackoverflow.com/questions/50750463/ |
Pytorch : How .grad() function returning result? | I am trying to understand grad() function in python, I know about backpropagation but having some doubt in .grad() function result.
So if i have a very simple network say with one single input and one single weight :
import torch
from torch.autograd import Variable
from torch import FloatTensor
a_tensor=Variable(Fl... | This is because you are not zeroing the gradients. What loss.backward() does is accumulate gradients - it adds gradients to existing ones. If you don't zero the gradient, then running loss.backward() over and over just keep adding the gradients to each other. What you want to do is zero the gradients after each step an... | https://stackoverflow.com/questions/50751689/ |
Adding modules in Pytorch Custom Module | Is it considered bad practice to add modules to a custom pytorch nn.Module using self.add_module()? All of the documentation seems to assign the layers to properties, then access them in the forward() method.
For example:
class ConvLayer(nn.Module):
def __init__(self):
self.add_module('conv',nn.Conv2d(...... | Calling add_module will add an entry to the _modules dict. The Module class also overwrites __getattr__ so that when you try to access a layer, it will look inside the _modules dict, despite the fact that the layer is not actually an attribute of the object. But from the user's perspective, it doesn't make a difference... | https://stackoverflow.com/questions/50753038/ |
What does data.norm() < 1000 do in PyTorch? | I am following the PyTorch tutorial here.
It says that
x = torch.randn(3, requires_grad=True)
y = x * 2
while y.data.norm() < 1000:
y = y * 2
print(y)
Out:
tensor([-590.4467, 97.6760, 921.0221])
Could someone explain what data.norm() does here?
When I change .randn to .ones its output is tensor([ 1... | It's simply the L2 norm (a.k.a Euclidean norm) of the tensor. Below is a reproducible illustration:
In [15]: x = torch.randn(3, requires_grad=True)
In [16]: y = x * 2
In [17]: y.data
Out[17]: tensor([-1.2510, -0.6302, 1.2898])
In [18]: y.data.norm()
Out[18]: tensor(1.9041)
# computing the norm using elementary op... | https://stackoverflow.com/questions/50753477/ |
Debugging GAN covergence error | Building a GAN to generate images. The images have 3 color channels, 96 x 96.
The images that are generated by the generator at the beginning are all black, which is an issue given that is statistically highly unlikely.
Also, the loss for both networks is not improving.
I have posted the entire code below, and comme... | One can't really easily debug your training without the data and so on, but a possible problem is that your generator's last layer is a Tanh(), which means output values between -1 and 1. You probably want:
To have your real images normalized to the same range, e.g. in train_discriminator():
# train on real
pred_re... | https://stackoverflow.com/questions/50762466/ |
Pytorch not using cuda device | I have the following code:
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
import scipy.io
folder = 'small/'
mat = scipy.io.loadmat(folder+'INISTATE.mat');
ini_state = np.float32(mat['ini_state']);
ini_state = torc... | Actually your model indeed runs on GPU instead of CPU. The reason of low GPU usage is that both your model and batch size are small, which demands low computational cost. You may try increasing the batch size to around 1000, and the GPU usage should be higher. In fact PyTorch prevents operations that mix CPU and GPU da... | https://stackoverflow.com/questions/50771001/ |
Pytorch - handling picutres and .jpeg files (beginner's questions) | I am new at Pytorch, and have a couple of questions regarding the way pictures are being handled:
1) In the "training a classifier" tutorial, the pictures are PIL files, and are being handled via the following commands (where "transform" also turns the PIL format into a tensor format):
trainset = torchvision.datasets... | For your first question:
image = trainset[1][0]
print(image)
For your second question:
from PIL import Image
import numpy as np
import os
def load_image(infilename):
"""This function loads an image into memory when you give it
the path of the image
"""
img = Image.open(infilename)
img.load(... | https://stackoverflow.com/questions/50772128/ |
Understanding the Input Parameters in RNN | I'm having a hard time to understand the different "jargons" used in RNN. They are the following:
batch_size, time_steps, inputs and instances.
Let me go through my understanding of each input parameters & please correct me where I'm wrong.
Suppose I've got a sequence of numbers and I want to predict the next numb... | Alright pal, you did good learning those concepts. I had a hard time learning those correctly. Everything you know seems to be in order and as for "instances". They're basically a set of data. There's no fixed term of usage of "instances" in a deep learning community. Some people use it for referring for a different se... | https://stackoverflow.com/questions/50773509/ |
How to calculate Pixel wise accuracy in pytorch? | My code looks like the following and I get accuracy from 0 to 9000, which means its clearly not working.
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
predicted = outputs.data
predicted = predicted.to('cpu')
predicted_img =... | I am assuming the following line accumulates accuracy over mini-batches.
accuracy += (correct/total)
And avg_accuracy = accuracy/batch gives average accuracy over the entire dataset where batch represents the total number of mini-batches representing the whole dataset.
If you are getting accuracy greater than 100,... | https://stackoverflow.com/questions/50773842/ |
Pytorch - Pick best probability after softmax layer | I have a logistic regression model using Pytorch 0.4.0, where my input is high-dimensional and my output must be a scalar - 0, 1 or 2.
I'm using a linear layer combined with a softmax layer to return a n x 3 tensor, where each column represents the probability of the input falling in one of the three classes (0, 1 or ... | torch.argmax() is probably what you want:
import torch
x = torch.FloatTensor([[0.2, 0.1, 0.7],
[0.6, 0.2, 0.2],
[0.1, 0.8, 0.1]])
y = torch.argmax(x, dim=1)
print(y.detach())
# tensor([ 2, 0, 1])
# If you want to reshape:
y = y.view(1, -1)
print(y.detach())
# tensor([... | https://stackoverflow.com/questions/50776548/ |
Pytorch - meaning of a command in a basic "forward" pass | I am new with Pytorch, and will be glad if someone will be able to help me understand the following (and correct me if I am wrong), regarding the meaning of the command x.view in Pytorch first tutorial, and in general about the input of convolutional layers and the input of fully-connected layers:
def forward(self, x)... | Its from Petteri Nevavuori's lecture notes and shows how a feature map is produced from an image I with a kernel K. With each application of the kernel a dot product is calculated, which effectively is the sum of element-wise multiplications between I and K in an K-sized area within I.
You could say that kernel look... | https://stackoverflow.com/questions/50777675/ |
AttributeError: module 'torch' has no attribute "device" | ---> 13 device = torch.device({"cuda"} if torch.cuda.is_available() else {"cpu"})
14
15
AttributeError: module 'torch' has no attribute 'device'
I'm 99% sure this is because I didn't upgrade pytorch from 0.31 to 0.4 however I can't upgrade pytorch for now.
I need to translate .device (0.4) to something... | torch.cuda.device() is a context manager.
torch.cuda.set_device(0)
# On device 0
with torch.cuda.device(1):
print("Inside device is 1")
# On device 1
print("Outside is still 0")
# On device 0
And the above works from 0.2 version.
| https://stackoverflow.com/questions/50781020/ |
Invalid device Ordinal , CUDA / TORCH | I am getting this error on running the script in ubuntu 16.04 . Please bear with me , i am new to python ,
I have checked the already available options on internet but i couldnt fix it.
RuntimeError: cuda runtime error (10) : invalid device ordinal at torch/csrc/cuda/Module.cpp:32
I am currently running this file ... | The pre-trained weights might be mapped to a different gpuid. If a model pre-trained on multiple Cuda devices is small enough, it might be possible to run it on a single GPU. This is assuming at least batch of size 1 fits in the available GPU and RAM.
#WAS
model.load_state_dict(torch.load(final_model_file, map_locatio... | https://stackoverflow.com/questions/50783853/ |
What does -1 mean in pytorch view? | As the question says, what does -1 do in pytorch view?
>>> a = torch.arange(1, 17)
>>> a
tensor([ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.,
11., 12., 13., 14., 15., 16.])
>>> a.view(1,-1)
tensor([[ 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.,
... | Yes, it does behave like -1 in numpy.reshape(), i.e. the actual value for this dimension will be inferred so that the number of elements in the view matches the original number of elements.
For instance:
import torch
x = torch.arange(6)
print(x.view(3, -1)) # inferred size will be 2 as 6 / 3 = 2
# tensor([[ 0., ... | https://stackoverflow.com/questions/50792316/ |
Pytorch: how to make the trainloader use a specific amount of images? | Assume I am using the following calls:
trainset = torchvision.datasets.ImageFolder(root="imgs/", transform=transform)
trainloader = torch.utils.data.DataLoader(trainset,batch_size=4,suffle=True,num_workers=1)
As far as I can tell, this defines the trainset as consisting of all the images in the folder "images", with... | You can wrap the class DatasetFolder (or ImageFolder) in another class to limit the dataset:
class LimitDataset(data.Dataset):
def __init__(self, dataset, n):
self.dataset = dataset
self.n = n
def __len__(self):
return self.n
def __getitem__(self, i):
return self.dataset[i... | https://stackoverflow.com/questions/50798172/ |
Error in pip install torchvision on Windows 10 | on pytorch, installing on Windows 10, conda and Cuda 9.0.
cmd did not complain when i ran conda install pytorch cuda90 -c pytorch, then when I ran pip3 install torchvision I get this error message.
Requirement already satisfied: torchvision in PATHTOFILE\python35\lib\site-packages (0.2.1)
Requirement already satisfie... | Fixed it by running the following
pip3 install http://download.pytorch.org/whl/cu90/torch-0.4.0-cp35-cp35m-win_amd64.whl
pip3 install torchvision
This weirdly fixes the problem. No idea why. Next time just try to run everything on pip
| https://stackoverflow.com/questions/50812838/ |
Pytorch - Subclasses of torchvision.dataset.ImageFolder - Import Error | Following my last post, I am now trying to implement a subclass of the torchvision.datasets.ImageFolder class. The following code returns an error ("name 'default_loader' is not defined"), and I can't figure out why. Will you please help me?
class ExtendingImageFolder(torchvision.datasets.ImageFolder)
def __init__(... | default_loader() is a function defined in torchvision/datasets/folder.py, along ImageFolder and other folder-based dataset helpers.
It is however not exported in torchvision/datasets/__init__.py (unlike ImageFolder). You can still import it directly with "from torchvision.datasets.folder import default_loader" - which... | https://stackoverflow.com/questions/50817964/ |
pytorch 0.4.0 broadcasting doesn't work in optimizer | I can't seem to get broadcasting to work with autograd in pytorch 0.4.0! Any help appreciated. Below is a minimal code example that reproduces my problem. I would like to find a single value "bias", which minimizes the loss over the dataset. The understand the error message as it wants to backpropagate a vector with 5 ... | I forgot to do a reverse broadcasting in the backward pass!
Specifically, had to change
if len_grad == 2: grad_bias = -1 * grad_out
to
if len_grad == 2: grad_bias = -1 * torch.mean(grad_out)
| https://stackoverflow.com/questions/50826045/ |
Why do we do batch matrix-matrix product? | I'm following Pytorch seq2seq tutorial and ittorch.bmm method is used like below:
attn_applied = torch.bmm(attn_weights.unsqueeze(0),
encoder_outputs.unsqueeze(0))
I understand why we need to multiply attention weight and encoder outputs.
What I don't quite understand is the reason why we n... | In the seq2seq model, the encoder encodes the input sequences given in as mini-batches. Say for example, the input is B x S x d where B is the batch size, S is the maximum sequence length and d is the word embedding dimension. Then the encoder's output is B x S x h where h is the hidden state size of the encoder (which... | https://stackoverflow.com/questions/50826644/ |
How to perform sum pooling in PyTorch | How to perform sum pooling in PyTorch. Specifically, if we have input (N, C, W_in, H_in) and want output (N, C, W_out, H_out) using a particular kernel_size and stride just like nn.Maxpool2d ?
| You could use torch.nn.AvgPool1d (or torch.nn.AvgPool2d, torch.nn.AvgPool3d) which are performing mean pooling - proportional to sum pooling. If you really want the summed values, you could multiply the averaged output by the pooling surface.
| https://stackoverflow.com/questions/50838876/ |
pytorch seq2seq encoder forward method | I'm following Pytorch seq2seq tutorial and below is how they define the encoder function.
class EncoderRNN(nn.Module):
def __init__(self, input_size, hidden_size):
super(EncoderRNN, self).__init__()
self.hidden_size = hidden_size
self.embedding = nn.Embedding(input_size, hidden_size)
... | In PyTorch, you write your own class by extending torch.nn.Module and define the forward method to express your desired computational steps that serve as the "paperwork" (e.g. calling hooks) in the model.__call__(...) method (which is what model(x) will call by python special name specifications).
If you are curious y... | https://stackoverflow.com/questions/50847438/ |
Is it possible to use a machine learning library with streaming inputs and outputs? | I want to incorporate machine learning into a project ive been working on but i havent seen anything about my intended use case. It seems like the old pandoras box project did something like this but with textual input and output.
I want to train a model in real time as well as use it (and then switch it from testing t... | It sounds like a usecase for recurrent neural networks, which translate sequences (your stream) into single outputs or other sequences. This a well-explored approach, e.g., in natural language processing. Tensorflow has support for different flavors of such nets.
| https://stackoverflow.com/questions/50850497/ |
Taking the last state from BiLSTM (BiGRU) in PyTorch | After reading several articles, I am still quite confused about correctness of my implementation of getting last hidden states from BiLSTM.
Understanding Bidirectional RNN in PyTorch (TowardsDataScience)
PackedSequence for seq2seq model (PyTorch forums)
What's the difference between “hidden” and “output” in PyTorch L... | In a general case if you want to create your own BiLSTM network, you need to create two regular LSTMs, and feed one with the regular input sequence, and the other with inverted input sequence. After you finish feeding both sequences, you just take the last states from both nets and somehow tie them together (sum or con... | https://stackoverflow.com/questions/50856936/ |
PyTorch custom dataset dataloader returns strings (of keys) not tensors | I am trying to load my own dataset and I use a custom Dataloader that reads in images and labels and converts them to PyTorch Tensors. However when the Dataloader is instantiated it returns strings x "image" and y "labels" but not the real values or tensors when read (iter)
print(self.train_loader) # shows a Tensor ... | You are not properly using python's enumerate(). (x, y) are currently assigned the 2 keys of your batch dictionary i.e. the strings "image" and "labels". This should solve your problem:
for i, batch in enumerate(self.train_loader):
x, y = batch["image"], batch["labels"]
# ...
| https://stackoverflow.com/questions/50878650/ |
F.conv2d stuck on my CentOS | I run my pytorch code well on mac and even on windows system but the same code seems stuck on CentOS6.3.
I debug with ipdb, and found the code was stuck at F.conv2d function:
> /home/work/anaconda2/envs/PyTorch/lib/python2.7/site-packages/torch/nn/modules/conv.py(301)forward()
300 return F.conv2d(input, sel... | I reinstall CentOS6.3, and then upgrade glibc2.14, glibc2.17 due to the pytorch0.4.0 running error info.
Now everything is ok.
By the way, the pytorch0.3.1 perform well before i upgrade the glibc(up to 2.12). So i think the lastest pytorch0.4.0 may haven’t deal very well with glibc, leave running deadlock appearance ... | https://stackoverflow.com/questions/50888863/ |
Channel wise CrossEntropyLoss for image segmentation in pytorch | I am doing an image segmentation task. There are 7 classes in total so the final outout is a tensor like [batch, 7, height, width] which is a softmax output. Now intuitively I wanted to use CrossEntropy loss but the pytorch implementation doesn't work on channel wise one-hot encoded vector
So I was planning to make a... | As Shai's answer already states, the documentation on the torch.nn.CrossEntropy() function can be found here and the code can be found here. The built-in functions do indeed already support KD cross-entropy loss.
In the 3D case, the torch.nn.CrossEntropy() functions expects two arguments: a 4D input matrix and a 3D t... | https://stackoverflow.com/questions/50896412/ |
How to import the tensorflow lite interpreter in Python? | I'm developing a Tensorflow embedded application using TF lite on the Raspberry Pi 3b, running Raspbian Stretch. I've converted the graph to a flatbuffer (lite) format and have built the TFLite static library natively on the Pi. So far so good. But the application is Python and there seems to be no Python binding av... | I was able to write python scripts to do classification 1, object-detection (tested with SSD MobilenetV{1,2}) 2, and image semantic segmentation 3 on an x86 running Ubuntu and an ARM64 board running Debian.
How to build Python binding for TF Lite code: Build pip with recent TensorFlow master branch and install it (Ye... | https://stackoverflow.com/questions/50902067/ |
Can't open jupyter notebook in docker | I am trying to open the jupyter notebook in a container, but I just came cross this situation:
[I 10:01:25.051 NotebookApp] The Jupyter Notebook is running at:
[I 10:01:25.051 NotebookApp] http://8c1eb91f0492:8888/?token=7671a7abe557349c8d8ad1cbf207702451925efd2c27c84e
[I 10:01:25.051 NotebookApp] Use Control-C to stop... | Try using localhost step by step :
1 - Launch the following command :
docker run -p 8888:8888 jupyter/scipy-notebook
2 - Copy/paste the url URL into your browser : http://e6ef92c5e5d6:8888/?token=...
3 - Replace the hostname by localhost : http://localhost:8888/?token=...
It worked for me :
[I 03:22:51.414 Note... | https://stackoverflow.com/questions/50919752/ |
Training Error in PyTorch - RuntimeError: Expected object of type FloatTensor vs ByteTensor | A minimal working sample will be difficult to post here but basically I am trying to modify this project http://torch.ch/blog/2015/09/21/rmva.html which works smoothly with MNIST. I am trying to run it with my own dataset with a custom dataloader.py as below:
from __future__ import print_function, division #ds
import ... | As far as I can tell, it seems that as you commented the normalize / transforms.Normalize operations applied to your dataset, your images don't have their values normalize to float between [0, 1], and are instead keeping their byte values between [0, 255].
Try applying data normalization or at least converting your im... | https://stackoverflow.com/questions/50930300/ |
Understanding torch.nn.Parameter | How does torch.nn.Parameter() work?
| I will break it down for you. Tensors, as you might know, are multi dimensional matrices. Parameter, in its raw form, is a tensor i.e. a multi dimensional matrix. It sub-classes the Variable class.
The difference between a Variable and a Parameter comes in when associated with a module. When a Parameter is associated... | https://stackoverflow.com/questions/50935345/ |
AttributeError: 'builtin_function_or_method' object has no attribute 'requires_grad' | I'm getting this error when training the MNIST data, the csvfiles is from Kaggle. Can someone show me where I went wrong? Here is my code. The version of PyTorch is 0.4.0.
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.utils.data as data
impor... | You are not calling the squeeze method,This should work
b_y = b_y.squeeze()
| https://stackoverflow.com/questions/50939730/ |
Using CUDA with pytorch? | Is there a way to reliably enable CUDA on the whole model?
I want to run the training on my GPU. I found on some forums that I need to apply .cuda() on anything I want to use CUDA with (I've applied it to everything I could without making the program crash). Surprisingly, this makes the training even slower.
Then, I f... | You can use the tensor.to(device) command to move a tensor to a device.
The .to() command is also used to move a whole model to a device, like in the post you linked to.
Another possibility is to set the device of a tensor during creation using the device= keyword argument, like in t = torch.tensor(some_list, device=... | https://stackoverflow.com/questions/50954479/ |
Pytorch - Purpose of images preprocessing in the transfer learning tutorial | In the Pytorch transfer learning tutorial, the images in both the training and the test sets are being pre-processed using the following code:
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normal... | Regarding RandomResizedCrop
Why ...ResizedCrop? - This answer is straightforward. Resizing crops to the same dimensions allows you to batch your input data. Since the training images in your toy dataset have different dimensions, this is the best way to make your training more efficient.
Why Random...? - Generating d... | https://stackoverflow.com/questions/50963295/ |
how is the batch size determined? | I'm looking at this pytorch starter tutorial:
https://pytorch.org/tutorials/beginner/blitz/neural_networks_tutorial.html#sphx-glr-beginner-blitz-neural-networks-tutorial-py
the zero_grad() function is being used to zero the gradients which means that it's running with mini-batches, is this a correct assumption? I... | You predefine the batch_Size in the dataloader, For a linear layer you do not specify batch size but the number of features of your previous layer and the number of features you wish to get after the linear operation.
This is a code sample from the Pytorch Docs
m = nn.Linear(20, 30)
input = Variable(torch.randn(128, ... | https://stackoverflow.com/questions/50978781/ |
Multi-label, multi-class image classifier (ConvNet) with PyTorch | I am trying to implement an image classifier (CNN/ConvNet) with PyTorch where I want to read my labels from a csv-file. I have 4 different classes and an image may belong to more than one class.
I have read through the PyTorch Tutorial and this Stanford tutorial and this one, but none of them cover my specific case. I... | Maybe I am missing something, but if you want to convert your columns 1..N (N = 4 here) into a label vector or shape (N,) (e.g. given your example data, label(img1) = [0, 0, 0, 1], label(img3) = [1, 0, 1, 0], ...), why not:
Read all the label columns into self.label_arr:
self.label_arr = np.asarray(self.data_info.il... | https://stackoverflow.com/questions/50981714/ |
Pytorch broadcasting product of two tensors | I want to multiply two tensors, here is what I have got:
A tensor of shape (20, 96, 110)
B tensor of shape (20, 16, 110)
The first index is for batch size.
What I want to do is essentially take each tensor from B - (20, 1, 110), for example, and with that, I want to multiply each A tensor (20, n, 110).
So the produ... | Using torch.einsum followed by torch.reshape:
AB = torch.einsum("ijk,ilk->ijlk", (A, B)).reshape(A.shape[0], -1, A.shape[2])
Example:
import numpy as np
import torch
# A of shape (2, 3, 2):
A = torch.from_numpy(np.array([[[1, 1], [2, 2], [3, 3]],
[[4, 4], [5, 5], [6, 6]]]))... | https://stackoverflow.com/questions/50982503/ |
How to sample through a small dataset for more iterations than data size? | I have one small and one large dataset and they signify two separate classes. The network I am training is style transfer, so I need one image of each class in order to keep training. The training stops though, as soon as the smaller dataset runs out. How can I keep sampling from the small dataset randomly beyond its s... | Your idea with the RandomSampler was not far off. There is a sampler called SubsetRandomSampler. While a subset typically is smaller than the whole set, this has not to be the case.
Lets say your smaller dataset has A entries and your second dataset has B. You could define your indices:
indices = np.random.randint(0... | https://stackoverflow.com/questions/50982781/ |
How to optimize lower Cholesky Parameter in Pytorch? | Is there any way to create a parameter which is lower triangular with positive diagonal and enforce this constraint during optimization in Pytorch?
| Check this one torch.potrf.
A simple example:
a = torch.randn(3, 3)
a = torch.mm(a, a.t()) # make symmetric positive definite
l = torch.potrf(a, upper=False)
tri_loss = l.sum()
opt.zero_grad()
tri_loss.backward()
opt.step()
| https://stackoverflow.com/questions/50988668/ |
Is there any pytorch function can combine the specific continuous dimensions of tensor into one? | Let's call the function I'm looking for "magic_combine", which can combine the continuous dimensions of tensor I give to it. For more specific, I want it to do the following thing:
a = torch.zeros(1, 2, 3, 4, 5, 6)
b = a.magic_combine(2, 5) # combine dimension 2, 3, 4
print(b.size()) # should be (1, 2, 60, 6)
I... | I am not sure what you have in mind with "a more elegant way", but Tensor.view() has the advantage not to re-allocate data for the view (original tensor and view share the same data), making this operation quite light-weight.
As mentioned by @UmangGupta, it is however rather straight-forward to wrap this function to a... | https://stackoverflow.com/questions/50991189/ |
loading librispeech in pytorch for ASR | I'm newly working to train an automatic speech recognition machine using neural network and CTC loss. But the first thing I'm supposed to do is to prepare the data for training the model. Since the Librispeech contains huge amounts of data, initially I am going to use a subset of it called "Mini LibriSpeech ASR corpus"... | Your question is quite broad : are you looking after the transcripts of the audio files ? If so they are in a text file in each directory, each line starting with the filename (without the extension).
You can look here : https://github.com/inikdom/rnn-speech/blob/master/util/dataprocessor.py
Especially this method wh... | https://stackoverflow.com/questions/50993861/ |
What does the gather function do in pytorch in layman terms? | What does torch.gather do?
This answer is hard to understand.
|
The torch.gather function (or torch.Tensor.gather) is a multi-index selection method. Look at the following example from the official docs:
t = torch.tensor([[1,2],[3,4]])
r = torch.gather(t, 1, torch.tensor([[0,0],[1,0]]))
# r now holds:
# tensor([[ 1, 1],
# [ 4, 3]])
Let's start with going through the ... | https://stackoverflow.com/questions/50999977/ |
How to vectorise a list of matrix vector multiplications using pytorch/numpy | For example, I have a list of N B x H tensor(i.e. a N x B x H tensor) and a list of N vectors (i.e. N x B tensor). And I want multiply each B x H tensor in the list with corresponding B dimensional tensor, resulting a N x H tensor.
I know how to use a single for-loop with PyTorch to implement the computation, but is t... | You could achieve this with torch.bmm() and some torch.squeeze()/torch.unsqueeze().
I am personally rather fond of the more generictorch.einsum() (which I find more readable):
import torch
import numpy as np
A = torch.from_numpy(np.array([[[1, 10, 100], [2, 20, 200], [3, 30, 300]],
[[4... | https://stackoverflow.com/questions/51001968/ |
Why do we "pack" the sequences in PyTorch? | I was trying to replicate How to use packing for variable-length sequence inputs for rnn but I guess I first need to understand why we need to "pack" the sequence.
I understand why we "pad" them but why is "packing" (via pack_padded_sequence) necessary?
| I have stumbled upon this problem too and below is what I figured out.
When training RNN (LSTM or GRU or vanilla-RNN), it is difficult to batch the variable length sequences. For example: if the length of sequences in a size 8 batch is [4,6,8,5,4,3,7,8], you will pad all the sequences and that will result in 8 sequence... | https://stackoverflow.com/questions/51030782/ |
Getting different output in the Pytorch NLP example Part-of-Speech Tagging | I am following the NLP tutorials on Pytorch’s tutorials website. I am getting different output than what it should show, so I just copy pasted the whole code as it is and still the output is different.
My code is shared in this gist:
Example: An LSTM for Part-of-Speech Tagging
For the 1st sentence
[‘The’, ‘dog’, ‘a... | I updated the epochs=500, i.e ran 500 times and it now outputs the correct sequence.
| https://stackoverflow.com/questions/51032181/ |
PyTorch : predict single example | Following the example from:
https://github.com/jcjohnson/pytorch-examples
This code trains successfully:
# Code in file tensor/two_layer_net_tensor.py
import torch
device = torch.device('cpu')
# device = torch.device('cuda') # Uncomment this to run on GPU
# N is batch size; D_in is input dimension;
# H is hidden... | The code you posted is a simple demo trying to reveal the inner mechanism of such deep learning frameworks. These frameworks, including PyTorch, Keras, Tensorflow and many more automatically handle the forward calculation, the tracking and applying gradients for you as long as you defined the network structure. However... | https://stackoverflow.com/questions/51041128/ |
PyTorch Autograd automatic differentiation feature | I am just curious to know, how does PyTorch track operations on tensors (after the .requires_grad is set as True and how does it later calculate the gradients automatically. Please help me understand the idea behind autograd. Thanks.
| That's a great question!
Generally, the idea of automatic differentiation (AutoDiff) is based on the multivariable chain rule, i.e.
.
What this means is that you can express the derivative of x with respect to z via a "proxy" variable y; in fact, that allows you to break up almost any operation in a bunch of simpler ... | https://stackoverflow.com/questions/51054627/ |
Applying convolution operation to image - PyTorch | To render an image if shape 27x35 I use :
random_image = []
for x in range(1 , 946):
random_image.append(random.randint(0 , 255))
random_image_arr = np.array(random_image)
matplotlib.pyplot.imshow(random_image_arr.reshape(27 , 35))
This generates :
I then try to apply a convolution to the image using t... | There are two problems with your code:
First, 2d convolutions in pytorch are defined only for 4d tensors.
This is convenient for use in neural networks. The first dimension is the batch size while the second dimension are the channels (a RGB image for example has three channels). So you have to reshape your tensor lik... | https://stackoverflow.com/questions/51115476/ |
How to find IoU from segmentation masks? | I am doing an image segmentation task and I am using a dataset that only has ground truths but no bounding boxes or polygons.
I have 2 classes( ignoring 0 for background) and the outputs and ground truth labels are in an array like
Predicted--/---Labels
0|0|0|1|2 0|0|0|1|2
0|2|1|0|0 0|2|1|0|0
0|0|1|1|1 0|... | So I just found out that jaccard_similarity_score is regarded as IoU.
So the solution is very simple,
from sklearn.metrics import jaccard_similarity_score
jac = jaccard_similarity_score(predictions, label, Normalize = True/False)
Source link: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.jaccard... | https://stackoverflow.com/questions/51115630/ |
Jupyterhub with custom singleuser image raises 'no such file or directory' for '/home/jovyan/work' | I tried to setup Jupyterhub to serve Jupyter pytorch notebook using this repo as image https://github.com/stepankuzmin/pytorch-notebook, which is also available as a Docker image on dockerhub as https://hub.docker.com/r/stepankuzmin/pytorch-notebook/.
This involves modifying the config.yml file to point to the image, ... | Resolved.
After much googling I stumbled on this: https://github.com/jupyterhub/jupyterhub/issues/1425. The summary from this is thread is the error can occur due to:
* The singleuser jupyterhub image you are building does not conform to the requirements
* You are building a singleuser jupyterhub image based on an old... | https://stackoverflow.com/questions/51120540/ |
Why a larger neural network back-propagate faster than a smaller one | I wrote the following two NN in pytorch for image segmentation:
The smaller one:
class ConvNetV0(nn.Module):
def __init__(self):
super(ConvNetV0, self).__init__()
self.conv1 = nn.Conv2d(3, 30, 4, padding=2)
self.conv2 = nn.Conv2d(30, 50, 16, padding=7, bias=True)
self.conv3 = nn.Conv2d(50, 20, 2, stri... | I ran a quick benchmark of your models on synthetic data of the size you indicated. At least on my system, the difference isn't actually given by the model forward or backward, but by the computation of the loss. This is likely to be due to the fact that the first model uses more the GPU, therefore the queuing of the o... | https://stackoverflow.com/questions/51124101/ |
LSTM layer returns nan when fed by its own output in PyTorch | I’m trying to generate time-series data with an LSTM and a Mixture Density Network as described in https://arxiv.org/pdf/1308.0850.pdf
Here is a link to my implementation: https://github.com/NeoVand/MDNLSTM
The repository contains a toy dataset to train the network.
On training, the LSTM layer returns nan for its hidde... | The issue was caused by the log-sum-exp operation not being done in a stable way. Here is an implementation of a weighted log-sum-exp trick that I used and could fix the problem:
def weighted_logsumexp(x,w, dim=None, keepdim=False):
if dim is None:
x, dim = x.view(-1), 0
xm, _ = torch.max(x, dim, keepd... | https://stackoverflow.com/questions/51125933/ |
How to format TSV files to use with torchtext? | The way i'm formatting is like:
Jersei N
atinge V
média N
. PU
Programe V
...
First string in each line is the lexical item, the other is a pos tag. But the empty-line (that i'm using to indicate the end of a sentence) gives me the error AttributeError: 'Example' object has no attribute 'text' when running t... | The following code reads the TSV the way i formatted:
mt_train = datasets.SequenceTaggingDataset(path='/path/to/file.tsv',
fields=(('text', text),
('labels', labels)))
It happens that SequenceTaggingDataset properly identif... | https://stackoverflow.com/questions/51127880/ |
what's the difference between torch.Tensor() vs torch.empty() in pytorch? | I have tried it out as below. It seems to me they're the same. What's the difference between torch.Tensor() vs torch.empty() in pytorch?
| torch.Tensor() is just an alias to torch.FloatTensor() which is the default type of tensor, when no dtype is specified during tensor construction.
From the torch for numpy users notes, it seems that torch.Tensor() is a drop-in replacement of numpy.empty()
So, in essence torch.FloatTensor() and torch.empty() does the ... | https://stackoverflow.com/questions/51129043/ |
Why pytorch has two kinds of Non-linear activations? | Why pytorch has two kinds of Non-linear activations?
Non-liner activations (weighted sum, nonlinearity):
https://pytorch.org/docs/stable/nn.html#non-linear-activations-weighted-sum-nonlinearity
Non-linear activations (other): https://pytorch.org/docs/stable/nn.html#non-linear-activations-other
| The primary difference is that the functions listed under Non-linear activations (weighted sum, nonlinearity) perform only thresholding and do not normalize the output. (i.e. the resultant tensor need not necessarily sum up to 1, either on the whole or along some specified axes/dimensions)
Example non-linearities:
... | https://stackoverflow.com/questions/51129751/ |
what is uninitialized data in pytorch.empty function | i was going through pytorch tutorial and came across pytorch.empty function. it was mentioned that empty can be used for uninitialized data. But, when i printed it, i got a value. what is the difference between this and pytorch.rand which also generates data(i know that rand generates between 0 and 1). Below is the cod... | Once you call torch.empty(), a block of memory is allocated according to the size (shape) of the tensor. By uninitialized data, it's meant that torch.empty() would simply return the values in the memory block as is. These values could be default values or it could be the values stored in those memory blocks as a result... | https://stackoverflow.com/questions/51140927/ |
OpenNMT issue with PyTorch: .copy_ function not clear behavior | I'm working with the PyTorch version OpenNMT and I'm trying to modify the Beam Search algorithm. I'm currently stuck in the beam_update function (in OpenNMT-py/onmt/decoders/decoder.py file). When it is called:
sent_states.data.copy_(
sent_states.data.index_select(1, positions))
according to the pyt... | The self tensor is the tensor you call copy_ on.
In your example it is sent_states.data.
To answer the question raised in the comments: Why does copy not behave like assigning with =
.copy() creates a real copy to a new memory location, while assigning with = only stores a reference to the memory location.
The co... | https://stackoverflow.com/questions/51152088/ |
Building recurrent neural network with feed forward network in pytorch | I was going through this tutorial. I have a question about the following class code:
class RNN(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(RNN, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.output_size = output_siz... | The network is recurrent, because you evaluate multiple timesteps in the example.
The following code is also taken from the pytorch tutorial you linked to.
loss_fn = nn.MSELoss()
batch_size = 10
TIMESTEPS = 5
# Create some fake data
batch = torch.randn(batch_size, 50)
hidden = torch.zeros(batch_size, 20)
target = to... | https://stackoverflow.com/questions/51152658/ |
How do I install and run pytorch in MSVS2017 (to avoid "module not found" error on "import torch" statement)? | I'm trying to use pytorch in MSVS2017. I started a pytorch project, have anaconda environment set using python3.6, but when I run the debugger, I get a "module not found" error on the first import statement "import torch". I've tried various methods for installing pytorch in a way that allows MSVS2017 to use it, incl... | Probably, at the date of our MSVS2017 installation (esp. if prior to April 2018), there were no official .whl files for Windows pytorch (this has since changed). Also, given the default installation pathway, permissions on Windows (or file lock access) may be a problem (for example, when attempting to install to the "... | https://stackoverflow.com/questions/51173695/ |
GPU performing slower than CPU for Pytorch on Google Colaboratory | The GPU trains this network in about 16 seconds. The CPU in about 13 seconds. (I am uncommenting/commenting appropriate lines to do the test). Can anyone see what's wrong with my code or pytorch installation? (I have already checked that the GPU is available, and that there is sufficient memory available on the GPU.
f... | I see you're timing things you shouldn't be timing (definition of dtype, device, ...). What's interesting to time here is the creation of the input, output and weight tensors.
startTime = datetime.now()
# Create random Tensors to hold input and outputs.
x = torch.randn(N, D_in, device=device, dtype=dtype)
t = torch.ra... | https://stackoverflow.com/questions/51179133/ |
How to get the input and output channels in a CNN? | I am specifically looking at the AlexNet architecture found here:
https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py
I am confused as to how they are getting the input and output channels. Based on my readings of the AlexNet, I can't figure out where they are getting outputchannels = 64 from (a... | The 3 is the number of input channels (R, G, B). That 64 is the number of channels (i.e. feature maps) in the output of the first convolution operation. So, the first conv layer takes a color (RGB) image as input, applies 11x11 kernel with a stride 4, and outputs 64 feature maps.
I agree that this is different from th... | https://stackoverflow.com/questions/51180135/ |
Is it possible to see the read data of a pytorchtext.data.Tabulardataset? | train, test = data.TabularDataset.splits(path="./data/", train="train.csv",test="test.csv",format="csv",fields=[("Tweet",TEXT), ("Affect Dimension",LABEL)])
I have this code and want to evaluate, if the loaded data is correct or if it's using wrong columns for the actual text fields etc.
If my file has the columns "... | You can put any field name irrespective of what your file has. Also, I recommend NOT TO use white-spaces in the field names.
So, rename Affect Dimension to Affect_Dimension or anything convenient for you.
Then you can iterate over different fields like below to check the read data.
for i in train.Tweet:
print i
... | https://stackoverflow.com/questions/51183040/ |
(Single Layer) Perceptron in PyTorch, bad convergence | I'm trying to develop a simple single layer perceptron with PyTorch (v0.4.0) to classify AND boolean operation.
I want to develop it by using autograd to calculate gradient of weights and bias and then update them in a SGD manner.
The code is very simple and is the following:
# AND points and labels
data = torch.tens... | The equation you use to compute the plane
yr = (-1 / weights[1].item()) * (weights[0].item() * xr + bias.item())
is derived in the case where y_i = [+1, -1] and there is a sign function: it's computed by looking for the plane that separates positive and negative examples. This assumption is not valid anymore if you... | https://stackoverflow.com/questions/51198135/ |
PyTorch Linear Regression Issue | I am trying to implement a simple linear model in PyTorch that can be given x data and y data, and then trained to recognize the equation y = mx + b. However, whenever I try to test my model after training, it thinks that the equation is y= mx + 2b. I'll show my code, and hopefully someone will be able to spot an issue... | Your network does not learn long enough.
It gets a vector with 500 features to describe a single datum.
Your network has to map the big input of 500 features to an output including 500 values.
Your trainingdata is randomly created, not like your simple example, so I think you just have to train longer to fit your weig... | https://stackoverflow.com/questions/51198474/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.