instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
Differences in SciKit Learn, Keras, or Pytorch | Are these libraries fairly interchangeable?
Looking here, https://stackshare.io/stackups/keras-vs-pytorch-vs-scikit-learn, it seems the major difference is the underlying framework (at least for PyTorch).
| Yes, there is a major difference.
SciKit Learn is a general machine learning library, built on top of NumPy. It features a lot of machine learning algorithms such as support vector machines, random forests, as well as a lot of utilities for general pre- and postprocessing of data. It is not a neural network framework.... | https://stackoverflow.com/questions/54527439/ |
How to Tensorize loss of multiple 3D Keypoints | I have a tensor of ground truth values of 3D points of G=[18000x3], and an output from my network of the same size O=[18000x3].
I need to compute a loss so that I basically have the square root of the distance between each 3D point, summed over all keypoints and normalized over 18000. How do I write this efficiently?
| Just write the expression you propose using the vectorized operations provided by PyTorch. In this case
loss = (O - G).pow(2).sum(axis=1).sqrt().mean()
Check out pow, sum, sqrt and mean.
| https://stackoverflow.com/questions/54543595/ |
Need to change GPU option to CPU in a python pytorch based code | The code basically trains the usual MNIST image dataset but it does the training on a GPU. I need to change this option so the code trains the model using my laptop computer. I need to substitute the .cuda() at the second line for the equivalent in CPU.
I know there are many examples online on how to train neural net... | It is better to move up to latest pytorch (1.0.x).
With latest pytorch, it is more easy to manage "device".
Below is a simple example.
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
#Now send existing model to device.
model_ft = model_ft.to(device)
#Now send input to device and so on.
inputs... | https://stackoverflow.com/questions/54544986/ |
Element wise calculation breaks autograd | I am using pytorch to calculate loss for a logistic regression (I know pytorch can do this automatically but I have to make it myself). My function is defined below but the cast to torch.tensor breaks autograd and gives me w.grad = None. Im new to pytorch so Im sorry.
logistic_loss = lambda X,y,w: torch.tensor([tor... | Your post isn't very clear on details and this is a monster of a one-liner. I first reworked it to make a minimal, complete, verifiable example. Please correct me if I misunderstood your intentions and please do it yourself next time.
import torch
# unroll the one-liner to have an easier time understanding what's goi... | https://stackoverflow.com/questions/54546058/ |
Have I implemented implemenation of learning rate finder correctly? | Using implementation of lr_finder from https://github.com/davidtvs/pytorch-lr-finder based on paper https://arxiv.org/abs/1506.01186
Without the learning rate finder :
from __future__ import print_function, with_statement, division
import torch
from tqdm.autonotebook import tqdm
from torch.optim.lr_scheduler import ... | The code looks like it's using the implementation correctly. To answer your last question,
Can see the training accuracy is much lower 84.09833333333333 versus 9.93 . Should the learning rate finder find a learning rate that allows to achieve greater training set accuracy ?
Not really. A few points
You are usi... | https://stackoverflow.com/questions/54553388/ |
LSTM's expected hidden state dimensions doesn't take batch size into account | I have this decoder model, which is supposed to take batches of sentence embeddings (batchsize = 50, hidden size=300) as input and output a batch of one hot representation of predicted sentences:
class DecoderLSTMwithBatchSupport(nn.Module):
# Your code goes here
def __init__(self, embedding_size,batch... | When you create the LSTM, the flag batch_first is not necessary, because it assumes a different shape of your input. From the docs:
If True, then the input and output tensors are provided as (batch,
seq, feature). Default: False
change the LSTM creation to:
self.lstm = nn.LSTM(input_size=embedding_size, num_la... | https://stackoverflow.com/questions/54566209/ |
Result of auto-encoder dimensions are incorrect | Using below code I'm attempting to encode image from mnist into a lower dimension representation :
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib import pyplot as plt
from sklearn import metrics
import datetime
from sklearn.prep... | You have 60000 images in mnist and your batch = 100. That is why your len(encoded_images)=600 because you do 60000/100=600 iterations when generating encoded image. You end up with a list of 600 elements where each element has shape [100, 32]. You can do the following
encoded_images = torch.zeros(len(mnist), 32)
for ... | https://stackoverflow.com/questions/54568113/ |
Store weight updates for momemntum | I am trying to implement momentum in my implementation of SGD with momentum.
From my understanding this update look like this:
parameters -= (lr * (p.grad*0.1 + p_delta_prev*0.9))
My question is how I should store my previous deltas from every update
Here is what I have in my update function:
#we now want to do th... | Yes, it does store the parameter momenta in a dictionary, indexed by their names, as returned by model.named_parameters(). I don't know how to rigorously prove this, but I strongly believe it's impossible to apply momentum without using additional memory twice the size of your model.
That being said, I wouldn't worry,... | https://stackoverflow.com/questions/54578255/ |
How to reset Colab after the following CUDA error 'Cuda assert fails: device-side assert triggered'? | I'm running my Jupyter Notebook using Pytorch on Google Colab. After I received the 'Cuda assert fails: device-side assert triggered' I am unable to run any other code that uses my pytorch module. Does anyone know how to reset my code so that my Pytorch functions that were working before can still run?
I've already tr... | You need to reset the Colab notebook. To run existing Pytorch modules that used to work before, you have to do the following:
Go to 'Runtime' in the tool bar
Click 'Restart and Run all'
This will reset your CUDA assert and flush out the module so that you can have another shot at avoiding the error!
| https://stackoverflow.com/questions/54585685/ |
How to wrap PyTorch functions and implement autograd? | I'm working through the PyTorch tutorial on Defining new autograd functions. The autograd function I want to implement is a wrapper around torch.nn.functional.max_pool1d. Here is what I have so far:
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as tag
clas... | You have picked a rather unlucky example. torch.nn.functional.max_pool1d is not an instance of torch.autograd.Function, because it's a PyTorch built-in, defined in C++ code and with an autogenerated Python binding. I am not sure if it's possible to get the backward property via its interface.
Firstly, in case you have... | https://stackoverflow.com/questions/54586938/ |
Pytorch equivalent of Numpy's logical_and and kin? | Does Pytorch have an equivalent of Numpy's element-wise logical operators (logical_and, logical_or, logical_not, and logical_xor)? Calling the Numpy functions on Pytorch tensors seems to work well enough when using the CPU, even producing a Pytorch tensor as output. I mainly ask because I assume this would not work so ... | Update: With Pytorch 1.2, PyTorch introduced torch.bool datatype, which can be used using torch.BoolTensor:
>>> a = torch.BoolTensor([False, True, True, False]) # or pass [0, 1, 1, 0]
>>> b = torch.BoolTensor([True, True, False, False])
>>> a & b # logical and
tensor([False, True, Fa... | https://stackoverflow.com/questions/54590661/ |
Why/how can model.forward() succeed both on input being mini-batch vs single item? | Why and how does this work?
When I run the forward phase on input
being mini-batch tensor
or alternatively being a single input item
model.__call__() (which AFAIK is calling forward() ) swallows that and spills out adequate output (i.e. a tensor of mini-batch of estimates or a single item of estimate)
Adopting ... | The docs on nn.Linear state that
Input: (N,∗,in_features) where ∗ means any number of additional dimensions
so one would naturally expect that at least two dimensions are necessary. However, if we look under the hood we will see that Linear is implemented in terms of nn.functional.linear, which dispatches to torc... | https://stackoverflow.com/questions/54591124/ |
When to use learning rate finder | Reading the paper '
Cyclical Learning Rates for Training Neural Networks' https://arxiv.org/abs/1506.01186
Does it make sense to use the learning rate finder if the model is over-fitting ? Other than reduce the number of iterations before the model overfit's will using the learning finder prevent over-fitting ?
From ... | I don't think changing the learning rate reduces over-fit. To avoid over-fitting you might want to use L1/L2 regularization and drop-out or some of its variant.
| https://stackoverflow.com/questions/54607530/ |
"RuntimeError: Found 0 files in subfolders of ".. Error about subfolder in Pytorch | I'm based on Window 10, Jupyter Notebook, Pytorch 1.0, Python 3.6.x currently.
At first I confirm to the correct path of files using this code : print(os.listdir('./Dataset/images/')).
and I could check that this path is correct.
but I met Error :
RuntimeError: Found 0 files in subfolders of: ./Dataset/images/
... | Can you post the structure of your files? In your case, it is supposed to be:
img_dir
|_class1
|_a.jpg
|_b.jpg
|_class2
|_a.jpg
|_b.jpg
...
| https://stackoverflow.com/questions/54613573/ |
simple CNN model training using CIFAR-10 dataset STUCK at a low accuracy | Hi i have just learned to implement NN models in pytorch through the udacity course and thus created a simple model with a a few CNN and FC layers. after much struggle i got the model to work. but it seems that it is stuck at the same loss even after repeated executions. i dont know where i am going wrong. Must be some... | Since batch size is 1, use a lower learning rate like 1e-4 or increase the batch size.
I recommend making batch size 16 or larger though.
EDIT: To create a batch of data you can do something like this.
N = input.shape[0] #know the total size/samples in input
for i in range(n_epochs):
# this is to shuffle data
... | https://stackoverflow.com/questions/54621042/ |
Using a generator with pickled data in a Dataloader for PyTorch | I have done some preprocessing and feature selection before, and I have a pickle training input data that consists of list of lists, e.g. (but pickled)
[[1,5,45,13], [23,256,4,2], [1,12,88,78], [-1]]
[[12,45,77,325], [23,257,5,28], [3,7,48,178], [12,77,89,99]]
[[13,22,78,89], [12,33,97], [-1], [-1]]
[-1] is a paddin... | See my other answer for your options.
In short, you need to either preprocess each sample into separate files, or use a data format that does not need to be loaded fully into memory for reading.
| https://stackoverflow.com/questions/54621447/ |
PyTorch: accuracy of validation set greater than 100% during training | 1 ) Problem
I observe an odd behaviour during training where my validation-accuracy is above 100% right from the start.
Epoch 0/3
----------
100%|██████████| 194/194 [00:50<00:00, 3.82it/s]
train Loss: 1.8653 Acc: 0.4796
100%|██████████| 194/194 [00:32<00:00, 5.99it/s]
val Loss: 1.7611 Acc: 1.2939
Epoch 1/3
... | Your problem appears to be here:
class CustomDataset(Dataset):
def __init__(self, df, transform=None):
>>>>> self.dataframe = df_train
This should be
self.dataframe = df
In your case, you are inadvertently setting both the train and val CustomDataset to df_train ...
| https://stackoverflow.com/questions/54636288/ |
Torch Dataset Looping too far | Why does this dataset try to iterate past the final element
from torch.utils.data.dataset import Dataset
class DumbDataset(Dataset):
def __init__(self, dct):
self.dct = dct
self.mapping = dict(enumerate(dct))
def __getitem__(self, index):
return self.dct[self.mapping[index]]
def __... | The reason why your code raises KeyError is that Dataset does not implement __iter__() and thus when used in a for-loop Python falls back to starting at index 0 and calling __getitem__ until IndexError is raised, as discussed here. You can modify DumbDataset to work like this by having it raise an IndexError when the i... | https://stackoverflow.com/questions/54640906/ |
How to combine/stack tensors and combine dimensions in PyTorch? | I need to combine 4 tensors, representing greyscale images, of size [1,84,84], into a stack of shape [4,84,84], representing four greyscale images with each image represented as a "channel" in tensor style CxWxH.
I am using PyTorch.
I've tried using torch.stack and torch.cat but if one of these is the solution, I am ... | It seems you have misunderstood what torch.tensor([1, 84, 84]) is doing. Let's take a look:
torch.tensor([1, 84, 84])
print(x, x.shape) #tensor([ 1, 84, 84]) torch.Size([3])
You can see from the example above, it gives you a tensor with only one dimension.
From your problem statement, you need a tensor of shape [1,... | https://stackoverflow.com/questions/54643076/ |
Training (DC)GAN, D(G(z)) goes to 0.5 while D(x) stays 0.9 and G(z) becomes corrupt | I'm currently training a DCGAN for 1x32x32 (channel, height, width) images.
Quite soon in training G(z) becomes reasonably realistic apart from a problem with the 'chessboard' artifacts being visible, but this should go away after lots of training?
However, after a long training session D(G(z)) goes to 0.5000 (and no l... | Solved the problem by switching to WGAN-GP (https://arxiv.org/abs/1704.00028).
Turns out it is more stable while training.
| https://stackoverflow.com/questions/54647599/ |
How to set gradients to Zero without optimizer? | Between mutliple .backward() passes I'd like to set the gradients to zero. Right now I have to do this for every component seperately (here these are x and t), is there a way to do this "globally" for all affected variables? (I imagine something like z.set_all_gradients_to_zero().)
I know there is optimizer.zero_gra... | You can also use nn.Module.zero_grad(). In fact, optim.zero_grad() just calls nn.Module.zero_grad() on all parameters which were passed to it.
There is no reasonable way to do it globally. You can collect your variables in a list
grad_vars = [x, t]
for var in grad_vars:
var.grad = None
or create some hacky functio... | https://stackoverflow.com/questions/54648053/ |
pytorch torch.jit.trace returns function instead of torch.jit.ScriptModule | I need to run in c++ a pre-trained pytorch nn model (trained in python) to make predictions.
To do so, I'm following the instructions on how to load a pytorch model in c++ given here: https://pytorch.org/tutorials/advanced/cpp_export.html
But when I try to get the torch.jit.ScriptModule via tracing as stated in the f... | Thanks for asking Jatentaki. I was using PyTorch 0.4 in Python and when I updated to 1.0 it worked.
| https://stackoverflow.com/questions/54650423/ |
Expected input to torch Embedding layer with pre_trained vectors from gensim | I would like to use pre-trained embeddings in my neural network architecture. The pre-trained embeddings are trained by gensim. I found this informative answer which indicates that we can load pre_trained models like so:
import gensim
from torch import nn
model = gensim.models.KeyedVectors.load_word2vec_format('path/... | The documentation says the following
This module is often used to store word embeddings and retrieve them using indices. The input to the module is a list of indices, and the output is the corresponding word embeddings.
So if you want to feed in a sentence, you give a LongTensor of indices, each corresponding to ... | https://stackoverflow.com/questions/54655604/ |
how to load images data into pytorch dataLoader? | i am new to deep learning I want to use an algorithm written by pytorch, the example in pytorch tutorial is very specific . i have dataset in my Pc and i want to preprocess them .
thanks
| class Get_Dataset( Dataset ):
def __init__ (self) : #intital function define all member and class variables
super(Get_Dataset , self).__init__()
scale = 255
path = '/home/singhv/data/train/'
trainA = os.listdir(path + 'image')
trainB = os.listdir(path + 'mask')
self... | https://stackoverflow.com/questions/54658108/ |
Under macOS using pip install pytorch failure | When I'm using pip to install pytorch, some exception appeared.
Env:
Sys: MaxOS High Sierra
python version : 3.6
pip version : 19.0.2
input: pip install pytorch
output:
Collecting pytorch
Using cached https://files.pythonhosted.org/packages/a9/41/4487bc23e3ac4d674943176f5aa309427b011e00607eb98899e9d951f6... | You're installing an old package named pytorch on PyPI i.e. pytorch 0.1.2. That's why you're receiving the exception.
You're supposed to install it from the pytorch website. There you'll an option to select your system configuration, it'll give you the command to install it. Also, the latest version of pytorch is name... | https://stackoverflow.com/questions/54662230/ |
Confused about torch.nn.Sequential | Supposing we want to add a new layer, say a linear layer, to the end of the classifier of another model, such as VGG16, why exactly do these two implementations lead to different results? More specifically, I don't understand why the first implementation produces 2 classfiers:
vgg = torchvision.models.vgg16(pretrained... | It's because you have a syntax error in the spelling of classifier. You have written it as
vgg.classifer=nn.Sequential(vgg.classifier, nn.Linear(4096,300))
Note the missing i after f in classifier on LHS. So, you're inadvertently creating a new group of layers named classifer by this line.
After correction:
vgg.... | https://stackoverflow.com/questions/54662346/ |
Pytorch: Why loss functions are implemented both in nn.modules.loss and nn.functional module? | Many loss functions in Pytorch are implemented both in nn.modules.loss and nn.functional.
For example, the two lines of the below return same results.
import torch.nn as nn
import torch.functional as F
nn.L1Loss()(x,y)
F.l1_loss(x,y)
Why are there two implementations?
Consistency for other parametric loss functio... | I think of it as of a partial application situation - it's useful to be able to "bundle" many of the configuration variables with the loss function object. In most cases, your loss function has to take prediction and ground_truth as its arguments. This makes for a fairly uniform basic API of loss functions. However, th... | https://stackoverflow.com/questions/54662984/ |
How to give a batch of frames to the model in pytorch c++ api? | I've written a code to load the pytorch model in C++ with help of the PyTorch C++ Frontend api. I want to give a batch of frames to a pretrained model in the C++ by using module->forward(batch_frames). But it can forward through a single input.
How can I give a batch of inputs to the model?
A part of code that I w... | Finally, I used a function in c++ to concatenate images and make a batch of images. Then convert the batch into the torch::tensor and feed the model using the batch. A part of code is given below:
// cat 2 or more images to make a batch
cv::Mat batch_image;
cv::vconcat(image_2, images_1, batch_image);
// do some pre-p... | https://stackoverflow.com/questions/54665137/ |
pytorch: How does loss behave when coming from two networks? | I am trying to implement the following algorithm in this book, section 13.5, in pytorch.
This would require two separate neural networks, (in this question, model1 and model2). One's loss is dependent only on its own output [via delta] (parameterized by w), the other (parameterized by theta), dependent both on its o... | since optim2 has only model2's parameter it will only update model2 if you do optim2.step() as is being done.
However, loss2.backward() will compute gradients for both model1 and model2's params and if you do optim1.step() after that it will update model1's params. If you don't want to compute gradients for model1's p... | https://stackoverflow.com/questions/54677774/ |
Pytorch ValueError: optimizer got an empty parameter list | When trying to create a neural network and optimize it using Pytorch, I am getting
ValueError: optimizer got an empty parameter list
Here is the code.
import torch.nn as nn
import torch.nn.functional as F
from os.path import dirname
from os import getcwd
from os.path import realpath
from sys import argv
class NetAct... | Your NetActor does not directly store any nn.Parameter. Moreover, all other layers it eventually uses in forward are stored as a simple list in self.nn_layers.
If you want self.actor_nn.parameters() to know that the items stored in the list self.nn_layers may contain trainable parameters, you should work with container... | https://stackoverflow.com/questions/54678896/ |
How to find the max index for each row in a tensor object? | So I'm creating a pytorch model and for the forward pass, I'm applying my forward pass method to get the scores tensor which contains the prediction scores for each class. The shape of this tensor is [100, 10]. Now, I want to get the accuracy by comparing it to y which contains the actual scores. This tensor has the sh... | Use argmax with desired dim (a.k.a. axis)
a = tensor(
[[0.3232, -0.2321, 0.2332, -0.1231, 0.2435, 0.6728],
[0.2323, -0.1231, -0.5321, -0.1452, 0.5435, 0.1722],
[0.9823, -0.1321, -0.6433, 0.1231, 0.023, 0.0711]]
)
a.argmax(1)
# tensor([ 5, 4, 0])
| https://stackoverflow.com/questions/54681798/ |
requires_grad of params is True even with torch.no_grad() | I am experiencing a strange problem with PyTorch today.
When checking network parameters in the with scope, I am expecting requires_grad to be False, but apparently this is not the case unless I explicitly set all params myself.
Code
Link to Net -> Gist
net = InceptionResnetV2()
with torch.no_grad():
for name... | torch.no_grad() will disable gradient information for the results of operations involving tensors that have their requires_grad set to True. So consider the following:
import torch
net = torch.nn.Linear(4, 3)
input_t = torch.randn(4)
with torch.no_grad():
for name, param in net.named_parameters():
prin... | https://stackoverflow.com/questions/54682457/ |
PyTorch VAE fails conversion to onnx | I'm trying to convert a PyTorch VAE to onnx, but I'm getting: torch.onnx.symbolic.normal does not exist
The problem appears to originate from a reparametrize() function:
def reparametrize(self, mu, logvar):
std = logvar.mul(0.5).exp_()
if self.have_cuda:
eps = torch.normal(torch.zero... | In very short, the code bellow may work. (at least in my environment, it worked w/o errors).
It seems that .size() operator might return variable, not constant, so it causes error for onnx compilation. (I got the same error when changed to use .size())
import torch
import torch.utils.data
from torch import nn
from to... | https://stackoverflow.com/questions/54699201/ |
Moving member tensors with module.to() in PyTorch | I am building a Variational Autoencoder (VAE) in PyTorch and have a problem writing device agnostic code. The Autoencoder is a child of nn.Module with an encoder and decoder network, which are too. All weights of the network can be moved from one device to another by calling net.to(device).
The problem I have is with ... | A better version of tilman151's second approach is probably to override _apply, rather than to. That way net.cuda(), net.float(), etc will all work as well, since those all call _apply rather than to (as can be seen in the source, which is simpler than you might think):
def _apply(self, fn):
super(VariationalGener... | https://stackoverflow.com/questions/54706146/ |
Add channel to MNIST via transform? | I'm trying to use the MNIST dataset from torchvision.datasets.It seems to be provided as an N x H x W (uint8) (batch dimension, height, width) tensor. All the pytorch classes for working on images (for instance Conv2d) however require a N x C x H x W (float32) tensor where C is the number of colour channels. I've tried... | I had a misconception: dataset.train_data is not affected by the specified transform, only the output of a DataLoader(dataset,...) will be. After checking data from
for data, _ in DataLoader(dataset):
break
we can see that ToTensor actually does exactly what is desired.
| https://stackoverflow.com/questions/54707186/ |
How to do gradient clipping in pytorch? | What is the correct way to perform gradient clipping in pytorch?
I have an exploding gradients problem.
| clip_grad_norm (which is actually deprecated in favor of clip_grad_norm_ following the more consistent syntax of a trailing _ when in-place modification is performed) clips the norm of the overall gradient by concatenating all parameters passed to the function, as can be seen from the documentation:
The norm is comput... | https://stackoverflow.com/questions/54716377/ |
PyTorch: What does @weak_script_method decorator do? | In the torch.nn.Linear class (and other classes too), the forward method includes a @weak_script_method decorator as follows:
@weak_script_method
def forward(self, input):
return F.linear(input, self.weight, self.bias)
What does this decorator do? Should I include it if I'm overriding the forward method in my o... | You can find the exact decorator location to get the idea.
def weak_script_method(fn):
weak_script_methods[fn] = {
"rcb": createResolutionCallback(frames_up=2),
"original_method": fn
}
return fn
But, you shouldn't need to worry about that decorator. This decorator is internal to JIT.
Technic... | https://stackoverflow.com/questions/54718027/ |
CoreML: creating a custom layer for ONNX RandomNormal | I've trainined a VAE that in PyTorch that I need to convert to CoreML. From this thread PyTorch VAE fails conversion to onnx I was able to get the ONNX model to export, however, this just pushed the problem one step further to the ONNX-CoreML stage.
The original function that contains the torch.randn() call is the rep... | To add an input to your Core ML model, you can do the following from Python:
import coremltools
spec = coremltools.utils.load_spec("YourModel.mlmodel")
nn = spec.neuralNetworkClassifier # or just spec.neuralNetwork
layers = {l.name:i for i,l in enumerate(nn.layers)}
layer_idx = layers["your_custom_layer"]
layer = n... | https://stackoverflow.com/questions/54718662/ |
Activation gradient penalty | Here's a simple neural network, where I’m trying to penalize the norm of activation gradients:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 32, kernel_size=5)
self.conv2 = nn.Conv2d(32, 64, kernel_size=5)
self.pool = nn.MaxPool2d(2,... | I think your code ends up computing some of the gradients twice in each step. I also suspect it actually never zeroes out the activation gradients, so they accumulate across steps.
In general:
x.backward() computes gradient of x wrt. computation graph leaves (e.g. weight tensors and other variables), as well as wrt.... | https://stackoverflow.com/questions/54727099/ |
My numpy and pytorch codes have totally different results | I wanted to calculate the sum of 1st to K-th power of an array and equally calculate the sum of 1st to k-th power of a tensor. I found out that the following codes and their results are totally different and I don't know why.
I debugged the code and I know that the results are equal in the first round.
Numpy code:
a... | The problem was in using assignment. I should have used .clone() for pytorch and .copy() in numpy.
| https://stackoverflow.com/questions/54727465/ |
Concat tensors in PyTorch | I have a tensor called data of the shape [128, 4, 150, 150] where 128 is the batch size, 4 is the number of channels, and the last 2 dimensions are height and width. I have another tensor called fake of the shape [128, 1, 150, 150].
I want to drop the last list/array from the 2nd dimension of data; the shape of data w... | You could also just assign to that particular dimension.
orig = torch.randint(low=0, high=10, size=(2,3,2,2))
fake = torch.randint(low=111, high=119, size=(2,1,2,2))
orig[:,[2],:,:] = fake
Original Before
tensor([[[[0, 1],
[8, 0]],
[[4, 9],
[6, 1]],
[[8, 2],
[7, 6]]],
[[[1, 1],
... | https://stackoverflow.com/questions/54727686/ |
Calculating Variance in Pytorch on Spatial axis | I am trying to calculate variance in Pytorch but unable to do on multiple axis.
I have similar thing done in Tensorflow but unable to do it on Pytorch as torch.var function takes int as dimension instead of axes.
Below code is channel last code, I expect axes=[2,3]
Lambda(lambda x: tf.nn.moments(x, axes=[1, 2]))
F... | One thing you can do is to use tensor.view() to flatten all the dimensions that you want to calculate the variance for into one dimension before you apply the var() method:
torch.var(x.view(x.shape[0], x.shape[1], 1, -1,), dim=3, keepdim=True)
I used keepdim=True to keep the dimension that we calculate the variance f... | https://stackoverflow.com/questions/54732466/ |
Pytorch: How to create an update rule that doesn't come from derivatives? | I want to implement the following algorithm, taken from this book, section 13.6:
I don't understand how to implement the update rule in pytorch (the rule for w is quite similar to that of theta).
As far as I know, torch requires a loss for loss.backwward().
This form does not seem to apply for the quoted algorithm... | I am gonna give this a try.
.backward() does not need a loss function, it just needs a differentiable scalar output. It approximates a gradient with respect to the model parameters. Let's just look at the first case the update for the value function.
We have one gradient appearing for v, we can approximate this grad... | https://stackoverflow.com/questions/54734556/ |
Column-dependent bounds in torch.clamp | I would like to do something similar to np.clip on PyTorch tensors on a 2D array. More specifically, I would like to clip each column in a specific range of value (column-dependent). For example, in numpy, you could do:
x = np.array([-1,10,3])
low = np.array([0,0,1])
high = np.array([2,5,4])
clipped_x = np.clip(x, low... | Not as neat as np.clip, but you can use torch.max and torch.min:
In [1]: x
Out[1]:
tensor([[0.9752, 0.5587, 0.0972],
[0.9534, 0.2731, 0.6953]])
Setting the lower and upper bound per column
l = torch.tensor([[0.2, 0.3, 0.]])
u = torch.tensor([[0.8, 1., 0.65]])
Note that the lower bound l and upper bound u ... | https://stackoverflow.com/questions/54738045/ |
PyTorch: What's the difference between state_dict and parameters()? | In order to access a model's parameters in pytorch, I saw two methods:
using state_dict and using parameters()
I wonder what's the difference, or if one is good practice and the other is bad practice.
Thanks
| The parameters() only gives the module parameters i.e. weights and biases.
Returns an iterator over module parameters.
You can check the list of the parameters as follows:
for name, param in model.named_parameters():
if param.requires_grad:
print(name)
On the other hand, state_dict returns a dicti... | https://stackoverflow.com/questions/54746829/ |
Input dimension error on pytorch's forward check | I am creating an RNN with pytorch, it looks like this:
class MyRNN(nn.Module):
def __init__(self, batch_size, n_inputs, n_neurons, n_outputs):
super(MyRNN, self).__init__()
self.n_neurons = n_neurons
self.batch_size = batch_size
self.n_inputs = n_inputs
self.n_outputs = n_o... | You are missing one of the required dimensions for the RNN layer.
Per the documentation, your input size needs to be of shape (sequence length, batch, input size).
So - with the example above, you are missing one of these. Based on your variable names, it appears you are trying to pass 64 examples of 15 inputs each.... | https://stackoverflow.com/questions/54749244/ |
Stacking up of LSTM outputs in pytorch | I was going through some tutorial about the sentiment analysis using lstm network.
The below code said that its stacks up the lstm output. I Don't know how it works.
lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim)
| It indeed stacks the output, the comment by kHarshit is misleading here!
To visualize this, let us review the output of the previous line in the tutorial (accessed May 1st, 2019):
lstm_out, hidden = self.lstm(embeds, hidden)
The output dimension of this will be [sequence_length, batch_size, hidden_size*2], as per t... | https://stackoverflow.com/questions/54749665/ |
How does Module.parameters() find the parameters? | I noticed that whenever you create a new net extending torch.nn.Module, you can immediately call net.parameters() to find the parameters relevant for backpropagation.
import torch
class MyNet(torch.nn.Module):
def __init__(self):
super(MyNet, self).__init__()
self.fc = torch.nn.Linear(5, 5)
d... | It's simple really, just go through attributes via meta-programming and check their type
class Example():
def __init__(self):
self.special_thing = nn.Parameter(torch.rand(2))
self.something_else = "ok"
def get_parameters(self):
for key, value in self.__dict__.items():
if ty... | https://stackoverflow.com/questions/54751318/ |
Autograd.grad() for Tensor in pytorch | I want to compute the gradient between two tensors in a net. The input X tensor (batch size x m) is sent through a set of convolutional layers which give me back and output Y tensor(batch size x n).
I’m creating a new loss and I would like to know the gradient of Y w.r.t. X. Something that in tensorflow would be like:
... |
Let's start from simple working example with plain loss function and regular backward. We will build short computational graph and do some grad computations on it.
Code:
import torch
from torch.autograd import grad
import torch.nn as nn
# Create some dummy data.
x = torch.ones(2, 2, requires_grad=True)
gt = torch.... | https://stackoverflow.com/questions/54754153/ |
Using autograd.grad() as a parameter for a loss function (pytorch) | I want to compute the gradient between two tensors in a net. The input X tensor is sent through a set of convolutional layers which give me back and output Y tensor.
I’m creating a new loss and I would like to know the MSE between gradient of norm(Y) w.r.t. each element of X. Here the code:
# Staring tensors
X = tor... | You are receiving mentioned error because you are trying to feed a slice of tensor X: X[i] to grad(), and it is going to be considered as a separate tensor, outside of your main computational graph. Not sure, but seems it returns new tensor while performing slicing.
But you don't need a for loop to compute gradients:
... | https://stackoverflow.com/questions/54763081/ |
Why aren't torch.nn.Parameter listed when net is printed? | I recently had to construct a module that required a tensor to be included. While back propagation worked perfectly using torch.nn.Parameter, it did not show up when printing the net object. Why isn't this parameter included in contrast to other modules like layer? (Shouldn't it behave just like layer?)
import torch
i... | When you call print(net), the __repr__ method is called. __repr__ gives the “official” string representation of an object.
In PyTorch's nn.Module (base class of your MyNet model), the __repr__ is implemented like this:
def __repr__(self):
# We treat the extra repr like the sub-module, one item per line
... | https://stackoverflow.com/questions/54770249/ |
How to upscale image in pytorch? | how to upscale an image in Pytorch without defining height and width using transforms?
('--upscale_factor', type=int, required=True, help="super resolution upscale factor")
| This might do the Job
transforms.Compose([transforms.resize(ImageSize*Scaling_Factor)])
| https://stackoverflow.com/questions/54771426/ |
Simple way to load specific sample using Pytorch dataloader | I am currently training a 3D CNN for binary classification with relatively sparse labels (~ 1% of voxels in label data correspond to target class).
In order to perform basic sanity checks during the training (e.g. does the network learn at all?) it would be handy to present the network with a small, handpicked subset... | Just in case anyone with a similar question comes across this at some point:
The quick-and-dirty workaround I ended up using was to bypass the dataloader in the training loop by directly accessing it's associated dataset attribute. Suppose we want to quickly check if our network learns at all by repeatedly presenting ... | https://stackoverflow.com/questions/54773106/ |
How to change default optimization in spotlight from pytorch e.g. torch.optim.SGD? | I'm currently using spotlight https://github.com/maciejkula/spotlight/tree/master/spotlight
to implement Matrix Factorization in recommender system. spotlight is based on pytorch, it's a integrated platform implementing RS. In spotlight/factorization/explicit, it uses torch.optim.Adam as optimizer, I want to change it ... | You could use partial from functools to first set the learning rate and momentum and then pass this class to ExplicitFactorizationModel. Something like:
from functools import partial
SDG_fix_lr_momentum = partial(torch.optim.SGD, lr=0.001, momentum=0.9)
emodel = ExplicitFactorizationModel(n_iter=15,
... | https://stackoverflow.com/questions/54775494/ |
Does pytorch do eager pruning of its computational graph? | This is a very simple example:
import torch
x = torch.tensor([1., 2., 3., 4., 5.], requires_grad=True)
y = torch.tensor([2., 2., 2., 2., 2.], requires_grad=True)
z = torch.tensor([1., 1., 0., 0., 0.], requires_grad=True)
s = torch.sum(x * y * z)
s.backward()
print(x.grad)
This will print,
tensor([2., 2., 0., 0.,... | No, pytorch does no such thing as pruning any subsequent calculations when zero is reached. Even worse, due to how float arithmetic works all subsequent multiplication by zero will take roughly the same time as any regular multiplication.
For some cases there are ways around it though, for example if you want to use a... | https://stackoverflow.com/questions/54781966/ |
What kind of tricks we can play with to further refine the trained neural network model so that it has lower objective function value? | I ask this question because many deep learning frameworks, such as Caffe, supports model refining function. For example, in Caffe, we can use snapshot to initialling the neural network parameters and then continue performing training as the following command shows:
./caffe train -solver solver_file.prototxt -snapshot ... | The question is way too broad, I think. However, this is a common practice, especially in case of a small training set. I would rank possible methods like this:
smaller learning rate
more/different data augmentation
add noise to train set (related to data augmentation, indeed)
fine-tune on subset of the training set.... | https://stackoverflow.com/questions/54789401/ |
Selecting second dim of tensor using an index tensor | I have a 2D tensor and an index tensor. The 2D tensor has a batch dimension, and a dimension with 3 values. I have an index tensor that selects exactly 1 element of the 3 values. What is the "best" way to product a slice containing just the elements in the index tensor?
t = torch.tensor([[1,2,3], [4,5,6], [7,8,9]])... | An example of the answer is as follows.
import torch
t = torch.tensor([[1,2,3], [4,5,6], [7,8,9]])
col_i = [0, 0, 1]
row_i = range(3)
print(t[row_i, col_i])
# tensor([1, 4, 8])
| https://stackoverflow.com/questions/54799650/ |
Pytorch resumes training after every training session | I have a dataset which is partitioned into smaller datasets.
I want to train 3 models for each partition of the dataset, but I need all training sessions to start from the same initialised network parameters.
so it looks like this:
modelList = []
thisCNN = NNet()
for x in range(3):
train = torch.utils.data.Da... | When you call bb = trainMyNet(thisCNN, train, test) you are not taking a copy of thisCNN, but it is the same model you are updating in each iteration. To get your code working you should probably pass a copy of this model:
from copy import deepcopy
modelList = []
thisCNN = NNet()
for x in range(3):
train = to... | https://stackoverflow.com/questions/54808117/ |
PyTorch version of as simple Keras LSTM model | Trying to translate a simple LSTM model in Keras to PyTorch code. The Keras model converges after just 200 epochs, while the PyTorch model:
needs many more epochs to reach the same loss level (200 vs. ~8000)
seems to overfit the inputs because the predicted value is not near 100
This is the Keras code:
from numpy ... | The behaviour difference is because of the activation function in the LSTM API. By changing the activation to tanh, I can reproduce the problem in Keras too.
model.add(LSTM(50, activation='tanh', recurrent_activation='sigmoid', input_shape=(3, 1)))
There is no option to change the activation function to 'relu' in th... | https://stackoverflow.com/questions/54815899/ |
pytorch 0.4.1 - ‘LSTM’ object has no attribute ‘weight_ih_l’ | Simple question. I’d like to see the initialized parameter of LSTM. How do I see it?
Do I need to always put lstm in the model to see the params?
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
torch.manual_seed(1)
torch.__version__
lstm = nn.LSTM(3, 3)
lstm.weigh... | nn.LSTM is implemented with nn.RNNBase which puts all the parameters inside the OrderedDict: _parameters. So to 'see' the initialized parameters, you can simply do:
import torch
torch.manual_seed(1)
import torch.nn as nn
lstm = nn.LSTM(3, 3)
print(lstm._parameters['weight_ih_l0'])
Also, to know what are the keys ... | https://stackoverflow.com/questions/54817864/ |
tensorflow equivalent of pytorch ReplicationPad2d | I'm trying to figure out how to do the tensorflow equivalent of the following padding in pytorch:
nn.ReplicationPad2d((1, 0, 1, 0))
I've tried the following, but this only seems to work if the input tensor is actually 2x2:
tf.pad(my_tensor, [[1, 0], [1, 0]], "SYMMETRIC")
| The equivalent for Tensorflow is tf.pad(my_tensor,[[0,0],[0,0],[1,0],[1,0]],"SYMMETRIC"). (This assumes that you are interested in operating on 4D tensors, with the first two dimensions being batch and channel).
In Tensorflow, you need to explicitly give the padding for all of the four dimensions. If you don't want t... | https://stackoverflow.com/questions/54818515/ |
RNN model (GRU) of word2vec to regression not learning | I am converting Keras code into PyTorch because I am more familiar with the latter than the former. However, I found that it is not learning (or only barely).
Below I have provided almost all of my PyTorch code, including the initialisation code so that you can try it out yourself. The only thing you would need to pro... | TL;DR: Use permute instead of view when swapping axes, see the end of answer to get an intuition about the difference.
About RegressorNet (neural network model)
No need to freeze embedding layer if you are using from_pretrained. As documentation states, it does not use gradient updates.
This part:
self.w2v_rnode = ... | https://stackoverflow.com/questions/54824768/ |
Compute maxima and minima of a 4D tensor in PyTorch | Suppose that we have a 4-dimensional tensor, for instance
import torch
X = torch.rand(2, 3, 4, 4)
tensor([[[[-0.9951, 1.6668, 1.3140, 1.4274],
[ 0... | Just calculate the max for both dimensions sequentially, it gives the same result:
tup = (2,3)
for dim in tup:
X = torch.max(X,dim=dim,keepdim=True)[0]
| https://stackoverflow.com/questions/54833289/ |
Given list of image filenames for eachset,Split large dataset to train/valid/test directories? | I am trying to split a large dataset into train/valid/test sets from Food101 dataset for image classification
and the structure of a dataset is like this and has all images in one folder
'',
'Structure:',
'----------',
'pec/',
' images/',
' <class_name>/',
' <image_id>.jpg',
' me... | It seems i have been going all wrong about the solution, i need not move the images all i need to change is path to images in the required format through os module
Below is the code for doing it. Say you have list of filenames in valid list
#for valid set
v = valid.reshape(15150,)
or_fpath = '/content/food-101/im... | https://stackoverflow.com/questions/54838339/ |
Import error on Windows10 with pytorch0.4 | Discription
I am trying to install pytorch 0.4 on Windows10.
My enviroment settings:
- Windows10
- cuda9.0
- python 3.6
- pytorch 0.4
- anaconda
I tried by using both conda install -n myenv and pip install $path:whl and both failed.
Error
>>> import torch
Traceback (most recent call last):
File "<std... | After you create the new environment with conda, execute conda install -c pytorch pytorch to install pytorch.
pip does not work that well with external, non-Python dependencies. Not unlikely in your case path to the DLL is not set correctly (just a guess).
| https://stackoverflow.com/questions/54839446/ |
No module named "Torch" | I successfully installed pytorch via conda:
conda install pytorch-cpu torchvision-cpu -c pytorch
I also successfully installed pytorch via pip:
pip3 install https://download.pytorch.org/whl/cpu/torch-1.0.1-cp36-cp36m-win_amd64.whl
pip3 install torchvision
But, it only works in a jupyter notebook. Whenever I try to ex... | Try to install PyTorch using pip:
First create a Conda environment using:
conda create -n env_pytorch python=3.6
Activate the environment using:
conda activate env_pytorch
Now install PyTorch using pip:
pip install torchvision
Note: This will install both torch and torchvision.
Now go to Python shell and im... | https://stackoverflow.com/questions/54843067/ |
PyTorch get all layers of model | What's the easiest way to take a pytorch model and get a list of all the layers without any nn.Sequence groupings? For example, a better way to do this?
import pretrainedmodels
def unwrap_model(model):
for i in children(model):
if isinstance(i, nn.Sequential): unwrap_model(i)
else: l.append(i)
mod... | You can iterate over all modules of a model (including those inside each Sequential) with the modules() method. Here's a simple example:
>>> model = nn.Sequential(nn.Linear(2, 2),
nn.ReLU(),
nn.Sequential(nn.Linear(2, 1),
nn.Sigmoid... | https://stackoverflow.com/questions/54846905/ |
element 0 of tensors does not require grad and does not have a grad_fn | I am trying to apply reiforcement learning mechanism to classification tasks.
I know it is useless thing to do because deep learning can overperform rl in the tasks. Anyway in research purposes I am doing.
I reward agent if he's correct positive 1 or not negative -1
and computate loss FUNC with predicted_action(predic... | action is produced by the argmax funtion, which is not differentiable. You instead want take the loss between the reward and the responsible probability for the action taken.
Often, the "loss" chosen for the policy in reinfocement learning is the so called score function:
Which is the product of the log of the respo... | https://stackoverflow.com/questions/54849812/ |
List not populated correctly unless use PyTorch clone() | I'm attempting to add the final weights of each trained model to a list using below code :
%reset -f
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.utils.... |
First of all, I am going to reproduce your case. I will use very simple model:
Code:
import torch
import torch.nn as nn
import torch.optim as optim
torch.manual_seed(42)
# Some dummy data:
X = torch.randn(100, 5, requires_grad=True, dtype=torch.float)
Y = torch.randn(100, 5, requires_grad=True, dtype=torch.float)
... | https://stackoverflow.com/questions/54852644/ |
Equal output values given for Multiclass Classification | I'm trying to build a CNN for predicting the number of fingers in an image, using PyTorch. The network:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.Layer1 = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=16, kernel_size=(3, 3)),
nn.ReLU(),
... | If you are using CrossEntropyLoss, you don't need to use Softmax in your forward. It is already included to CrossEntropyLoss, so you need the "raw" output. But, if you need Softmax during inference time, use NLLLoss + 'Softmax' instead.
You can find more info here
| https://stackoverflow.com/questions/54853225/ |
'ToPILImage' object has no attribute 'show' | I'm doing an image processing task and I want to concat two sites of pictures. For concatting, I first converted the image to tensor, then converted the tensor to a PIL image to display it, but it was reported incorrectly.Could someone please help me?
Here is my code:
import skimage.io as io
import torch
from torchvis... | The ToPILImage method accepts a tensor or an ndarray as input, source.
You will need to cast a single image tensor to the ToPILImage method. From your post, I suspect you are passing batches of image tensor instead of one, hence the error.
Assumed if you want to visualize image from tensor c,
img = transforms.ToPI... | https://stackoverflow.com/questions/54862480/ |
Deal with negative values resulting from my nn model | I have a simple nn model that looks like this
class TestRNN(nn.Module):
def __init__(self, batch_size, n_steps, n_inputs, n_neurons, n_outputs):
super(TestRNN, self).__init__()
...
self.basic_rnn = nn.RNN(self.n_inputs, self.n_neurons)
self.FC = nn.Linear(self.n_neurons, self.n_outp... | TL;DR
You have two options:
Make the second dimension of outputs be of size 2 instead of 1.
Use nn.BCEWithLogitsLoss instead of nn.CrossEntropyLoss
I think that the problem is not the negative numbers. It is the shape of outputs.
Looking at your array y, I see that you have 2 different classes (maybe even more,... | https://stackoverflow.com/questions/54870863/ |
How to install torch audio on Windows 10 conda? | In Anaconda Python 3.6.7 with PyTorch installed, on Windows 10, I do this sequence:
conda install -c conda-forge librosa
conda install -c groakat sox
then in a fresh download from https://github.com/pytorch/audio I do
python setup.py install
and it runs for a while and ends like this:
torchaudio/torch_sox.cpp(3)... | I managed to compile torchaudio with sox in Windows 10, but is a bit tricky.
Unfortunately the sox_effects are not usable, this error shows up:
RuntimeError: Error opening output memstream/temporary file
But you can use the other torchaudio functionalities.
The steps I followed for Windows 10 64bit are:
TORCHAUDIO... | https://stackoverflow.com/questions/54872876/ |
How can I use pytorch pre-trained model without installing pytorch? | I only want to use pre-trained model in pytorch without installing the whole package.
Can I just copy the model module from pytorch?
| I'm afraid you cannot do that: in order to run the model, you need not only the trained weights ('.pth.tar' file) but also the "structure" of the net: that is, the layers, how they are connected to each other etc. This network structure is coded in python and requires pytorch to be installed.
| https://stackoverflow.com/questions/54880783/ |
How to to drop a specific labeled pixels in semantic segmentation | I am new to semantic segmentation. I used the FCN to train my dataset. In the data set there are some pixels for the unknown class. I would like to exclude this class from my loss. So I defined a weight based on the class distribution of whole dataset and set the weight for the unknown class to zero as following. But I... | For semantic segmentation you have 2 "special" labels: the one is "background" (usually 0), and the other one is "ignore" (usually 255 or -1).
"Background" is like all other semantic labels meaning "I know this pixel does not belong to any of the semantic categories I am working with". It is important for your mode... | https://stackoverflow.com/questions/54887933/ |
TextLMDataBunch Memory issue Language Model Fastai | I have a dataset with 45 million rows of data. I have three 6gb ram gpu. I am trying to train a language model on the data.
For that, I am trying to load the data as the fastai data bunch. But this part always fails because of the memory issue.
data_lm = TextLMDataBunch.from_df('./', train_df=df_trn,
valid_df=df_va... | When you use this function, your Dataframe is loaded in memory. Since you have a very big dataframe, this causes your memory error. Fastai handles tokenization with a chunksize, so you should still be able to tokenize your text.
Here are two things you should try :
Add a chunksize argument (the default value is 10k... | https://stackoverflow.com/questions/54890488/ |
Using PyTorch on AWS Lambda | Has anyone had any luck being able to use PyTorch on AWS Lambda for feature extraction from images or just using the framework at all? I finally got PyTorch, numpy, and pillow zipped in a folder under the uncompressed size limit (which is actually around 262 MB) but I had to build PyTorch from source to do this. The pr... | I was able to utilize the below layers for using pytorch on AWS Lambda:
arn:aws:lambda:AWS_REGION:934676248949:layer:pytorchv1-py36:1 PyTorch 1.0.1
arn:aws:lambda:AWS_REGION:934676248949:layer:pytorchv1-py36:2 PyTorch 1.1.0
Found these on Fastai production deployment page, thanks to Matt McClean
| https://stackoverflow.com/questions/54893935/ |
RuntimeError when changing the values of specific parts of a `torch.Tensor` | Say I have a 3 dimentional tensor x initialized with zeros:
x = torch.zeros((2, 2, 2))
and an other 3 dimentional tensor y
y = torch.ones((2, 1, 2))
I am trying to change the values of the first line of x[0] and x[1] like this
x[:, 0, :] = y
but I get this error:
RuntimeError: expand(torch.FloatTensor{[2, 1, ... | I found a straight forward way to do it:
x[:, 0, :] = y[:, 0, :]
| https://stackoverflow.com/questions/54897612/ |
PyTorch Datasets: Converting entire Dataset to NumPy | I'm trying to convert the Torchvision MNIST train and test datasets into NumPy arrays but can't find documentation to actually perform the conversion.
My goal would be to take an entire dataset and convert it into a single NumPy array, preferably without iterating through the entire dataset.
I've looked at How do I ... | If I understand you correctly, you want to get the whole train dataset of MNIST images (in total 60000 images, each image of size 1x28x28 array with 1 for color channel) as a numpy array of size (60000, 1, 28, 28)?
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# Transform to norm... | https://stackoverflow.com/questions/54897646/ |
DataLoader Class Errors Pytorch | I am beginner pytorch user, and I am trying to use dataloader.
Actually, I am trying to implement this into my network but it takes a very long time to load. And so, I debugged my network to see if the network itself has the problem, but it turns out it has something to with my dataloader class. Here is the code:
f... | There are some bugs in your code - could you check if this works (it is working on my computer with your toy example):
from torch.utils.data import Dataset, DataLoader
import numpy as np
import pandas as pd
import torch
class DiabetesDataset(Dataset):
def __init__(self, csv):
self.xy = pd.read_csv(csv)
... | https://stackoverflow.com/questions/54898145/ |
How to load images in the same folder in Pytorch? | I want to load all of the images from the folder /img and /mask respectively. The data structure can be shown as follows:
data
img
0.png
1.png
2.png
3.png
...
mask
label_0.png
label_1.png
label_2.png
...
Hopefully for help.
| If you want to load all the images from the two folders then you can try cv2
import cv2
img = []
for i in range(n): # n = number of images in img folder
img_path = f'~data\img\{i}.png' # replace ~ with full path
img.append(cv2.imread(img_path))
for i in range(n): # n = number of images in mask folder
im... | https://stackoverflow.com/questions/54898655/ |
how to modify rnn cells in pytorch? | If I want to change the compute rules in a RNN cell (e.g. GRU cell), what should I do?
I do not want to implement it via for or while loop considering the issue of efficiency.
I have viewed the source code of pytorch, but it seems that the major components of rnn cells are implement in c code which I cannot find and mo... | Yes, you implement it "via for or while loop".
Since Pytorch 1.0 there is JIT https://pytorch.org/docs/stable/jit.html that works pretty well (probably better to use the latest git version of PyTorch because of recent improvements to JIT), and depending on your network and implementation in can as fast as a native PyTo... | https://stackoverflow.com/questions/54903778/ |
Understanding Feature Maps in Convolutional Layers (PyTorch) | I've got this segment of code in a discriminator network for MNIST:
nn.Conv2d(1, 64, 4, 2, 1),
From my understanding, there is 1 input channel (the MNIST image), then we apply a 4x4 kernel to the image in strides of 2 to produce 64 feature maps. Does this mean that we actually have 64 kernels at this layer? Because ... | Your understanding in the first example is correct, you have 64 different kernels to produce 64 different feature maps.
In case of the second example, so the number of input channels not beeing one, you still have as "many" kernels as the number of output feature maps (so 128), which each are trained on a linear combi... | https://stackoverflow.com/questions/54904608/ |
Custom weight initialisation causing error - pytorch | %reset -f
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
import torch.utils.data as data_utils
import torch.nn as nn
import torch.nn.functional as F
num_epochs = 20
x1 = np.array([0,0])
x2 = np.array([0,1])
x3 = np.... | You are trying to set the weights of a weight-free layer (ReLU).
Inside weights_init, you should check the type of layers before initializing weights. For instance:
def weights_init(m):
if type(m) == nn.Linear:
m.weight.data.normal_(0.0, 1)
See How to initialize weights in PyTorch?.
| https://stackoverflow.com/questions/54911328/ |
What is the class definition of nn.Linear in PyTorch? | What is self.hidden in the following code?
import torch.nn as nn
import torch.nn.functional as F
class Network(nn.Module):
def __init__(self):
super().__init__()
self.hidden = nn.Linear(784, 256)
self.output = nn.Linear(256, 10)
def forward(self, x):
x = F.sigmoid(self.hidd... |
What is the class definition of nn.Linear in pytorch?
From documentation:
CLASS torch.nn.Linear(in_features, out_features, bias=True)
Applies a linear transformation to the incoming data: y = x*W^T + b
Parameters:
in_features – size of each input sample (i.e. size of x)
out_features – size of each output sample (i.... | https://stackoverflow.com/questions/54916135/ |
Is it possible to freeze only certain embedding weights in the embedding layer in pytorch? | When using GloVe embedding in NLP tasks, some words from the dataset might not exist in GloVe. Therefore, we instantiate random weights for these unknown words.
Would it be possible to freeze weights gotten from GloVe, and train only the newly instantiated weights?
I am only aware that we can set:
model.embedding.wei... | 1. Divide embeddings into two separate objects
One approach would be to use two separate embeddings one for pretrained, another for the one to be trained.
The GloVe one should be frozen, while the one for which there is no pretrained representation would be taken from the trainable layer.
If you format your data that f... | https://stackoverflow.com/questions/54924582/ |
Pytorch CNN error: Expected input batch_size (4) to match target batch_size (64) | I've been teaching myself this since November and any help on this would be really appreciated, thank you for looking, as I seem to be going round in circles. I am trying to use a Pytorch CNN example that was used with the Mnist dataset. Now I am trying to modify the CNN for facial key point recognition. I am using th... | to understand what went wrong you can print shape after every step in forward :
# Input data
torch.Size([64, 1, 96, 96])
x = F.relu(F.max_pool2d(self.conv1(x), 2))
torch.Size([64, 32, 48, 48])
x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2))
torch.Size([64, 64, 24, 24])
x = x.view(-1, 64 * 96 * 96)
torch.S... | https://stackoverflow.com/questions/54928638/ |
cudnn error while running a pyorch code on gpu | I have the following error:
Traceback (most recent call last):
File "odenet_mnist.py", line 343, in <module>
logits = model(x)
File "/home/subhashnerella/.conda/envs/pytorch/lib/python3.7/site-packages/torch/nn/modules/module.py", line 489, in __call__
result = self.forward(*input, **kwargs)
File "... | RTX2080Ti needs CUDA10 to work properly.Install the PyTorch binaries containing CUDA10
| https://stackoverflow.com/questions/54930268/ |
python - tensor : access a value | Given below is the output of VGG16 model. The command VGG16.classifier[6] output shows Linear(in_features=25088, out_features=4096, bias=True) I'm not able to understand how this works. ALso,how can I print the values of linear
VGG(
(features): Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1... | VGG16 model is divided into two groups of layers named features and classifier. You can access them as VGG16.features and VGG16.classifier:
>>> VGG16 = torchvision.models.vgg16(pretrained=True)
>>> VGG16.classifier
Sequential(
(0): Linear(in_features=25088, out_features=4096, bias=True)
(1): ReLU... | https://stackoverflow.com/questions/54934668/ |
Scatter homogenous list of values to PyTorch tensor | Consider the following list:
[[3], [1, 2], [4], [0], [2]]
And zeros tensor of size (5, 5)
I want to fill these indices according to their index in the list to the tensor with 1.
So, the expected output should be:
tensor([[0., 0., 0., 1., 0.],
[0., 1., 1., 0., 0.],
[0., 0., 0., 0., 1.],
[1... | You can solve this by modifying your index list to have the same number of indices in each element.
max_length = max([len(l) for l in index])
index = [l + l[-1:] * (max_length - len(l)) for l in index]
This code will repeat the last element of each sub-list until they are all the same size. You can then pass it to... | https://stackoverflow.com/questions/54935503/ |
How to access pytorch model parameters by index | If I have network with let's say 10 layers including biases, how can I access its i'th layer parameters just by index?
Currently, what I am doing is something like this
for parameter in myModel.parameters():
parameter.data /= 5
How could I access parameter.data with an index? For example I'd like to access 9th... | simply do a :
layers=[x.data for x in myModel.parameters()]
Now it will be a list of weights and biases, in order to access weights of the first layer you can do:
print(layers[0])
in order to access biases of the first layer:
print(layers[1])
and so on.
Remember if bias is false for any particular layer it wi... | https://stackoverflow.com/questions/54942416/ |
Understanding ELMo's number of presentations | I am trying my hand at ELMo by simply using it as part of a larger PyTorch model. A basic example is given here.
This is a torch.nn.Module subclass that computes any number of ELMo
representations and introduces trainable scalar weights for each. For
example, this code snippet computes two layers of representat... | See Section 3.2 of the original paper.
ELMo is a task specific combination of the intermediate layer representations in the biLM. For each token, a L-layer biLM computes a set of 2L+ 1representations
Previously in Section 3.1, it is said that:
Recent state-of-the-art neural language models comput... | https://stackoverflow.com/questions/54947258/ |
Pytorch torchvision MNIST download | I'm new to Pytorch and torchvision. I followed a tutorial that is roughly a year old where he tried to download mnist via python and torchvision.
This is how:
import torch
from torchvision import datasets, transforms
kwargs = {'num_workers': 1, 'pin_memory': True}
train = torch.utils.data.DataLoader(
datasets.MN... | So the problem wasn't the code or the naming or anything.
It was the torchvision version. I had 0.2.2.post2 and it worked with 0.2.1!
| https://stackoverflow.com/questions/54950428/ |
How to sort a dataset in pytorch | I would like to sort my dataset by the numerical values in the labels.
Is there a function from pytorch to handle this efficiently?
my dataset type() is in this from:
<class 'torchvision.datasets.mnist.MNIST'>
| There is no generic way to do this efficiently, as the dataset class is only implements a __getitem__ and __len__ method, and don't necessarily have any "stored" information about the labels.
In the case of the MNIST dataset class however you can sort the dataset from the label list.
For example when you want to list... | https://stackoverflow.com/questions/54964330/ |
Pytorch Indexing | I have a tensor [[1,2],[4,5],[7,8]] and a tensor with indices [0,1,0].
I want to apply them to second dimension so that it returns: [1,5,8].
How should I do that?
Thanks!
| import torch
arr=torch.tensor([[1,2],[4,5],[7,8]])
indices_arr=torch.tensor([0,1,0])
ret=arr[[0,1,2],indices_arr]
# print(ret)
# tensor([1, 5, 7])
| https://stackoverflow.com/questions/54964521/ |
How does pytorch backprop through argmax? | I'm building Kmeans in pytorch using gradient descent on centroid locations, instead of expectation-maximisation. Loss is the sum of square distances of each point to its nearest centroid. To identify which centroid is nearest to each point, I use argmin, which is not differentiable everywhere. However, pytorch is st... | As alvas noted in the comments, argmax is not differentiable. However, once you compute it and assign each datapoint to a cluster, the derivative of loss with respect to the location of these clusters is well-defined. This is what your algorithm does.
Why does it work? If you had only one cluster (so that the argmax o... | https://stackoverflow.com/questions/54969646/ |
How to add augmented images to original dataset using Pytorch? | From my understanding, RandomHorizontalFlip etc. replace image rather than adding new images to dataset. How do I increase my dataset size by adding augmented images to dataset using PyTorch?
I have gone through the links posted & haven't found a solution. I want to increase the data size by adding flipped/rotated... | Why do you want it? Generally speaking, it is enough to increase the number of epochs over the dataset, and your model will see the original and the augmented version of every image at least once (assuming a relatively high number of epochs).
Explanation:
For instance, if your augmentation has a chance of 50% to be app... | https://stackoverflow.com/questions/54969705/ |
RuntimeError: size mismatch, m1: [4 x 3136], m2: [64 x 5] at c:\a\w\1\s\tmp_conda_3.7_1 | I used python 3 and when i insert transform random crop size 224 it gives miss match error.
here my code
what did i wrong ?
| Your code makes variations on resnet: you changed the number of channels, the number of bottlenecks at each "level", and you removed a "level" entirely. As a result, the dimension of the feature map you have at the end of layer3 is not 64: you have a larger spatial dimension than you anticipated by the nn.AvgPool2d(8).... | https://stackoverflow.com/questions/54976741/ |
What is loss_cls and loss_bbox and why are they always zero in training | I'm trying to train a custom dataset on using faster_rcnn using the Pytorch implementation of Detectron here. I have made changes to the dataset and configuration according to the guidelines in the repo.
The training process is carried out successfully, but the loss_cls and loss_bbox values are 0 from the beginning an... | What are the two losses?
When training a multi-object detector, you usually have (at least) two types of losses:
loss_bbox: a loss that measures how "tight" the predicted bounding boxes are to the ground truth object (usually a regression loss, L1, smoothL1 etc.).
loss_cls: a loss that measures the correctne... | https://stackoverflow.com/questions/54977311/ |
Why feature extraction of text don't return all possible feature names? | Here is the snippet of code from the book
Natural Language Processing with PyTorch:
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
import seaborn as sns
corpus = ['Time flies flies like an arrow.', 'Fruit flies like a banana.']
one_hot_vectorizer = CountVectorizer()
vocab = one_hot_ve... | Very good question! Though this is not a pytorch question but a sklearn one =)
I encourage to first go through this https://www.kaggle.com/alvations/basic-nlp-with-nltk, esp. the "Vectorization with sklearn" section
TL;DR
If we use the CountVectorizer,
from io import StringIO
from sklearn.feature_extraction.text... | https://stackoverflow.com/questions/54977756/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.