instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
PyTorch custom loss function | How should a custom loss function be implemented ? Using below code is causing error :
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.function... | Your loss function is programmatically correct except for below:
# the number of tokens is the sum of elements in mask
num_tokens = int(torch.sum(mask).data[0])
When you do torch.sum it returns a 0-dimensional tensor and hence the warning that it can't be indexed. To fix this do int(torch.sum(mask).item()) a... | https://stackoverflow.com/questions/53980031/ |
How to multiply a tensor row-wise by a vector in PyTorch? | When I have a tensor m of shape [12, 10] and a vector s of scalars with shape [12], how can I multiply each row of m with the corresponding scalar in s?
| You need to add a corresponding singleton dimension:
m * s[:, None]
s[:, None] has size of (12, 1) when multiplying a (12, 10) tensor by a (12, 1) tensor pytorch knows to broadcast s along the second singleton dimension and perform the "element-wise" product correctly.
| https://stackoverflow.com/questions/53987906/ |
How to store switch locations during max-pooling layer | I am implementing the article https://arxiv.org/abs/1311.2901 by Zeiler and Fergus on visualizing and understanding convolutional Networks. To be able reflect hidden layers back to the image space we need deconvolution kernels, rectified linear functions and switch locations. I couldn't find how to store switch locatio... | The pytorch max pool operation takes an optional argument return_indices which is set to False by default. If you set that to True, the output will be the max pooled tensor as well the indices of the maximum items.
| https://stackoverflow.com/questions/53989912/ |
what is the first initialized weight in pytorch convolutional layer | I do self-studying in Udacity PyTorch
Regarding to the last paragraph
Learning
In the code you've been working with, you've been setting the values of filter weights explicitly, but neural networks will actually learn the best filter weights as they train on a set of image data. You'll learn all about this type of neu... | When you declared nn.Conv2d the weights are initialized via this code.
In particular, if you give bias it uses initialization as proposed by Kaiming et.al. It initializes as uniform distribution between (-bound, bound) where bound=\sqrt{6/((1+a^2)fan_in)} (See here).
You can initialize weight manually too. This has ... | https://stackoverflow.com/questions/53990652/ |
How can i process multi loss in pytorch? |
Such as this, I want to using some auxiliary loss to promoting my model performance.
Which type code can implement it in pytorch?
#one
loss1.backward()
loss2.backward()
loss3.backward()
optimizer.step()
#two
loss1.backward()
optimizer.step()
loss2.backward()
optimizer.step()
loss3.backward()
optimizer.step()
#t... | First and 3rd attempt are exactly the same and correct, while 2nd approach is completely wrong.
In Pytorch, low layer gradients are Not "overwritten" by subsequent backward() calls, rather they are accumulated, or summed. This makes first and 3rd approach identical, though 1st approach might be preferable if... | https://stackoverflow.com/questions/53994625/ |
axes don't match array in pytorch | I am new to pytorch and i am stuck in this for more than a week now.
i am trying to use AlexNet to make a 'gta san Andreas' self driving car and i am having alot of problems with preparing the data.
for now i am getting this error.
Traceback (most recent call last):
File "training_script.py", line 19, in <module&... | You are applying the transformation to a list of numpy arrays instead of to a single PIL image (which is usually what ToTensor() transforms expects).
| https://stackoverflow.com/questions/53995708/ |
How does the "number of workers" parameter in PyTorch dataloader actually work? |
If num_workers is 2, Does that mean that it will put 2 batches in the RAM and send 1 of them to the GPU or Does it put 3 batches in the RAM then sends 1 of them to the GPU?
What does actually happen when the number of workers is higher than the number of CPU cores? I tried it and it worked fine but How does it work? (... |
When num_workers>0, only these workers will retrieve data, main process won't. So when num_workers=2 you have at most 2 workers simultaneously putting data into RAM, not 3.
Well our CPU can usually run like 100 processes without trouble and these worker processes aren't special in anyway, so having more workers th... | https://stackoverflow.com/questions/53998282/ |
How to use AlexNet with one channel | I am new to pytorch and had a problem with channels in AlexNet.
I am using it for a ‘gta san andreas self driving car’ project, I collected the dataset from a black and white image that has one channel and trying to train AlexNet using the script:
from AlexNetPytorch import*
import torchvision
import torchvision.trans... | Your error is not related to using gray-scale images instead of RGB. Your error is about the spatial dimensions of the input: while "forwarding" an input image through the net, its size (in feature space) became zero - this is the error you see. You can use this nice guide to see what happens to the output size of each... | https://stackoverflow.com/questions/53999587/ |
How do I implement a PyTorch Dataset for use with AWS SageMaker? | I have implemented a PyTorch Dataset that works locally (on my own desktop), but when executed on AWS SageMaker, it breaks. My Dataset implementation is as follows.
class ImageDataset(Dataset):
def __init__(self, path='./images', transform=None):
self.path = path
self.files = [join(path, f) for f i... | I was able to create a PyTorch Dataset backed by S3 data using boto3. Here's the snippet if anyone is interested.
class ImageDataset(Dataset):
def __init__(self, path='./images', transform=None):
self.path = path
self.s3 = boto3.resource('s3')
self.bucket = self.s3.Bucket(path)
self... | https://stackoverflow.com/questions/54003052/ |
How to set a variable as an attribute? | I'm getting error when trying to set variable as an atribute.
parser = argparse.ArgumentParser()
parser.add_argument('--arch', action='store',
dest='arch', default='alexnet',
help='Store a simple value')
args = parser.parse_args()
model = models.args.arch(pretrained=True)
I know ... | You want to access the internal dict to update:
model = models.__dict__[args.arch](pretrained=True)
or using getattr:
getattr(models, args.arch)(pretrained=True)
| https://stackoverflow.com/questions/54012820/ |
pytorch dataloader stucked if using opencv resize method | I can run all the cells of the tutorial notebook of Pytorch about dataloading (pytorch tutorial).
But when I use OpenCV in place of Skimage to resize the image, the dataloader gets stuck, i.e nothing happens.
In the Rescale class:
class Rescale(object):
.....
def __call__(self, sample):
....
#im... | I had a very similar problem and that's how I solved it:
when you import cv2 set cv2.setNumThreads(0)
and then you can set num_workers>0 in the dataloader in PyTorch.
Seems like OpenCV tries to multithread and somewhere something goes into a deadlock.
Hope it helps.
| https://stackoverflow.com/questions/54013846/ |
Selection/Filter with indices using pytorch | I have a 3-dimensional numpy array, for example:
x = [[[0.3, 0.2, 0.5],
[0.1, 0.2, 0.7],
[0.2, 0.2, 0.6]]]
The indices array is also 3-dimensional, like:
indices = [[[0],
[1],
[2]]]
I expect the output is:
output= [[[0.3],
[0.2],
[0.6]]]
I tried the... | How about using x.gather(dim=2, indices)? That works for me.
| https://stackoverflow.com/questions/54028810/ |
What does the & operator do in PyTorch and why does it change the shape? | I have code that contains x and y, both of the type torch.autograd.variable.Variable. Their shape is
torch.Size([30, 1, 9])
torch.Size([1, 9, 9])
What I don't understand is, why the following results in a different size/shape
z = x & y
print(z.shape)
which outputs
torch.Size([30, 9, 9])
Why is the shape of... | This has nothing to do with the & operator, but with how broadcasting works in Python. To quote Eric Wieser's excellent documentation on broadcasting in NumPy:
In order to broadcast, the size of the trailing axes for both arrays in an operation must either be the same size or one of them must be one.
See the... | https://stackoverflow.com/questions/54032221/ |
The correct way to build a binary classifier for CNN | I created a neural network on pytorch using the pretraining model VGG16 and added my own extra layer to define belonging to one of two classes. For example bee or ant.
model = models.vgg16(pretrained=True)
# Freeze early layers
for param in model.parameters():
param.requires_grad = False
n_inputs = model.classifie... | It is indeed not surprising that a 2-class classifier fails with an image not belonging to any class.
To train your new one-class classifier, yes, use in our test set bees images and a set of non bee images. You need to accommodate for the imbalance between the classes as well to avoid overfitting just the bees images... | https://stackoverflow.com/questions/54040574/ |
A vector and matrix rows cosine similarity in pytorch | In pytorch, I have multiple (scale of hundred thousand) 300 dim vectors (which I think I should upload in a matrix), I want to sort them by their cosine similarity with another vector and extract the top-1000. I want to avoid for loop as it is time consuming. I was looking for an efficient solution.
| You can use torch.nn.functional.cosine_similarity function for computing cosine similarity. And torch.argsort to extract top 1000.
Here is an example:
x = torch.rand(10000,300)
y = torch.rand(1,300)
dist = F.cosine_similarity(x,y)
index_sorted = torch.argsort(dist)
top_1000 = index_sorted[:1000]
Please note the sha... | https://stackoverflow.com/questions/54042307/ |
There is an error with LSTM Hidden state dimension: RuntimeError: Expected hidden[0] size (4, 1, 256), got (1, 256) | I'm experimenting with seq2seq_tutorial in PyTorch. There appears to be a dimension error with the encoder's lstm hidden state size.
With bidirectional=True and num_layers = 2, the hidden state's shape is supposed to be (num_layers*2, batch_size, hidden_size).
However, an error occurs with the following message:
Ru... | I know this was asked a while ago but I think I found the answer to this in this torch discussion. Relevant info:
LSTM takes a tuple of hidden states: self.rnn(x, (h_0, c_0)) it looks like you haven’t sent in the second hidden state?
You can also see this in the documentation for LSTM
| https://stackoverflow.com/questions/54042737/ |
Gradually decay the weight of loss function | I am not sure is the right place to ask this question, feel free to tell me if I need to remove the post.
I am quite new in pyTorch and currently working with CycleGAN (pyTorch implementation) as a part of my project and I understand most of the implementation of cycleGAN.
I read the paper with the name ‘CycleGAN wi... | Below is a prototype function you can use!
def loss (other params, decay params, initial_lambda, steps):
# compute loss
# compute cyclic loss
# function that computes lambda given the steps
cur_lambda = compute_lambda(step, decay_params, initial_lamdba)
final_loss = loss + cur_lambda*cyclic_loss... | https://stackoverflow.com/questions/54047725/ |
pytorch:RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1) | When i using the cross-entropy loss as a loss function,i get this dimension out of range error.
This is my code:
self.ce = nn.CrossEntropyLoss()
def forward(self, pred, y):
loss = 0
for w_, p_, y_ in zip(self.weights, pred, y):
loss += w_ * self.ce(p_, y_)
return loss
when i ... | For cross entropy there should be the same number of labels as predictions.
In your specific case the dimensions of y_ and p_ should match which they don't as y_ is a 0 dimensional scalar and p_ is 1x2.
| https://stackoverflow.com/questions/54052653/ |
Pytorch: AttributeError: cannot assign module before Module.__init__() call even if initialized | I'm getting the following error:
AttributeError: cannot assign module before Module.init() call
I'm trying to create an instance of my class :
class ResNetGenerator(nn.Module):
def __init__(self, input_nc=3, output_nc=3, n_residual_blocks=9, use_dropout=False):
# super(ResNetGenerator, self).__init__... | In fact, I realized that i wasn't calling super().__init__() in the main class ColorizationCycleGAN. Adding this solved the problem.
I hope that this answer will have the effect of reminding you to check to call the super().__init__() function in all classes that inherits from nn.Module.
| https://stackoverflow.com/questions/54053256/ |
Index pytorch tensor with different dimension index array | I have the following function, which does what I want using numpy.array, but breaks when feeding a torch.Tensor due to indexing errors.
import torch
import numpy as np
def combination_matrix(arr):
idxs = np.arange(len(arr))
idx = np.ix_(idxs, idxs)
mesh = np.stack(np.meshgrid(idxs, idxs))
def np_com... | It is actually embarrassingly easy. You just need to flatten the indices, then reshape and permute the dimensions.
This is the full working version:
import torch
import numpy as np
def combination_matrix(arr):
idxs = np.arange(len(arr))
idx = np.ix_(idxs, idxs)
mesh = np.stack(np.meshgrid(idxs, idxs))
... | https://stackoverflow.com/questions/54054163/ |
Indexing the max elements in a multidimensional tensor in PyTorch | I'm trying to index the maximum elements along the last dimension in a multidimensional tensor. For example, say I have a tensor
A = torch.randn((5, 2, 3))
_, idx = torch.max(A, dim=2)
Here idx stores the maximum indices, which may look something like
>>>> A
tensor([[[ 1.0503, 0.4448, 1.8663],
[ ... | An ugly hackaround is to create a binary mask out of idx and use it to index the arrays. The basic code looks like this:
import torch
torch.manual_seed(0)
A = torch.randn((5, 2, 3))
_, idx = torch.max(A, dim=2)
mask = torch.arange(A.size(2)).reshape(1, 1, -1) == idx.unsqueeze(2)
B = torch.zeros_like(A)
B[mask] = A[m... | https://stackoverflow.com/questions/54057112/ |
Weight decay loss | I need to write a code to gradually decay the weight of my loss function by computes lambda with given steps, But I don't have any idea. Any help will be appreciated.
This is my Loss function:
loss_A = criterion(recov_A, real_A)
loss_Final = lambda_A * loss_A + #lambda_A is a fixed number: 10
I don't want the lambd... | To decay the fixed number depends on the number of steps or even the number of epochs you can use the following code or you can write the code as a function and call it whenever you want.
final_value = 1e-3 # Small number because dont end up with 0
initial_value = 20
starting_step = 25
total_step = 100
for i in rang... | https://stackoverflow.com/questions/54057338/ |
RuntimeError: Error(s) in loading state_dict for ResNet: | I am loading my model using the following code.
def load_model(checkpoint_path):
'''
Function that loads a checkpoint and rebuilds the model
'''
checkpoint = torch.load(checkpoint_path, map_location = 'cpu')
if checkpoint['architecture'] == 'resnet18':
model = models.resnet18(pretrained=True)
# Free... | I was using Pytorch 0.4.1 but Jupyter Notebook which I loaded uses 0.4.0. So I added strict=False attribute to load_state_dict().
model.load_state_dict(checkpoint['state_dict'], strict=False)
| https://stackoverflow.com/questions/54058256/ |
I can't adapt my dataset to VGG-net, getting size mismatch | I’m trying to implement the pre-trained VGG net to my script, in order to recognize faces from my dataset in RGB [256,256], but I’m getting a “size mismatch, m1: [1 x 2622], m2: [4096 x 2]” even if i'm resizing my images it doesn't work, as you can see my code work with resnet and alexnet.
I've tryed resizing the imag... | The error comes from this line:
model_conv.fc = nn.Linear(4096, 2)
Change to:
model_conv.fc = nn.Linear(2622, 2)
| https://stackoverflow.com/questions/54059953/ |
Gradient disappearing after first epoch in manual linear regression | I'm new to Pytorch and I've been working through the tutorials and playing around with toy examples. I wanted to just make a super simple model to get a better handle on autograd, but I'm running into issues.
I'm trying to train a linear regression model but I keep running into the following error,
------------------... | The answer lies in locally disabling gradient computation. As you can see in the first example, computations carried out with the torch.no_grad() context manager result in tensors for which requires_grad == False. Since you create "fresh" w and b instead of updating them in place, these tensors lose the requires_grad p... | https://stackoverflow.com/questions/54064934/ |
Why does this semantic segmentation network have no softmax classification layer in Pytorch? | I am trying to use the following CNN architecture for semantic pixel classification. The code I am using is here
However, from my understanding this type of semantic segmentation network typically should have a softmax output layer for producing the classification result.
I could not find softmax used anywhere withi... | You are using quite a complex code to do the training/inference. But if you dig a little you'll see that the loss functions are implemented here and your model is actually trained using cross_entropy loss. Looking at the doc:
This criterion combines log_softmax and nll_loss in a single function.
For numerical sta... | https://stackoverflow.com/questions/54083220/ |
Bicubic interpolation in pytorch | I'm trying to do bicubic interpolation on a torch.Tensor.
I know about torch.nn.functional.interpolate, but that method doesn't support bicubic interpolation yet.
I know that PIL images support bicubic interpolation, so I created this snippet (part of torch.nn.Module).
def build_transform(self, shape):
h, w = sh... | torch.nn.functional.interpolate() with mode='bicubic' is supported since pytorch 1.2.0.
| https://stackoverflow.com/questions/54083474/ |
Expect FloatTensors but got LongTensors in MNIST-like task | I am performing a MNIST-like task, the input is 10-class images, and the expected output is the predicted class of the images.
But now the output is like [-2.3274, -2.2723, ...], which the length is the batch_size. And the target is [4., 2., 2., 8., ...]
Error message: RuntimeError: expected object for scalar type L... | The error you got refers to the second (#2) argument of the loss: the target.
NLLLoss expects (for each element) to have a float vector of probabilities, and a single long (i.e., integer) target per element.
In your case, your "target" values are [4., 2., 2., 8., ...] which are of type float. you need to convert your t... | https://stackoverflow.com/questions/54085357/ |
In PyTorch, what makes a tensor have non-contiguous memory? | According to this SO and this PyTorch discussion, PyTorch's view function works only on contiguous memory, while reshape does not. In the second link, the author even claims:
[view] will raise an error on a non-contiguous tensor.
But when does a tensor have non-contiguous memory?
| This is a very good answer, which explains the topic in the context of NumPy. PyTorch works essentially the same. Its docs don't generally mention whether function outputs are (non)contiguous, but that's something that can be guessed based on the kind of the operation (with some experience and understanding of the impl... | https://stackoverflow.com/questions/54095351/ |
How to fix 'cannot initialize type TensorProto DataType' error while importing torch? | I installed pytorch using pip3 command for my windows pc without GPU support.
But when I tried to import torch it is giving an error.
At first, there was a different error saying numpy version not matching and I updated the numpy to the latest version.
import torch
RuntimeError Traceback ... | I reinstalled anaconda and then created a virtual environment for pytorch.Now everything works fine
| https://stackoverflow.com/questions/54096158/ |
Implementing dropout from scratch | This code attempts to utilize a custom implementation of dropout :
%reset -f
import torch
import torch.nn as nn
# import torchvision
# import torchvision.transforms as transforms
import torch
import torch.nn as nn
import torch.utils.data as data_utils
import numpy as np
import matplotlib.pyplot as plt
import torch.n... |
It seems I've implemented the dropout function incorrectly?
np.random.binomial([np.ones((len(input),np.array(list(input.shape))))],1 dropout_percent)[0] * (1.0/(1-self.p))
In fact, the above implementation is known as Inverted Dropout. Inverted Dropout is how Dropout is implemented in practice in the various deep le... | https://stackoverflow.com/questions/54109617/ |
Why listing model components in pyTorch is not useful? | I am trying to create Feed forward neural networks with N layers
So idea is suppose If I want 2 inputs 3 hidden and 2 outputs than I will just pass [2,3,2] to neural network class and neural network model will get created so if I want [100,1000,1000,2]
where in this case 100 is inputs, two hidden layers contains 1000 n... | If you do print(FeedForwardNetModel([1,2,3]) it gives the following error
AttributeError: 'FeedforwardNeuralNetModel' object has no attribute '_modules'
which basically means that the object is not able to recognize modules that you have declared.
Why does this happen?
Currently, modules are declared in self.... | https://stackoverflow.com/questions/54143427/ |
pytorch instance tensor not moved to gpu even with explicit cuda() call | I'm working on a project where the model requires access to a tensor that i declare in the constructor init of the class (im sub-classing torch.nn.Module class) and then i need to use this tensor in the forward() method via a simple matmul() , the model is sent to gpu via a cuda() call:
model = Model()
model.cuda()
... | Let's assume the following:
X is moved correctly to the GPU
The tensor declared in the Model class is a simple attribute.
i.e. Something like the following:
class Model(nn.Module):
def __init__(self):
super().__init__()
self.matrix = torch.randn(784, 10)
def forward(self, x):
retu... | https://stackoverflow.com/questions/54155969/ |
RuntimeError: The shape of the mask [1682] at index 0 does not match the shape of the indexed tensor [1, 1682] at index 0 | I am designing an stacked autoencoder trying to train my neural network on movie rating if the user doesnt rate any movie it will not consider it
My training set runs perfectly but when i run test set it shows me this error
RuntimeError: The shape of the mask [1682] at index 0 does not match the shape of the index... | Change:
output[target == 0] = 0 # I get error at this line
To:
output[(target == 0).unsqueeze(0)] = 0
Reason:
The torch.Tensor returned by target == 0 is of the shape [1682].
(target == 0).unsqueeze(0) will convert it to [1, 1682]
| https://stackoverflow.com/questions/54159814/ |
How to use a numpy function as the loss function in PyTorch and avoid getting errors during run time? | For my task, I do not need to compute gradients. I am simply replacing nn.L1Loss with a numpy function (corrcoef) in my loss evaluation but I get the following error:
RuntimeError: Can’t call numpy() on Variable that requires grad. Use var.detach().numpy() instead.
I couldn’t figure out how exactly I should detach t... | TL;DR
with torch.no_grad():
predFeats = self(x)
targetFeats = self(target)
loss = torch.tensor(np.corrcoef(predFeats.cpu().numpy(),
targetFeats.cpu().numpy())[1][1]).float()
You would avoid the first RuntimeError by detaching the tensors (predFeats and targetFeats) f... | https://stackoverflow.com/questions/54165651/ |
grad_outputs in torch.autograd.grad (CrossEntropyLoss) | I’m trying to get d(loss)/d(input). I know I have 2 options.
First option:
loss.backward()
dlossdx = x.grad.data
Second option:
# criterion = nn.CrossEntropyLoss(reduce=False)
# loss = criterion(y_hat, labels)
# No need to call backward.
dlossdx = torch.autograd.grad(outputs = loss,
... | Let's try to understand how both the options work.
We will use this setup
import torch
import torch.nn as nn
import numpy as np
x = torch.rand((64,10), requires_grad=True)
net = nn.Sequential(nn.Linear(10,10))
labels = torch.tensor(np.random.choice(10, size=64)).long()
criterion = nn.CrossEntropyLoss()
First op... | https://stackoverflow.com/questions/54166206/ |
PyTorch - RuntimeError: bool value of Tensor with more than one value is ambiguous | I trained a GAN on the MNIST dataset, and I'm trying to make a very simple UI that has a button to generate and display new images. When I press a button I make a call to the generator and pass a new latent vector to the forward method and keep getting this error message.
def update_picture():
print('press')
_... | I think I got the problem.
Variable is a name reserved in torch and tkinter. If you are doing from ... import * you may get Variable from tkinter. Since the error is comming from this line, the Variable in your code is from tkinter. However, since you are calling it with a Tensor inside, I'm guessing that you wanted t... | https://stackoverflow.com/questions/54188885/ |
Pytorch detach() function failed to be excuated on different GPU severs | Recently, our lab bought a new server with 9 GPUs and I want to run my programming on this machine. However, I do not change my right code and I got an unexpected error like the following.
THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THC/THCGeneral.cpp line=663 error=11 : invalid argu... | The error is caused by the version mismatching between the RTX GPU cards and the CUDA driver.
| https://stackoverflow.com/questions/54193209/ |
Torch C++: Getting the value of a int tensor by using *.data() | In the C++ version of Libtorch, I found that I can get the value of a float tensor by *tensor_name[0].data<float>(), in which instead of 0 I can use any other valid index. But, when I have defined an int tensor by adding option at::kInt into the tensor creation, I cannot use this structure to get the value of the... | Use item<dtype>() to get a scalar out of a Tensor.
int main() {
torch::Tensor tensor = torch::randint(20, {2, 3});
std::cout << tensor << std::endl;
int a = tensor[0][0].item<int>();
std::cout << a << std::endl;
return 0;
}
~/l/build ❯❯❯ ./example-app
3 10 3
2 5 ... | https://stackoverflow.com/questions/54200785/ |
size mismatch, m1: [3584 x 28], m2: [784 x 128] at /pytorch/aten/src/TH/generic/THTensorMath.cpp:940 | I have executed the following code and getting the error shown at extreme bottom. I would like to know how to resolve this. thanks
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torchvision import transforms
_tasks = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(... | Your input MNIST data has shape [256, 1, 28, 28] corresponding to [B, C, H, W]. You need to flatten the input images into a single 784 long vector before feeding it to the Linear layer Linear(784, 128) such that the input becomes [256, 784] corresponding to [B, N], where N is 1x28x28, your image size. This can be done ... | https://stackoverflow.com/questions/54218604/ |
How to vectorize computation of mean over specific set of indices given as matrix rows? | I have a problem vectorizing some code in pytorch.
A numpy solution would also help, but a pytorch solution would be better.
I'm going to use array and Tensor interchangeably.
The problem I am facing is this:
Given an 2D float array X of size (n, x), and a boolean 2D array A of size (n, n), compute the mean over row... | We can leverage matrix-multiplication -
c = A.sum(1,keepdims=True)
means_np = np.where(c==0,0,A.dot(X)/c)
We can optimize it further by converting A to float32 dtype if it's not already so and if the loss of precision is okay there, as shown below -
In [57]: np.random.seed(0)
In [58]: A = np.random.randint(0,2,(10... | https://stackoverflow.com/questions/54220249/ |
how to fix capsule training problem for a single class of MNIST dataset? | I am training a Capsule Network with both encoder and decoder part. It works perfectly fine with all the classes (10 classes) of the MNIST data set. But when I am extracting a single class say (class 0 or class 5) and then training the capsule network, the reconstruction of the image is very poor.
Where do I need to c... | I checked the normal performing code and then the problematic one, I found that the dataset passed into the network was of not same nature. The problems were -
The MNIST data extracted for a single class was not transformed into tensor and no normalization was applied, although I tried passing it through the transfor... | https://stackoverflow.com/questions/54221434/ |
pytorch : unable to understand model.forward function | I am learning deep learning and am trying to understand the pytorch code given below. I'm struggling to understand how the probability calculation works. Can somehow break it down in lay-man terms. Thanks a ton.
ps = model.forward(images[0,:])
# Hyperparameters for our network
input_size = 784
hidden_sizes = [128... | I'm a layman so I'll help you with the layman's terms :)
input_size = 784
hidden_sizes = [128, 64]
output_size = 10
These are parameters for the layers in your network. Each neural network consists of layers, and each layer has an input and an output shape.
Specifically input_size deals with the input shape of the ... | https://stackoverflow.com/questions/54239125/ |
What is the difference between MLP implementation from scratch and in PyTorch? | Following up the question from How to update the learning rate in a two layered multi-layered perceptron?
Given the XOR problem:
X = xor_input = np.array([[0,0], [0,1], [1,0], [1,1]])
Y = xor_output = np.array([[0,1,1,0]]).T
And a simple
two layered Multi-Layered Perceptron (MLP) with
sigmoid activations betwee... | List of differences between hand-rolled code and PyTorch code
Turns out there are a lot of differences between what your hand-rolled code and the PyTorch code are doing. Here's what I uncovered, listed roughly in order of most to least impact on the output:
Your code and the PyTorch code use two different functions ... | https://stackoverflow.com/questions/54247143/ |
Model parameter initialization | I am new to PyTorch. I am writing a simple program for linear regression and i want to compare the results by using different methods (SGD,momentum,ADAM,etc). The problem I have is that I want every time a loop ends for the model parameters to be reinitialized to the same value that the previous model started with so ... | The parameters of a linear layer are stored in model.weight and model.bias. You need to copy those before training, and then restore afterwards. This is a bit more involved than what you're doing in your code. Example below
# clone and detach so that we have an actual backup copy,
# not merely a reference to the param... | https://stackoverflow.com/questions/54248646/ |
how to multiply all rows by column of single matrix in pytorch in a vectorized way | I need to multiply all rows of a matrix by column, i think with an example it will be clearer:
matrix is:
1,2,3
4,5,6
7,8,9
An i need an operation that returns:
28,80,162
But i can't find anything in the documentation and blogs and other SO question only are related to matrix multiplication and dot product, w... | I found the solution, there's no :
the_matrix.mul(dim=0)
But there's:
he_matrix.prod(dim=0)
Which does exactly what is needed.
| https://stackoverflow.com/questions/54249399/ |
Pytorch mask missing values when calculating rmse | I'm trying to calculate the rmse error of two torch tensors. I would like to ignore/mask the rows where the labels are 0 (missing values). How could I modify this line to take that restriction into account?
torch.sqrt(((preds.detach() - labels) ** 2).mean()).item()
Thank you in advance.
| This can be solved by defining a custom MSE loss function* that masks out the missing values, 0 in your case, from both the input and target tensors:
def mse_loss_with_nans(input, target):
# Missing data are nan's
# mask = torch.isnan(target)
# Missing data are 0's
mask = target == 0
out = (input... | https://stackoverflow.com/questions/54249737/ |
How Weight update in Dynamic Computation Graph of pytorch works? | How does the Weight Update works in Pytorch code of Dynamic Computation Graph when Weights are shard (=reused multiple times)
https://pytorch.org/tutorials/beginner/examples_nn/dynamic_net.html#sphx-glr-beginner-examples-nn-dynamic-net-py
import random
import torch
class DynamicNet(torch.nn.Module):
def __init__... | When you call backward (either as the function or a method on a tensor) the gradients of operands with requires_grad == True are calculated with respect to the tensor you called backward on. These gradients are accumulated in the .grad property of these operands. If the same operand A appears multiple times in the expr... | https://stackoverflow.com/questions/54250651/ |
Pytorch errors: "received an invalid combination of arguments" in Jupyter Notebook | I'm trying to learn Pytorch, but whenever I seem to try any online tutorial (https://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html#sphx-glr-beginner-blitz-tensor-tutorial-py), I get errors when trying to run certain functions, but only in Jupyter Notebook.
When running
x = torch.empty(5, 3)
I get an err... | Ok, so the fix for me was to either update pytorch through conda using the following command
conda update pytorch
If it's not installed yet, I've gotten it to work in other environments by simply installing it through conda
conda install pytorch
Kind of stupid that I didn't try this earlier, but I was confused on... | https://stackoverflow.com/questions/54257695/ |
How to look at the parameters of a pytorch model? | I have a simple pytorch neural net that I copied from openai, and I modified it to some extent (mostly the input).
When I run my code, the output of the network remains the same on every episode, as if no training occurs.
I want to see if any training happens, or if some other reason causes the results to be the same... | Depends on what you are doing, but the easiest would be to check the weights of your model.
You can do this (and compare with the ones from previous iteration) using the following code:
for parameter in model.parameters():
print(parameter.data)
If the weights are changing, the neural network is being optimized... | https://stackoverflow.com/questions/54259943/ |
How does the parameter 'dim' in torch.unique() work? | I am trying to extract the unique values in each row of a matrix and returning them into the same matrix (with repeated values set to say, 0) For example, I would like to transform
torch.Tensor(([1, 2, 3, 4, 3, 3, 4],
[1, 6, 3, 5, 3, 5, 4]])
to
torch.Tensor(([1, 2, 3, 4, 0, 0, 0],
[1, 6,... | One must admit the unique function can sometimes be very confusing without given proper examples and explanations.
The dim parameter specifies which dimension on the matrix tensor you want to apply on.
For instance, in a 2D matrix, dim=0 will let operation perform vertically where dim=1 means horizontally.
Example,... | https://stackoverflow.com/questions/54262689/ |
How to convert a pytorch tensor into a numpy array? | How do I convert a torch tensor to numpy?
| copied from pytorch doc:
a = torch.ones(5)
print(a)
tensor([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)
[1. 1. 1. 1. 1.]
Following from the below discussion with @John:
In case the tensor is (or can be) on GPU, or in case it (or it can) require grad, one can use
t.detach().cpu().numpy()
I recommend to uglify yo... | https://stackoverflow.com/questions/54268029/ |
Strange behavior of linear regression in PyTorch | I am facing a peculiar problem and I was wondering if there is an explanation. I am trying to run a linear regression problem and test different optimization methods and two of them have a strange outcome when comparing to each other. I build a data set that satisfies y=2x+5 and I add a random noise to that.
xtrain=n... | This has to do with the fact that you are drawing the training samples themselves from a random distribution.
By doing so, you inherently randomized the ground truth to some extent. Sure, you will get values that are inherently distributed around 2x+5, but you do not guarantee that 2x+5 will also be the best fit to th... | https://stackoverflow.com/questions/54273680/ |
RuntimeError: PyTorch does not currently provide packages for PyPI | I'm trying to run this https://github.com/shariqiqbal2810/MAAC repository and it has a module called torch
import torch as McLawrence
from torch.autograd import Variable
I'm using python version 3.7.1 and I downgraded to 3.6.5 on win10
I tried to use
pip install torch
pip install pytorch
pip install torchvision
I ch... | Installing from the PyTorch wheel should have worked. But, the problem turns out to be that pip is using the cached pytorch to install it as mentioned on GitHub here.
Collecting pytorch
Using cached https://files.pythonhosted.org/packages...
Either removing the pip's cache from %LocalAppData%\pip\Cache on Windows ... | https://stackoverflow.com/questions/54274089/ |
Applying any optimization causes values to be NaN | I am working on a classifier model for this data set:
https://archive.ics.uci.edu/ml/datasets/ILPD+%28Indian+Liver+Patient+Dataset%29
and I have come up with this code in pytorch:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn import preprocessing
from sklea... | The problem is caused by not normalizing every column in the dataset. I have no idea why but normalizing column will solve the problem.
| https://stackoverflow.com/questions/54275436/ |
What's the difference between torch.stack() and torch.cat() functions? | OpenAI's REINFORCE and actor-critic example for reinforcement learning has the following code:
REINFORCE:
policy_loss = torch.cat(policy_loss).sum()
actor-critic:
loss = torch.stack(policy_losses).sum() + torch.stack(value_losses).sum()
One is using torch.cat, the other uses torch.stack, for similar use cases.
As far... | stack
Concatenates sequence of tensors along a new dimension.
cat
Concatenates the given sequence of seq tensors in the given dimension.
So if A and B are of shape (3, 4):
torch.cat([A, B], dim=0) will be of shape (6, 4)
torch.stack([A, B], dim=0) will be of shape (2, 3, 4)
| https://stackoverflow.com/questions/54307225/ |
Pytorch median - is it bug or am I using it wrong | I am trying to get median of each row of 2D torch.tensor. But the result is not what I expect when compared to working with standard array or numpy
import torch
import numpy as np
from statistics import median
print(torch.__version__)
>>> 0.4.1
y = [[1, 2, 3, 5, 9, 1],[1, 2, 3, 5, 9, 1]]
median(y[0])
>&g... | Looks like this is the intended behaviour of Torch as mentioned in this issue
https://github.com/pytorch/pytorch/issues/1837
https://github.com/torch/torch7/pull/182
The reasoning as mentioned in the link above
Median returns 'middle' element in case of odd-many elements, otherwise one-before-middle element (coul... | https://stackoverflow.com/questions/54310861/ |
Update step in PyTorch implementation of Newton's method | I'm trying to get some insight into how PyTorch works by implementing Newton's method for solving x = cos(x). Here's a version that works:
x = Variable(DoubleTensor([1]), requires_grad=True)
for i in range(5):
y = x - torch.cos(x)
y.backward()
x = Variable(x.data - y.data/x.grad.data, requires_grad=True)... | I think your first version of code is optimal, meaning that it is not creating a computation graph on every run.
# initial guess
guess = torch.tensor([1], dtype=torch.float64, requires_grad = True)
# function to optimize
def my_func(x):
return x - torch.cos(x)
def newton(func, guess, runs=5):
for _ in ran... | https://stackoverflow.com/questions/54316053/ |
Size mismatch error with PyTorch toturial | I am learning the tutorial called Deep Learning with PyTorch: A 60 Minute Blitz on PyTorch website. My codes are the same as those of it, but there is a size mismatch error as shown below. Could anyone tell me why and how to solve it? Thank you:)
RuntimeError: size mismatch, m1: [80 x 5], m2: [400 x 120] at
c:\a\... | Sorry for disturbance, I find the mistake. I missed x= in x=x.view(-1,self.num_flat_features(x))...
| https://stackoverflow.com/questions/54319419/ |
PIL image resize change the value of pixel? | I want to resize an PIL image without changing the pixel value range.
I have tried the Image.resize() but it changes my pixel value range from [0,255] to [79,179]
I'm using Python and PyTorch, in PyTorch, the transforms.resize() will implement Image.resize()
Here is the test code I used
a = torch.randint(0,255,(500... | Try resize with Nearest neighbor algorithm implemented in pil. It doesn't change pixels
| https://stackoverflow.com/questions/54321678/ |
How to fill in the blank using bidirectional RNN and pytorch? | I am trying to fill in the blank using a bidirectional RNN and pytorch.
The input will be like: The dog is _____, but we are happy he is okay.
The output will be like:
1. hyper (Perplexity score here)
2. sad (Perplexity score here)
3. scared (Perplexity score here)
I discovered this idea here: https://medium.c... | As this question is rather open-ended I will start from the last parts, moving towards the more general answer to the main question posed in the title.
Quick note: as pointed in the comments by @Qusai Alothman, you should find a better resource on the topic, this one is rather sparse when it comes to necessary informat... | https://stackoverflow.com/questions/54323427/ |
Test set accuracy is very high after very few epochs on mnist dataset | With very few epochs this model learns to classify beween 1 and 0 extremely quickly which leads me to consider something is wrong.
Below code downloads mnist dataset, extracts the mnist images that contain 1 or 0 only. A random sample of size 200 is selected from this subset of mnist images. This random sample is the... | Here's my 2 cents on your binary experiment.
It would seem like you have severely reduce the complexity of your dataset and with the high number of neurons in your intermediate layers, your model is expected to converge very quickly.
Note that MNIST dataset has channel of 1 and this makes the task very simple.
You ... | https://stackoverflow.com/questions/54334829/ |
Impact of using data shuffling in Pytorch dataloader | I implemented an image classification network to classify a dataset of 100 classes by using Alexnet as a pretrained model and changing the final output layers.
I noticed when I was loading my data like
trainloader = torch.utils.data.DataLoader(train_data, batch_size=32, shuffle=False)
, I was getting accuracy on val... | Yes it totally can affect the result! Shuffling the order of the data that we use to fit the classifier is so important, as the batches between epochs do not look alike.
Checking the Data Loader Documentation it says:
"shuffle (bool, optional) – set to True to have the data reshuffled at every epoch"
In any c... | https://stackoverflow.com/questions/54354465/ |
Unable to get an image in the output when using MNIST Database using Pytorch | iter_test = 0
for images, labels in test_loader:
iter_test += 1
images = images.view(-1, 28*28)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
if iter_test == 1:
print('PREDICTION')
print(predicted[0])
print('LABEL SIZE')
print(labels.size())
print('LABEL FOR IMAGE 0')
... | Yes :).
You can use pyplot and show the image loaded by test_loader.
Check https://www.oreilly.com/learning/not-another-mnist-tutorial-with-tensorflow .
Hope this helps!
| https://stackoverflow.com/questions/54355067/ |
Is there any other reason why we make sequence length the same using padding? | Is there any other reason why we make sequence length the same length using padding? Other than in order to do matrix multiplication (therefore doing parallel computation).
| It may depend on the specific situation you are dealing with. But in general, the only reason I would do zero padding or any kind of padding to RNN would be to make batch-wise computations work. Also, padding should be done in a way that it doesn't affect the results. So, it should not contribute to computing hidden st... | https://stackoverflow.com/questions/54355310/ |
Pytorch: Why is the memory occupied by the `tensor` variable so small? | In Pytorch 1.0.0, I found that a tensor variable occupies very small memory. I wonder how it stores so much data.
Here's the code.
a = np.random.randn(1, 1, 128, 256)
b = torch.tensor(a, device=torch.device('cpu'))
a_size = sys.getsizeof(a)
b_size = sys.getsizeof(b)
a_size is 262288. b_size is 72.
| The answer is in two parts. From the documentation of sys.getsizeof, firstly
All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.
so it could be that for tensors __sizeof__ is undefined or defined differently than you would ... | https://stackoverflow.com/questions/54361763/ |
os.mknod returns [error38] function not implemented in google colab | I am trying to run the following piece of code on google colab.
dir_path = '/content/drive/My Drive/Colab Notebooks'
log_loss_path =os.path.join(dir_path, 'log_loss.txt')
if not os.path.isfile(log_loss_path):
os.mknod(log_loss_path)
but i get the error [Errno 38] Function not implemented
OSError ... | /content/drive is a FUSE filesystem which doesn't support this operation.
If you are just trying to create a file, use instead open(log_loss_path, 'w').
| https://stackoverflow.com/questions/54364457/ |
By picture that is displayed in Jupyter notebook isn't shown when running the same code in IDE? | I was trying to run code from an online tutorial on my local machine by copying code from Jupiter notebook to my IDE (pycharm).
This part
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
pig_img = Image.open(... | You need to call .show() explicitly to show the image in terminal i.e.
Add this to the end of the code
plt.show()
From the documentation:
Display a figure. When running in ipython with its pylab mode, display all figures and return to the ipython prompt.
In non-interactive mode, display all figures and block until th... | https://stackoverflow.com/questions/54370810/ |
What kinds of optimization are used in PyTorch methods? | I'm using PyTorch to implement an intense sequence of matrix operations, using methods such as torch.mm or torch.dot. I was wondering if PyTorch uses multithreading or other optimization mechanisms to speed up the process. I am not utilizing a GPU. I appreciate if you could inform me of how fast these methods are and w... | PyTorch uses an efficient BLAS implementation and multithreading (openMP, if I'm not wrong) to parallelize such operations with multiple cores. Some performance loss comes from the Python itself - since this is an interpreted language, no significant compiler-like optimization can be done. You can use the jit module to... | https://stackoverflow.com/questions/54379214/ |
Pytorch RuntimeError: Invalid index in gather | I'm new to Pytorch and I encounter this error:
x.gather(1, c)
RuntimeError: Invalid index in gather at
/pytorch/aten/src/TH/generic/THTensorEvenMoreMath.cpp:457
Here is some informations about the tensors:
print(x.size())
print(c.size())
print(type(x))
print(type(c))
torch.Size([128, 2])
torch.Size([128,... | This simply means your index tensor c has invalid indices.
For example, the following index tensor is valid:
x = torch.tensor([
[5, 9, 1],
[3, 2, 8],
[7, 4, 0]
])
c = torch.tensor([
[0, 0, 0],
[1, 2, 0],
[2, 2, 1]
])
x.gather(1, c)
>>>ten... | https://stackoverflow.com/questions/54380830/ |
Forward Jacobian Of Neural Network in Pytorch is Slow | I am computing the forward jacobian (derivative of outputs with respect to inputs) of a 2 layer feedforward neural network in pytorch, and my results are correct but relatively slow. Given the nature of the calculation I would expect it to be approximately as fast as a forward pass through the network (or maybe 2-3x as... | The second calculation of 'a' takes the most time on my machine (cpu).
# Here you increase the size of the matrix with a factor of "input_1"
expanded_deriv = tanh_deriv_tensor.unsqueeze(-1).expand(-1, -1, input_1)
partials = expanded_deriv * a.expand_as(expanded_deriv)
# Here your torch.matmul() needs to handle "inpu... | https://stackoverflow.com/questions/54383474/ |
How to fix ' ImportError: cannot import name 'numpy_type_map' ' in Python? | I've followed the instructions in Detectron and I've configured it several times: the code compiles as it should. When it comes to run the code, I get this error:
Traceback (most recent call last):
File "tools/train_net_step.py", line 21, in <module>
import nn as mynn
File "/home/federico/Pycharm... | I suppose there is a version mismatch between detectron and the needed pytorch release you are using.
if you look at latest pytorch source code, there is no numpy_type_map component.
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/dataloader.py
| https://stackoverflow.com/questions/54387659/ |
when training simple code of pytorch, cpu ratio increased. GPU is 0% approximately | I'm doing tutorial of Pytorch.
Code is clearly completed. but i have one problem.
It is about my CPU use ratio.
If I enter into training, CPU usage ratio is increasıng up to 100%.
but GPU is roughly 0%.
I installed CUDA 9.2 and cudnn.
and I already checked massage about torch.cuda.is_available()==True.
is it OK, o... | 1.. Did you upload your model and input tensors onto GPU explicitly, showing as follow
https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#training-on-gpu
For example,
# Configure your device
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Upload your model onto GPU
net.to(dev... | https://stackoverflow.com/questions/54387686/ |
Why does gpytorch seem to be less accurate than scikit-learn? | I current found gpytorch (https://github.com/cornellius-gp/gpytorch). It seems to be a great package for integrating GPR into pytorch. First tests were also positive. Using gpytorch the GPU-Power as well as intelligent algorithms can used in order to improve performance in comparison to other packages such as scikit-le... | (I also answer your question on the GitHub issue you created for it here)
Primarily this happened because you used different models in sklearn and gpytorch. In particular, sklearn learns independent GPs in the multi-output setting by default (see e.g., the discussion here). In GPyTorch, you used the multitask GP metho... | https://stackoverflow.com/questions/54389944/ |
pretrained object detection models in keras | There are pretrained object recognition models in keras.applications library. But as far as I know, there is no pretrained object detection model available.
Does anyone know why it is the case? Object detection is a big part of problems when dealing with visual problems.
| That is because vanilla Keras does not include implementation of methods/models for object detection.
There are many approaches to object detection with deep learning (see Object Detection with Deep Learning: A Review for a survey), but none of them are implemented as a part of Keras library, so no official models as... | https://stackoverflow.com/questions/54396398/ |
RuntimeError: Expected a Tensor of type torch.FloatTensor but found a type torch.IntTensor for sequence element | I wanna generate some random number with python and transform it to tensor with pytorch. Here is my code for generating the random number and transform it into tensor.
import numpy as np
import torch
P = np.random.uniform(0.5, 1, size=[20, 1])
k = np.random.randint(1, 20, size=[20, 1])
d_k = np.random.uniform(0, np.s... | The error is because k tensor is of dtype torch.int32 while other tensors P and d_k are of dtype torch.float32. But the cat operation requires all the input tensors to be of same type. From the documentation
torch.cat(tensors, dim=0, out=None) → Tensor
tensors (sequence of Tensors) – any python sequence of ten... | https://stackoverflow.com/questions/54403933/ |
name '_C' is not defined pytorch+jupyter notebook | I have some code that uses pytorch, that runs fine from my IDE (pycharm).
For research, I tried to run it from a jupyter notebook.
The code in the notebook:
from algorithms import Argparser
from algorithms import Session
def main():
print("main started")
args = Argparser.parse()
session = Session(args)
... | You need Cython for pytorch to work:
pip3 install Cython
See this comment on the issue on github.
My understanding is that there is a library called _C.cpython-37m-x86_64-linux-gnu.so in site-packages/torch which provides the shared object _C and requires Cython. PyCharm provides Cython support whereas the Jupyter ... | https://stackoverflow.com/questions/54408973/ |
LSTM autoencoder always returns the average of the input sequence | I'm trying to build a very simple LSTM autoencoder with PyTorch. I always train it with the same data:
x = torch.Tensor([[0.0], [0.1], [0.2], [0.3], [0.4]])
I have built my model following this link:
inputs = Input(shape=(timesteps, input_dim))
encoded = LSTM(latent_dim)(inputs)
decoded = RepeatVector(timesteps)(e... | 1. Initializing hidden states
In your source code you are using init_hidden_encoder and init_hidden_decoder functions to zero hidden states of both recurrent units in every forward pass.
In PyTorch you don't have to do that, if no initial hidden state is passed to RNN-cell (be it LSTM, GRU or RNN from the ones curren... | https://stackoverflow.com/questions/54411662/ |
How to balance (oversampling) unbalanced data in PyTorch (with WeightedRandomSampler)? | I have a 2-class problem and my data is highly unbalanced. I have 232550 samples from one class and 13498 from the second class. PyTorch docs and the internet tells me to use the class WeightedRandomSampler for my DataLoader.
I have tried using the WeightedRandomSampler but I keep getting errors.
trainratio = np... | The problem is in the type of trainset.labels
To fix the error it is possible to convert trainset.labels to float
| https://stackoverflow.com/questions/54415345/ |
PyTorch runtime error : invalid argument 0: Sizes of tensors must match except in dimension 1 | I have a PyTorch model and I'm trying to test it by performing a forward pass. Here is the code:
class ResBlock(nn.Module):
def __init__(self, inplanes, planes, stride=1):
super(ResBlock, self).__init__()
self.conv1x1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False)
self.c... | This issue arises from mismatch in size between the variables in the downsampling (encoder) path and the upsampling (decoder) path. Your code is huge and difficult to understand, but by inserting print statements, we can check that
en6add is of size [1, 512, 5, 5]
en7 is [1, 512, 2, 2]
en8 is [1, 512, 1, 1]
then ups... | https://stackoverflow.com/questions/54417736/ |
PyTorch Dataloader - List is not callable error when enumerating | When iterating over a PyTorch dataloader, e.g.
# define dataset, dataloader
train_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)
test_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)
trainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=Tru... | Did you remember to call transforms.Compose on your list of transforms?
In this line
train_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)
the transform parameter is expecting a callable object, not a list.
So, for example, this is wrong:
train_transforms = [
transforms.RandomResi... | https://stackoverflow.com/questions/54431671/ |
net.load_state_dict(torch.load('rnn_x_epoch.net')) not working on cpu | I am using pytorch to train a Neural Network. When I train and test on GPU, it works fine.
But When I try to load the model parameters on CPU using:
net.load_state_dict(torch.load('rnn_x_epoch.net'))
I get the following error:
RuntimeError: cuda runtime error (35) : CUDA driver version is insufficient for CUDA runt... | From the PyTorch documentation:
When you call torch.load() on a file which contains GPU tensors, those tensors will be loaded to GPU by default.
To load the model on CPU which was saved on GPU, you need to pass map_location argument as cpu in load function as follows:
# Load all tensors onto the CPU
net.load_st... | https://stackoverflow.com/questions/54435133/ |
Application of nn.Linear layer in pytorch on additional dimentions | How is the fully-connected layer (nn.Linear) in pytorch applied on "additional dimensions"? The documentation says, that it can be applied to connect a tensor (N,*,in_features) to (N,*,out_features), where N in the number of examples in a batch, so it is irrelevant, and * are those "additional" dimensions. Does it mean... | There are in_features * out_features parameters learned in linear.weight and out_features parameters learned in linear.bias. You can think of nn.Linear working as
reshape the tensor to some (N', in_features), where N' is the product of N and all dimensions described with *: input_2d = input.reshape(-1, in_features)
A... | https://stackoverflow.com/questions/54444630/ |
Unsupported Wheel Error when pip installing PyTorch without Conda | I have been trying to install PyTorch in Windows 10 for Python 3.7.1
I do not have Anaconda on my machine, and do not wish to install it. I believe I have already satisfied all the necessary prerequisites (CUDA v10.0, NumPy). When I run the following installation command in the admin command line, (found on the PyTorc... | The wheel I was trying to install required 32 bit Python, I had 64 bit Python installed. Therefore, the wheel I was trying to install was not compatible with my Python version.
Checking Python Version:
I confirmed my Python version using the following command:
python -c "import struct; print(struct.calcsize('P') *... | https://stackoverflow.com/questions/54445160/ |
AND-gate with Pytorch | I'm new to PyTorch and deep learning generally.
The code I wrote can be seen longer down.
I'm trying to learn the simple 'And' problem, which is linearby separable.
The problem is, that I'm getting poor results. Only around 2/10 times it gets to the correct answer.
Sometimes the loss.item() values is stuck at 0.250.
J... | 1. Using zero_grad with optimizer
You are not using optimizer.zero_grad() to clear the gradient. Your learning loop should look like this:
for epoch in range(epochs):
optimizer.zero_grad()
pred = model(data_x)
loss = criterion(pred, data_y)
loss.backward()
optimizer.step()
if (epoch + 1) % epo... | https://stackoverflow.com/questions/54445471/ |
How to properly update the weights in PyTorch? | I'm trying to implement the gradient descent with PyTorch according to this schema but can't figure out how to properly update the weights. It is just a toy example with 2 linear layers with 2 nodes in hidden layer and one output.
Learning rate = 0.05;
target output = 1
https://hmkcode.github.io/ai/backpropagation-ste... | You should use .zero_grad() with optimizer, so optimizer.zero_grad(), not loss or model as suggested in the comments (though model is fine, but it is not clear or readable IMO).
Except that your parameters are updated fine, so the error is not on PyTorch's side.
Based on gradient values you provided:
gradients = [te... | https://stackoverflow.com/questions/54447084/ |
Pytorch Inner Product of 3D tensor with 1D Tensor to generate 2D Tensor | Operation : I have pytorch tensor A of dimension [n x m x c] and B of dimension [1 x 1 x c]. I want to take inner product of each of 1 x 1 x c vector from A with B and hence generate a tensor C of dimension [n x m].
Inside forward function of my network at a specific step I receive tensor of dimension [N, channels, He... | There is a one-liner
ans = torch.einsum('nhwc,nc->nhw', img, aud)
The API of torch.einsum can be difficult to grasp if you haven't had any experience with it before, but it's extremely powerful and generalizes a great deal of liner algebra operations (transpositions, matrix multiplications and traces).
import t... | https://stackoverflow.com/questions/54458911/ |
Error with _DataLoaderIter in torch.utils.data.dataloader | I want to run a code which needs to import _DataLoaderIter from torch.utils.data.dataloader. By checking the source code for dataloader class, that method exist. However, I get the error:
Traceback (most recent call last):
File "main.py", line 4, in
import data
File "D:\Hyperspectral Data\RCAN\RCAN_... | Your comment answers the question: the _DataLoaderIter is there in 1.0.0 (for which you are linking documentation) but not in 0.3.1, as you can check here - its name has no preceding _.
This is a textbook example why it is a bad idea to access other packages' private classes/functions (customarily prefixed with an und... | https://stackoverflow.com/questions/54467696/ |
Pytorch - Are gradients transferred on creation of new Variables? | I have the following code:
A = Tensor of [186,3]
If I create a new empty tensor as follows:
tempTens = torch.tensor(np.zeros((186,3)), requires_grad = True).cuda()
And I apply some operations on a block of A and output it into tempTens, which I use totally for further computation, say like this:
tempTens[20,:] =... | In this case, tempTens[20,:] = SomeMatrix * A[20,:] is an in-place operation with respect to tempTens, which is generally not guaranteed to work with autograd. However, if you create a new variable by applying an operation like concatenation
output = torch.cat([SomeMatrix * A[20, :], torch.zeros(163, 3, device='cuda')... | https://stackoverflow.com/questions/54469928/ |
About custom operations in Tensorflow and PyTorch | I have to implement an energy function, termed Rigidity Energy, as in Eq 7 of this paper here.
The energy function takes as input two 3D object meshes, and returns the energy between them. The first mesh is the source mesh, and the second mesh is the deformed version of the source mesh. In rough psuedo-code, the comput... | As far as I understand, you are essentially asking if this operation can be vectorized. The answer is no, at least not fully, because svd implementation in PyTorch is not vectorized.
If you showed the tensorflow implementation, it would help in understanding your starting point. I don't know what you mean by finding t... | https://stackoverflow.com/questions/54473620/ |
how to resolve the error while installing pytorch | When i am trying to install pytorch getting an error.
All my packages are upgraded to the latest version. The error is
setup.py::build_deps::run()
Failed to run 'bash ../tools/build_pytorch_libs.sh --use-fbgemm --use-nnpack --use-mkldnn --use-qnnpack caffe2'
thank you in Advance
| I also got same error with older python versions. It resolved for me when i tried with latest python version 3.7
Hope this information may help you.
| https://stackoverflow.com/questions/54476603/ |
Can we use pytorch scatter_ on GPU | I'm trying to do one hot encoding on some data with pyTorch on GPU mode, however, it keeps giving me an exception. Can anybody help me?
Here's one example:
def char_OneHotEncoding(x):
coded = torch.zeros(x.shape[0], x.shape[1], 101)
for i in range(x.shape[1]):
coded[:,i] = scatter(x[:,i])
return c... | Yes, it is possible. You have to pay attention that all tensors are on GPU. In particular, by default, constructors like torch.zeros allocate on CPU, which will lead to this kind of mismatches. Your code can be fixed by constructing with device=x.device, as below
import torch
def char_OneHotEncoding(x):
coded =... | https://stackoverflow.com/questions/54479547/ |
Why can't I install new version of Pytorch? | My OS is CentOS 7, and I want to install PyTorch so I did the following:
(pt_gpu) [martin@A08-R32-I196-3-FZ2LTP2 mlm]$ conda -V
conda 4.6.2
(pt_gpu) [martin@A08-R32-I196-3-FZ2LTP2 mlm]$ conda install -c anaconda pytorch-gpu
What's strange is that the installation message shows that it is installing a very old vers... | According to their official website( https://pytorch.org ) , they install package named pytorch, not pytorch-gpu.
conda install pytorch torchvision -c pytorch
| https://stackoverflow.com/questions/54484769/ |
PyTorch: Is there a way to store model in CPU ram, but run all operations on the GPU for large models? | From what I see, most people seem to be initializing an entire model, and sending the whole thing to the GPU. But I have a neural net model that is too big to fit entirely on my GPU. Is it possible to keep the model saved in ram, but run all the operations on the GPU?
| I do not believe this is possible. However, one easy work around would be to split you model into sections that will fit into gpu memory along with your batch input.
Send the first part(s) of the model to gpu and calculate outputs
Release the former part of the model from gpu memory, and send the next section of the... | https://stackoverflow.com/questions/54485815/ |
Pytorch Argrelmax function (or C++) | I'm trying to find the equivalent pytorch (or C++) for scipy.signal.argrelmax(), which finds the peaks in a 1D array with some padding. https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.argrelmax.html
Here's what I've come up with and it is faster than scipy.signal.argrelmax - but I'm missing a ... | Ok, so someone on pytorch forums did have a pretty good solution: https://discuss.pytorch.org/t/pytorch-argrelmax-or-c-function/36404
Here's the full answer in case it gets deleted:
a = #1D Array of your choice
window_maxima = torch.nn.functional.max_pool1d_with_indices(a.view(1,1,-1), width, 1, padding=widt... | https://stackoverflow.com/questions/54498775/ |
Get corner of rectangle near to origin in batch of tensor given any two diagonal coordinates in pytorch | Let's say I have pytorch tensor of batch of coordinates of off diagonal elements and I want to get coordinate of the corner which is near to origin. coordinates are in (x1, y1, x2, y2) form.
a = torch.tensor([[3,2,2,3], [1,1,2,2])
# expected output
[[2,2], [1,1]]
| You can just iterate over all tensors and for each of them calculate distance to four corners and take the corner with minimum distance.
import torch
a = torch.tensor([[3,2,2,3], [1,1,2,2]])
c = torch.zeros(a.shape[0], 2)
for idx, x in enumerate(a):
d1 = x[0] ** 2 + x[1] ** 2
d2 = x[2] ** 2 + x[3] ** 2
d3 ... | https://stackoverflow.com/questions/54507023/ |
More efficient way of implement this equation in pytorch (or Numpy) | I'm implementing the analytical form of this function
where k(x,y) is a RBF kernel k(x,y) = exp(-||x-y||^2 / (2h))
My function prototype is
def A(X, Y, grad_log_px,Kxy):
pass
and X, Y are NxD matrix where N is batch size and D is a dimension. So X is a batch of x with size N in the above equation grad_log_px... | Given that that I inferred all the dimensions of the various terms correctly here's a way to go about it. But first a summary of the dimensions (screenshot as it's easier to explain with math type setting; please verify if they are correct):
Also note the double derivative of the second term which gives:
where su... | https://stackoverflow.com/questions/54509150/ |
PyTorch weak_script_method decorator | I came across some code in an introduction to Word2Vec and PyTorch that I'm not quite familiar with. I haven't seen this type of code structure before.
>>> import torch
>>> from torch import nn
>>> # an Embedding module containing 10 tensors of size 3
>>> embedding = nn.Embedding(1... | No, @weak_script_method has nothing to do with it. embedding(input) follows the Python function call syntax, which can be used with both "traditional" functions and with objects which define the __call__(self, *args, **kwargs) magic function. So this code
class Greeter:
def __init__(self, name):
self.name ... | https://stackoverflow.com/questions/54518808/ |
Best practices for exploration/exploitation in Reinforcement Learning | My question follows my examination of the code in the PyTorch DQN tutorial, but then refers to Reinforcement Learning in general: what are the best practices for optimal exploration/exploitation in reinforcement learning?
In the DQN tutorial, the steps_done variable is a global variable, and the EPS_DECAY = 200. This ... | well, for that I guess it is better to use the linear annealed epsilon-greedy policy which updates epsilon based on steps:
EXPLORE = 3000000 #how many time steps to play
FINAL_EPSILON = 0.001 # final value of epsilon
INITIAL_EPSILON = 1.0# # starting value of epsilon
if epsilon > FINAL_EPSILON:
epsi... | https://stackoverflow.com/questions/54519830/ |
I was training the lstm network using pytorch and encountered this error | I was training the lstm network using pytorch and encountered this error in jupyter notebook.
RuntimeError Traceback (most recent call last)
<ipython-input-16-b6b1e0b8cad1> in <module>()
4
5 # train the model
----> 6 train(net, encoded, epochs=n_epochs, batch_si... | Cast output vector of your network to Long (you have Int) as the error says.
Oh, and please provide Minimal, Complete and Verifiable example next time you ask a question.
| https://stackoverflow.com/questions/54522426/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.