instruction
stringlengths 13
150
| input
stringlengths 36
29.1k
| output
stringlengths 31
29.5k
| source
stringlengths 45
45
|
---|---|---|---|
Use only certain layers of pretrained torchvision network | I'm trying to use only certain layers in a pretrained torchvision Faster-RCNN network initialized by:
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
model.eval()
This works. However, passing model.modules() or model.children() into an nn.Sequential yields an error. Even passing the whole model leads to errors, e.g.
model = torch.nn.Sequential(*model.modules())
model.eval()
# x is a [C, H, W] image
y = model(x)
leads to
AttributeError: 'dict' object has no attribute 'dim'
and
model = torch.nn.Sequential(*model.children())
model.eval()
# x is a [C, H, W] image
y = model(x)
leads to
TypeError: conv2d(): argument 'input' (position 1) must be Tensor, not tuple
This confuses me because I have modified other PyTorch pretrained models like that in the past. How can I use the FasterRCNN pretrained model to create a new (pretrained) model that uses only certain layers, e.g. all layers but the last one?
| Unlike other simple CNN models, it is not trivial to convert an R-CNN based detector to a simple nn.Sequential model. If you look at the functionality of R-CNN ('generalized_rcnn.py') you'll see that the output features (computed by the FCN backbone) are not just passed to the RPN component, but rather combined with the input image and even with the targets (during training).
Therefore, I suppose if you want to change the way faster R-CNN behaves, you'll have to use the base class torchvision.models.detection.FasterRCNN() and provide it with different roi pooling parameters.
| https://stackoverflow.com/questions/56455302/ |
How convert a list with None in it to torch.tensor()? | For example I have a variable z = [1, 3, None, 5, 6]
I would like to do: torch.tensor(z)
and get something like the following:
torch.tensor([1,3, None, 5,6], dtype=torch.float)
Howhever, such attempt raises an error
TypeError: must be real number, not NoneType
Is there a way to convert such list to a torch.tensor?
I don't want to impute this None value with something else. Numpy arrays are capable of converting such lists np.array([1, 3, None, 5, 6]), but I'd prefer not to convert back and forth variable either.
| It depends on what you do. Probable the best is to convert None to 0.
Converting things to numpy arrays and then to Torch tensors is a very good path since it will convert None to np.nan. Then you can create the Torch tensor even holding np.nan.
import torch
import numpy as np
a = [1,3, None, 5,6]
b = np.array(a,dtype=float) # you will have np.nan from None
print(b) #[ 1. 3. nan 5. 6.]
np.nan_to_num(b, copy=False)
print(b) #[1. 3. 0. 5. 6.]
torch.tensor(b, dtype=torch.float) #tensor([1., 3., 0., 5., 6.])
Try also copy=True inside np.nan_to_num and you will get nan inside your tensor instead of 0.
| https://stackoverflow.com/questions/56455944/ |
DataLoader num_workers vs torch.set_num_threads | Is there a difference between the parallelization that takes place between these two options? I’m assuming num_workers is solely concerned with the parallelizing the data loading. But is setting torch.set_num_threads for training in general? Trying to understand the difference between these options. Thanks!
| The num_workers for the DataLoader specifies how many parallel workers to use to load the data and run all the transformations. If you are loading large images or have expensive transformations then you can be in situation where GPU is fast to process your data and your DataLoader is too slow to continuously feed the GPU. In that case setting higher number of workers helps. I typically increase this number until my epoch step is fast enough. Also, a side tip: if you are using docker, usually you want to set shm to 1X to 2X number of workers in GB for large dataset like ImageNet.
The torch.set_num_threads specifies how many threads to use for parallelizing CPU-bound tensor operations. If you are using GPU for most of your tensor operations then this setting doesn't matter too much. However, if you have tensors that you keep on cpu and you are doing lot of operations on them then you might benefit from setting this. Pytorch docs, unfortunately, don't specify which operations will benefit from this so see your CPU utilization and adjust this number until you can max it out.
| https://stackoverflow.com/questions/56463317/ |
Making a Prediction Sagemaker Pytorch | I have trained and deployed a model in Pytorch with Sagemaker. I am able to call the endpoint and get a prediction. I am using the default input_fn() function (i.e. not defined in my serve.py).
model = PyTorchModel(model_data=trained_model_location,
role=role,
framework_version='1.0.0',
entry_point='serve.py',
source_dir='source')
predictor = model.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')
A prediction can be made as follows:
input ="0.12787057, 1.0612601, -1.1081504"
predictor.predict(np.genfromtxt(StringIO(input), delimiter=",").reshape(1,3) )
I want to be able to serve the model with REST API and am HTTP POST using lambda and API gateway. I was able to use invoke_endpoint() for this with an XGBOOST model in Sagemaker this way. I am not sure what to send into the body for Pytorch.
client = boto3.client('sagemaker-runtime')
response = client.invoke_endpoint(EndpointName=ENDPOINT ,
ContentType='text/csv',
Body=???)
I believe I need to understand how to write the customer input_fn to accept and process the type of data I am able to send through invoke_client. Am I on the right track and if so, how could the input_fn be written to accept a csv from invoke_endpoint?
| Yes you are on the right track. You can send csv-serialized input to the endpoint without using the predictor from the SageMaker SDK, and using other SDKs such as boto3 which is installed in lambda:
import boto3
runtime = boto3.client('sagemaker-runtime')
payload = '0.12787057, 1.0612601, -1.1081504'
response = runtime.invoke_endpoint(
EndpointName=ENDPOINT_NAME,
ContentType='text/csv',
Body=payload.encode('utf-8'))
result = json.loads(response['Body'].read().decode())
This will pass to the endpoint a csv-formatted input, that you may need to reshape back in the input_fn to put in the appropriate dimension expected by the model.
for example:
def input_fn(request_body, request_content_type):
if request_content_type == 'text/csv':
return torch.from_numpy(
np.genfromtxt(StringIO(request_body), delimiter=',').reshape(1,3))
Note: I wasn't able to test the specific input_fn above with your input content and shape but I used the approach on Sklearn RandomForest couple times, and looking at the Pytorch SageMaker serving doc the above rationale should work.
Don't hesitate to use endpoint logs in Cloudwatch to diagnose any inference error (available from the endpoint UI in the console), those logs are usually much more verbose that the high-level logs returned by the inference SDKs
| https://stackoverflow.com/questions/56467434/ |
Randomness in VGG16 prediction | I am using the VGG-16 network available in pytorch out of the box to predict some image index. I found out that for same input file, if i predict multiple time, I get different outcome. This seems counter-intuitive to me. Once the weights are predicted ( since I am using the pretrained model) there should not be any randomness at any step, and hence multiple run with same input file shall return same prediction.
Here is my code:
import torch
import torchvision.models as models
VGG16 = models.vgg16(pretrained=True)
def VGG16_predict(img_path):
transformer = transforms.Compose([transforms.CenterCrop(224),transforms.ToTensor()])
data = transformer(Image.open(img_path))
output = softmax(VGG16(data.unsqueeze(0)), dim=1).argmax().item()
return output # predicted class index
VGG16_predict(image)
Here is the image
| Recall that many modules have two states for training vs evaluation: "Some models use modules which have different training and evaluation behavior, such as batch normalization. To switch between these modes, use model.train() or model.eval() as appropriate. See train() or eval() for details." (https://pytorch.org/docs/stable/torchvision/models.html)
In this case, the classifier layers include dropout, which is stochastic during training. Run VGG16.eval() if you want the evaluations to be non-random.
| https://stackoverflow.com/questions/56483252/ |
Passing tensorDataset or Dataloader to skorch | I want to apply cross validation in Pytorch using skorch, so I prepared my model and my tensorDataset which returns (image,caption and captions_length) and so it has X and Y, so I'll not be able to set Y in the method
net.fit(dataset)
but when I tried that I got an error :
ValueError: Stratified CV requires explicitly passing a suitable y
Here's part of my code:
start = time.time()
net = NeuralNetClassifier(
decoder, criterion= nn.CrossEntropyLoss,
max_epochs=args.epochs,
lr=args.lr,
optimizer=optim.SGD,
device='cuda', # uncomment this to train with CUDA
)
net.fit(dataset, y=None)
end = time.time()
|
You are (implicitly) using the internal CV split of skorch which uses a stratified split in case of the NeuralNetClassifier which in turn needs information about the labels beforehand.
When passing X and y to fit separately this works fine since y is accessible at all times. The problem is that you are using torch.dataset.Dataset which is lazy and does not give you access to y directly, hence the error.
Your options are the following.
Set train_split=None to disable the internal CV split
net = NeuralNetClassifier(
train_split=None,
)
You will lose internal validation and, as such, features like early stopping.
Split your data beforehand
Split your dataset into two datasets, dataset_train and dataset_valid,
then use skorch.helper.predefined_split:
net = NeuralNetClassifier(
train_split=predefined_split(dataset_valid),
)
You lose nothing but depending on your data this might be complicated.
Extract your y and pass it to fit
y_train = np.array([y for X, y in iter(my_dataset)])
net.fit(my_dataset, y=y_train)
This only works if your y fits into memory. Since you are using TensorDataset you can also do the following to extract your y:
y_train = my_dataset.y
| https://stackoverflow.com/questions/56490278/ |
torch-1.1.0-cp37-cp37m-win_amd64.whl is not a supported wheel on this platform | I need to use pyTorch when developing a RNN and whenever I try to install it I'm getting an error saying torch-1.1.0-cp37-cp37m-win_amd32.whl is not a supported wheel on this platform.
pip3 install https://download.pytorch.org/whl/cpu/torch-1.1.0-cp37-cp37m-win_amd32.whl
This is how I tried to install it according to https://pytorch.org/.
I'm using,
Python 3.7.3 (default, Mar 27 2019, 17:13:21) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Any help would be appreciated. Thanks in advance!
| you are using anaconda you can install pytorch using
conda install pytorch-cpu torchvision-cpu -c pytorch
as written on the main pytorch page.
| https://stackoverflow.com/questions/56491650/ |
Python __getattr__ called and enter infinite recursion even the attribute is not missing | I define a NE_Conv2d class and override its __getattr__. When I try to get an existing attribute from one instance of this class, __getattr__ is called and enter infinite recursion.
I know one need to deal with __getattr__ carefully to avoid infinite recursion, but apparently the conv attribute already exists after __init__ is called. So when I try to get conv attribute, __getattr__ should not be called.
from torch import nn
class NE_Conv2d(nn.Module):
'''Nonexpansive conv2d'''
def __init__(self, *k, **kw):
super(NE_Conv2d, self).__init__()
self.conv = nn.Conv2d(*k, **kw)
print('foo')
def __getattr__(self, attr):
return getattr(self.conv, attr)
a = NE_Conv2d(3, 32, 5)
print(a)
print(a.conv)
Above code should print info about a and a.conv, but enter infinite recursion when trying to get a.conv.
| I seem to know what's wrong... setattr and getattr of nn.Module is reloaded...
| https://stackoverflow.com/questions/56497789/ |
I am getting error when importing torch and torch vision | I installed torch and torchvision using pip3 on MAC. When I imported the same, getting the below error.
Environment:
OS : macOS High Sierra
Python : 3.7
pip : 3
Pytorch 1.1
code:
import torch
import torchvision
Error:
ImportError Traceback (most recent call
last) in
1 import numpy as np
2 from glob import glob
----> 3 import torch
4 import torchvision
5 from torchvision import datasets
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/init.py
in
77 del _dl_flags
78
---> 79 from torch._C import *
80
81 all += [name for name in dir(_C)
ImportError:
dlopen(/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/_C.cpython-37m-darwin.so,
9): Library not loaded: /usr/local/opt/libomp/lib/libomp.dylib
Referenced from:
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/lib/libshm.dylib
Reason: image not found
Any help on solving this error would be appreciated.
| i think
$ brew install libomp
can help u, cause i solve the same problem by it.
according
github-issue-"libomp.dylib can't be loaded"
| https://stackoverflow.com/questions/56510691/ |
Loading original images besides the transformed ones using ImageFolder | I'm trying to train a GAN to colorize images. For that, I'm using ImageFolder of torchvision to load grayscale images but I also need the original data alongwith the transformed ones.
I want it in the fastest way as the data is large. I want to make ImageFolder load both at the same time to reduce the time complexity.
def load_data_bw(opt):
datapath = '/content/gdrive/My Drive/faces/2003'
dataset = torchvision.datasets.ImageFolder(datapath,
transform=transforms.Compose([
transforms.Grayscale(num_output_channels=3), #load images as grayscale with three channels
transforms.RandomChoice(
[transforms.Resize(opt['loadSize'], interpolation=1),
transforms.Resize(opt['loadSize'], interpolation=2),
transforms.Resize(opt['loadSize'], interpolation=3),
transforms.Resize((opt['loadSize'], opt['loadSize']),
interpolation=1),
transforms.Resize((opt['loadSize'], opt['loadSize']),
interpolation=2),
transforms.Resize((opt['loadSize'], opt['loadSize']),
interpolation=3)]
),
transforms.RandomChoice(
[transforms.RandomResizedCrop(opt['fineSize'], interpolation=1),
transforms.RandomResizedCrop(opt['fineSize'], interpolation=2),
transforms.RandomResizedCrop(opt['fineSize'], interpolation=3)]
),
transforms.ColorJitter(brightness=0.1, contrast=0.1),
transforms.RandomHorizontalFlip(),
transforms.ToTensor()
]))
return dataset
I'm expecting to get:
for iteration, orig_data, gray_data in enumerate(training_data_loader, 1):
# code..
| I assume you have 2 dataset variables i.e. dataset_bw and dataset_color that you can load as you mention using ImageFolder. Then you could do the following :
class GAN_dataset(Dataset):
def __init__(self, dataset_bw, dataset_color):
self.dataset1 = dataset_bw
self.dataset2 = dataset_color
def __getitem__(self, index):
x1 = self.dataset1[index]
x2 = self.dataset2[index]
return x1, x2
def __len__(self):
return len(self.dataset1)
dataset = GAN_dataset(dataset_bw, dataset_color)
loader = DataLoader(dataset, batch_size = ...)
This way you when you iterate through loader, you will get two images as you require.
| https://stackoverflow.com/questions/56513117/ |
Implementing self attention | I am trying to implement self attention in Pytorch.
I need to calculate the following expressions.
Similarity function S (2 dimensional), P(2 dimensional), C'
S[i][j] = W1 * inp[i] + W2 * inp[j] + W3 * x1[i] * inp[j]
P[i][j] = e^(S[i][j]) / Sum for all j( e ^ (S[i]))
basically, P is a softmax function
C'[i] = Sum (for all j) P[i][j] * x1[j]
I tried the following code using for loops
for i in range(self.dim):
for j in range(self.dim):
S[i][j] = self.W1 * x1[i] + self.W2 * x1[j] + self.W3 * x1[i] * x1[j]
for i in range(self.dim):
for j in range(self.dim):
P[i][j] = torch.exp(S[i][j]) / torch.sum( torch.exp(S[i]))
# attend
for i in range(self.dim):
out[i] = 0
for j in range(self.dim):
out[i] += P[i][j] * x1[j]
Is there any faster way to implement this in Pytorch?
| Here is an example of Self Attention I had implemented in Dual Attention for HSI Imagery
class PAM_Module(Module):
""" Position attention module https://github.com/junfu1115/DANet/blob/master/encoding/nn/attention.py"""
#Ref from SAGAN
def __init__(self, in_dim):
super(PAM_Module, self).__init__()
self.chanel_in = in_dim
self.query_conv = Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1)
self.key_conv = Conv2d(in_channels=in_dim, out_channels=in_dim//8, kernel_size=1)
self.value_conv = Conv2d(in_channels=in_dim, out_channels=in_dim, kernel_size=1)
self.gamma = Parameter(torch.zeros(1))
self.softmax = Softmax(dim=-1)
def forward(self, x):
"""
inputs :
x : input feature maps( B X C X H X W)
returns :
out : attention value + input feature
attention: B X (HxW) X (HxW)
"""
m_batchsize, C, height, width = x.size()
proj_query = self.query_conv(x).view(m_batchsize, -1, width*height).permute(0, 2, 1)
proj_key = self.key_conv(x).view(m_batchsize, -1, width*height)
energy = torch.bmm(proj_query, proj_key)
attention = self.softmax(energy)
proj_value = self.value_conv(x).view(m_batchsize, -1, width*height)
out = torch.bmm(proj_value, attention.permute(0, 2, 1))
out = out.view(m_batchsize, C, height, width)
out = self.gamma*out + x
#out = F.avg_pool2d(out, out.size()[2:4])
return out
| https://stackoverflow.com/questions/56515513/ |
Partial slices in pytorch / numpy with arbitrary and variable number of dimensions | Given an 2-dimensional tensor in numpy (or in pytorch), I can partially slice along all dimensions at once as follows:
>>> import numpy as np
>>> a = np.arange(2*3).reshape(2,3)
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
>>> a[1:,1:]
array([[ 5, 6, 7],
[ 9, 10, 11]])
How can I achieve the same slicing pattern regardless of the number of dimensions in the tensor if I do not know the number of dimensions at implementation time? (i.e. I want a[1:] if a has only one dimension, a[1:,1:] for two dimensions, a[1:,1:,1:] for three dimensions, and so on)
It would be nice if I could do it in a single line of code like the following, but this is invalid:
a[(1:,) * len(a.shape)] # SyntaxError: invalid syntax
I am specifically interested in a solution that works for pytorch tensors (just substitute torch for numpy above and the example is the same), but I figure it is likely and best if the solution works for both numpy and pytorch.
| Answer:
Making a tuple of slice objects does the trick:
a[(slice(1,None),) * len(a.shape)]
Explanation:
slice is a builtin python class (not tied to numpy or pytorch) which provides an alternative to the subscript notation for describing slices. The answer to a different question suggests using this as a way to store slice information in python variables. The python glossary points out that
The bracket (subscript) notation uses slice objects internally.
Since the __getitem__ methods for numpy ndarrays and pytorch tensors support multi-dimensional indexing with slices, they must also support multidimensional indexing with slice objects, and so we can make a tuple of those slices that of the right length.
Btw, you can see how python uses the slice objects by creating a dummy class as follows and then do slicing on it:
class A(object):
def __getitem__(self, ix):
return ix
print(A()[5]) # 5
print(A()[1:]) # slice(1, None, None)
print(A()[1:,1:]) # (slice(1, None, None), slice(1, None, None))
print(A()[1:,slice(1,None)]) # (slice(1, None, None), slice(1, None, None))
| https://stackoverflow.com/questions/56534732/ |
Output of a CNN doesn't change much with the input | I have been trying to implement Actor Critic with a convolutional neural network. There are two different images as the state for the reinforcement learning agent. The output(actions for Actor) of the CNN is the (almost)same for different inputs after (random)initialisation. Due to this even after training the agent never learns anything useful.
State definitions(2 inputs):
Input 1: [1,1,90,128] image with maximum value for the pixel being 45.
Input 2: [1,1,45,80] image with maximum value for the pixel being 45.
Expected output by the actor: [x,y]: a 2-dimensional vector according to the state. Here x is expected in the range [0,160] and y is expected in the range [0,112]
Different types of modifications tried with the input:
1: Feed both the images as it is.
2: Feed both images with normalisation as (img/45) so that pixel values are from [0,1]
3:Feed both images with normalisation as 2*((img/45)-0.5) so that pixel values are from [-1,1]
4: Feed both images with normalisation as (img-mean)/std
Result: The output of the CNN remains almost same.
The code for the definition of actor has been given below.
import numpy as np
import pandas as pd
from tqdm import tqdm
import time
import cv2
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Actor(nn.Module):
def __init__(self, action_dim, max_action):
super(Actor,self).__init__()
# state image [1,1,90,128]
self.conv11 = nn.Conv2d(1,16,5)
self.conv11_bn = nn.BatchNorm2d(16)
self.conv12 = nn.Conv2d(16,16,5)
self.conv12_bn = nn.BatchNorm2d(16)
self.fc11 = nn.Linear(19*29*16,500)
# dim image [1,1,45,80]
self.conv21 = nn.Conv2d(1,16,5)
self.conv21_bn = nn.BatchNorm2d(16)
self.conv22 = nn.Conv2d(16,16,5)
self.conv2_bn = nn.BatchNorm2d(16)
self.fc21 = nn.Linear(8*17*16,250)
# common pool
self.pool = nn.MaxPool2d(2,2)
# after concatenation
self.fc2 = nn.Linear(750,100)
self.fc3 = nn.Linear(100,10)
self.fc4 = nn.Linear(10,action_dim)
self.max_action = max_action
def forward(self,x,y):
# state image
x = self.conv11_bn(self.pool(F.relu(self.conv11(x))))
x = self.conv11_bn(self.pool(F.relu(self.conv12(x))))
x = x.view(-1,19*29*16)
x = F.relu(self.fc11(x))
# state dim
y = self.conv11_bn(self.pool(F.relu(self.conv21(y))))
y = self.conv11_bn(self.pool(F.relu(self.conv22(y))))
y = y.view(-1,8*17*16)
y = F.relu(self.fc21(y))
# concatenate
z = torch.cat((x,y),dim=1)
z = F.relu(self.fc2(z))
z = F.relu(self.fc3(z))
z = self.max_action*torch.tanh(self.fc4(z))
return z
# to read different sample states for testing
obs = []
for i in range(200):
obs.append(np.load('eval_episodes/obs_'+str(i)+'.npy',allow_pickle=True))
obs = np.array(obs)
def tensor_from_numpy(state):
# to add dimensions to tensor to make it [batch_size,channels,height,width]
state_img = state
state_img = torch.from_numpy(state_img).float()
state_img = state_img[np.newaxis, :]
state_img = state_img[np.newaxis, :].to(device)
return state_img
actor = Actor(2,torch.FloatTensor([160,112]))
for i in range(20):
a = tensor_from_numpy(obs[i][0])
b = tensor_from_numpy(obs[i][2])
print(actor(a,b))
Output of the above code:
tensor([[28.8616, 3.0934]], grad_fn=<MulBackward0>)
tensor([[27.4125, 3.2864]], grad_fn=<MulBackward0>)
tensor([[28.2210, 2.6859]], grad_fn=<MulBackward0>)
tensor([[27.6312, 3.9528]], grad_fn=<MulBackward0>)
tensor([[25.9290, 4.2942]], grad_fn=<MulBackward0>)
tensor([[26.9652, 4.5730]], grad_fn=<MulBackward0>)
tensor([[27.1342, 2.9612]], grad_fn=<MulBackward0>)
tensor([[27.6494, 4.2218]], grad_fn=<MulBackward0>)
tensor([[27.3122, 1.9945]], grad_fn=<MulBackward0>)
tensor([[29.6915, 1.9938]], grad_fn=<MulBackward0>)
tensor([[28.2001, 2.5967]], grad_fn=<MulBackward0>)
tensor([[26.8502, 4.4917]], grad_fn=<MulBackward0>)
tensor([[28.6489, 3.2022]], grad_fn=<MulBackward0>)
tensor([[28.1455, 2.7610]], grad_fn=<MulBackward0>)
tensor([[27.2369, 3.4243]], grad_fn=<MulBackward0>)
tensor([[25.9513, 5.3057]], grad_fn=<MulBackward0>)
tensor([[28.1400, 3.3242]], grad_fn=<MulBackward0>)
tensor([[28.2049, 2.6622]], grad_fn=<MulBackward0>)
tensor([[26.7446, 2.5966]], grad_fn=<MulBackward0>)
tensor([[25.3867, 5.0346]], grad_fn=<MulBackward0>)
The states(.npy) files can be found here
For different states the actions should vary from [0-160,0-112] but here the outputs just vary a little bit.
Note: the input images are initially sparse(lots of zeros in the image)
Is there a problem with the state pixel values or the network definition?
EDIT: I think the problem has got to do something with the normalisation or the sparsity of the inputs, because I also tried the same network with tensorflow and am facing the same problem there.
| The problem with this was that the weight initialization was not appropriate. I used Gaussian initialization with twice the standard deviation as of the default. This helped in giving different outputs for different inputs. Although after a few episodes of training the actor starts giving the same value once again, which is due the the critic network getting saturated.
| https://stackoverflow.com/questions/56541683/ |
Batch-Matrix multiplication in Pytorch - Confused with the handling of the output's dimension | I got two arrays :
A
B
Array A contains a batch of RGB images, with shape:
[batch, Width, Height, 3]
whereas Array B contains coefficients needed for a "transformation-like" operation on images, with shape:
[batch, 4, 4, 3]
To put it simply, the operation for a single image is a multiplication that outputs an environment map (normalMap * Coefficients).
The output I want should hold shape:
[batch, Width, Height, 3]
I tried using torch.bmm but failed. Is this possible somehow?
| I think you need to calculate that PyTorch works with
BxCxHxW : number of mini-batches, channels, height, width
format, and also use matmul, since bmm works with tensors or ndim/dim/rank =3.
I know you may find this online, but for any case:
batch1 = torch.randn(10, 3, 20, 10)
batch2 = torch.randn(10, 3, 10, 30)
res = torch.matmul(batch1, batch2)
res.size() # torch.Size([10, 3, 20, 30])
| https://stackoverflow.com/questions/56543924/ |
No module named 'cupy' on Google Colab | I'm working on the FastPhotoStyle project:
https://github.com/NVIDIA/FastPhotoStyle
and I follow the steps of its tutorial:
https://github.com/NVIDIA/FastPhotoStyle/blob/master/TUTORIAL.md
I'm running Example 1 on Google Colab where default environment is
CUDA 10.0
Python 3.6
Chainer 5.4.0
CuPy 5.4.0
This is how I tried on Colab Notebook:
https://colab.research.google.com/drive/1oBgdJgXCLlUQhpwPoG1Uom3OKTzHR4BF
After running
!python3 demo.py --output_image_path results/example1.png
Here's the error message I got:
Traceback (most recent call last): File "demo.py", line 9, in
import process_stylization
File "/content/drive/FastPhotoStyle/process_stylization.py", line 14,
in
from smooth_filter import smooth_filter
File "/content/drive/FastPhotoStyle/smooth_filter.py", line 327, in
from cupy.cuda import function
ModuleNotFoundError: No module named 'cupy'
Could someone help me with it please?
| have you tried running the demo with python full path?
!/usr/local/lib/python3.6//bin/python3 demo.py --output_image_path
or running without anaconda installation by simple install all necessary libraries
!pip install cupy
or see installation instructions here
| https://stackoverflow.com/questions/56563973/ |
why does linear regression converge slower if we use two layers of linear module? | I have tested linear regression of 1d input and 1d output by pytorch using three different ways.
One is using the formula from linear algebra,
the other one is using nn.Linear(1,1). These two always give identical solution.
However, when I use two layers: nn.Linear(1,2) and nn.Linear(2,1) sequentially for the third approach, the result does not converge at first. After I set learning rate much smaller and epoch number much bigger, it finally shows its convergence.
In theory, because composition of linear transform is again linear transform, they shall give the same answer no matter one layer and two layers.
Intuitively, I thought more neurons and layers make things more efficient. But this shows its opposite and I do not understand.
The code is in github. Please directly jump in the last shell for the third approach.
The expected result is given in both first and second approaches in the notebook.
| This is not surprising. With 2 Linear layers which, as you know, effectively express what a single Linear layer could, you're introducing a bunch of redundant degrees of freedom - different assignments of values to the two layers, which result in the same effective transformation. The optimizer can therefore "walk around" different solutions, which look the same in terms of the loss function (because they mathematically are the same), without converging to a single one. In other words, you cannot converge to a solution if there is an infinite number of them, all looking the same to you.
| https://stackoverflow.com/questions/56568667/ |
Need a vectorized solution in pytorch | I'm doing an experiment using face images in PyTorch framework. The input x is the given face image of size 5 * 5 (height * width) and there are 192 channels.
Objective: To obtain patches of x of patch_size(given as argument).
I have obtained the required result with the help of two for loops. But I want a better-vectorized solution so that the computation cost will be very less than using two for loops.
Used: PyTorch 0.4.1, (12 GB) Nvidia TitanX GPU.
The following is my implementation using two for loops
def extractpatches( x, patch_size): # x is bsx192x5x5
patches = x.unfold( 2, patch_size , 1).unfold(3,patch_size,1)
bs,c,pi,pj, _, _ = patches.size() #bs,192,
cnt = 0
p = torch.empty((bs,pi*pj,c,patch_size,patch_size)).to(device)
s = torch.empty((bs,pi*pj, c*patch_size*patch_size)).to(device)
//Want a vectorized method instead of two for loops below
for i in range(pi):
for j in range(pj):
p[:,cnt,:,:,:] = patches[:,:,i,j,:,:]
s[:,cnt,:] = p[:,cnt,:,:,:].view(-1,c*patch_size*patch_size)
cnt = cnt+1
return s
Thanks for your help in advance.
| I think you can try this as following. I used some parts of your code for my experiment and it worked for me. Here l and f are the lists of tensor patches
l = [patches[:,:,int(i/pi),i%pi,:,:] for i in range(pi * pi)]
f = [l[i].contiguous().view(-1,c*patch_size*patch_size) for i in range(pi * pi)]
You can verify the above code using toy input values.
Thanks.
| https://stackoverflow.com/questions/56573469/ |
Pytorch DataLoader fails when the number of examples are not exactly divided by the batch size | I have coded a custom data loader class in the pytorch. But it fails when iterating through all the number of batches inside an epoch. For example, think I have 100 data examples and my batch size is 9. It will fail in the 10th iteration saying batch size is different which will give a batch size 1 instead of 10. I have put my custom data loader in below. Also I have put how I extract the data from the loader inside the for-loop.
class FlatDirectoryAudioDataset(tdata.Dataset): #customized dataloader
def __init__(self, data_dir, transform=None):
self.data_dir = data_dir
self.transform = transform
self.files = self.__setup_files()
def __len__(self):
"""
compute the length of the dataset
:return: len => length of dataset
"""
return len(self.files)
def __setup_files(self):
file_names = os.listdir(self.data_dir)
files = [] # initialize to empty list
for file_name in file_names:
possible_file = os.path.join(self.data_dir, file_name)
if os.path.isfile(possible_file) and (file_name.lower().endswith('.wav') or file_name.lower().endswith('.mp3')): #&& (possible_file.lower().endswith('.wav') or possible_file.lower().endswith('.mp3')):
files.append(possible_file)
# return the files list
return files
def __getitem__ (self,index):
sample, _ = librosa.load(self.files[index], 16000)
if self.transform:
sample=self.transform(sample)
sample = torch.from_numpy(sample)
return sample
from torch.utils.data import DataLoader
my_dataset=FlatDirectoryAudioDataset(source_directory,source_folder,source_label,transform = None,label=True)
dataloader_my = DataLoader(
my_dataset,
batch_size=batch_size,
num_workers=0,
shuffle=True)
for (i,batch) in enumerate(dataloader_my,0):
print(i)
if batch.shape[0]!=16:
print(batch.shape)
assert batch.shape[0]==16,"Something wrong with the batch size"
| use drop_last=True utils.DataLoader(dataset,batch_size=batch_size,shuffle = True,drop_last=True)
https://pytorch.org/docs/stable/data.html
| https://stackoverflow.com/questions/56576716/ |
Correct data loading, splitting and augmentation in Pytorch | The tutorial doesn't seem to explain how we should load, split and do proper augmentation.
Let's have a dataset consisting of cars and cats. The folder structure would be:
data
cat
0101.jpg
0201.jpg
...
dogs
0101.jpg
0201.jpg
...
At first, I loaded the dataset by datasets.ImageFolder function. Image Function has command "TRANSFORM" where we can set some augmentation commands, but we don't want to apply augmentation to test dataset! So let's stay with transform=None.
data = datasets.ImageFolder(root='data')
Apparently, we don't have folder structure train and test and therefore I assume a good approach would be to use split_dataset function
train_size = int(split * len(data))
test_size = len(data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(data, [train_size, test_size])
Now let's load the data the following way.
train_loader = torch.utils.data.DataLoader(train_dataset,
batch_size=8,
shuffle=True)
test_loader = torch.utils.data.DataLoader(test_dataset,
batch_size=8,
shuffle=True)
How can I apply transformations (data augmentation) to the "train_loader" images?
Basically I need to: 1. load data from the folder structure explained above
2. split the data into test/train parts
3. apply augmentations on train part.
| I am not sure if there is a recommended way of doing this, but this is how I would workaround this problem:
Given that torch.utils.data.random_split() returns Subset, we cannot (can we? not 100% sure here I double-checked, we cannot) exploit their inner datasets, because they are the same (the only diference is in the indices). In this context, I would implement a simple class to apply transformations, something like this:
from torch.utils.data import Dataset
class ApplyTransform(Dataset):
"""
Apply transformations to a Dataset
Arguments:
dataset (Dataset): A Dataset that returns (sample, target)
transform (callable, optional): A function/transform to be applied on the sample
target_transform (callable, optional): A function/transform to be applied on the target
"""
def __init__(self, dataset, transform=None, target_transform=None):
self.dataset = dataset
self.transform = transform
self.target_transform = target_transform
# yes, you don't need these 2 lines below :(
if transform is None and target_transform is None:
print("Am I a joke to you? :)")
def __getitem__(self, idx):
sample, target = self.dataset[idx]
if self.transform is not None:
sample = self.transform(sample)
if self.target_transform is not None:
target = self.target_transform(target)
return sample, target
def __len__(self):
return len(self.dataset)
And then use it before passing the dataset to the dataloader:
import torchvision.transforms as transforms
train_transform = transforms.Compose([
transforms.ToTensor(),
# ...
])
train_dataset = ApplyTransform(train_dataset, transform=train_transform)
# continue with DataLoaders...
| https://stackoverflow.com/questions/56582246/ |
Multiply all elements of PyTorch tensor | I wanted to do something like this question in PyTorch i.e. multiply all elements with each other keeping a certain axis constant. Does PyTorch has any pre-defined function for this?
| Yes. torch.prod. Use the dim parameter to tell which along which axis you want the product to be computed.
x = torch.randn((2, 2))
print(x)
print(torch.prod(x, 0)) # product along 0th axis
This prints
tensor([[-0.3661, 1.0693],
[0.5144, 1.3489]])
tensor([-0.1883, 1.4424])
| https://stackoverflow.com/questions/56592745/ |
How to install older version of pytorch | Following this https://pytorch.org/get-started/previous-versions/#via-pip
pip install torch==0.2.0_4 -f https://download.pytorch.org/whl/cpu/stable
Collecting torch==0.2.0_4
Could not find a version that satisfies the requirement torch==0.2.0_4 (from versions: 0.1.2, 0.1.2.post1, 0.3.1, 0.4.0, 0.4.1, 1.0.0, 1.0.1, 1.0.1.post2, 1.1.0)
No matching distribution found for torch==0.2.0_4
How to install older version of pytorch?
| pip install torch==
Collecting torch==
ERROR: Could not find a version that satisfies the requirement torch== (from versions: 0.1.2, 0.1.2.post1, 0.4.1, 1.0.0, 1.0.1, 1.0.1.post2, 1.1.0)
ERROR: No matching distribution found for torch==
This means that version 0.2 is not available
You can download the specific version (wheels seem available) and install it with pip install
| https://stackoverflow.com/questions/56598674/ |
Why does training accuracy fall after reaching perfect training fit? | I am training a NN in pytorch on MNIST data. The model start well, improves, reaches good accuracy for both training and testing data, stabilizes for a while and then both the testing and training accuracy collapse, as shown on the following base results graph.
As for MNIST, I use 60000 training images, 10000 testing, training batch size 100 and learning rate 0.01. Neural network consist of two fully connected hidden layers, each with 100 nodes, nodes having ReLU activation functions. F.cross_entropy is used for loss and SGD for gradients calculations.
This is not the over-fitting problem, as it is both the training and testing accuracy which collapse. I suspected that it has something to do with too large learning rate. In the base case I have used 0.01 but when I lower it to 0.001 the whole pattern repeats, just later, as shown on the following graph (please notice x-axis scale change, the pattern is happening roughly 10 times later, which is intuitive). Similar results were obtained using even lower learning rates.
I have tried unit testing, checking the individual parts and making the model smaller. Here are results when I am using only 6 data points in the training set, batch size 2. Perfect fit on training data (here clearly different from the test accuracy, as expected) is unsurprisingly reached, but it still collapses from 100% to 1/6 so no better than a random pick. What needs to happen for the network to spin out from a perfect fit on the training set, can anybody tell me?
Here is the structure of the network (the relevant libraries are added before), although I hope that the aforementioned symptoms will be sufficient for you to recognize what the problem is without it:
class Network(nn.Module):
def __init__(self):
# call to the super class Module from nn
super(Network, self).__init__()
# fc strand for 'fully connected'
self.fc1 = nn.Linear(in_features=28*28, out_features=100)
self.fc2 = nn.Linear(in_features=100, out_features=100)
self.out = nn.Linear(in_features=100, out_features=10)
def forward(self, t):
# (1) input layer (redundant)
t = t
# (2) hidden linear layer
# As my t consists of 28*28 bit pictures, I need to flatten them:
t = t.reshape(-1, 28*28)
# Now having this reshaped input, add it to the linear layer
t = self.fc1(t)
# Again, apply ReLU as the activation function
t = F.relu(t)
# (3) hidden linear layer
# As above, but reshaping is not needed now
t = self.fc2(t)
t = F.relu(t)
# (4) output layer
t = self.out(t)
t = F.softmax(t, dim=1)
return t
The main execution of the code:
for b in range(epochs):
print('***** EPOCH NO. ', b+1)
# getting a batch iterator
batch_iterator = iter(batch_train_loader)
# For loop for a single epoch, based on the length of the training set and the batch size
for a in range(round(train_size/b_size)):
print(a+1)
# get one batch for the iteration
batch = next(batch_iterator)
# decomposing a batch
images, labels = batch[0].to(device), batch[1].to(device)
# to get a prediction, as with individual layers, we need to equate it to the network with the samples as input:
preds = network(images)
# with the predictions, we will use F to get the loss as cross_entropy
loss = F.cross_entropy(preds, labels)
# function for counting the number of correct predictions
get_num_correct(preds, labels))
# calculate the gradients needed for update of weights
loss.backward()
# with the known gradients, we will update the weights according to stochastic gradient descent
optimizer = optim.SGD(network.parameters(), lr=learning_rate)
# with the known weights, step in the direction of correct estimation
optimizer.step()
# check if the whole data check should be performed (for taking full training/test data checks only in evenly spaced intervals on the log scale, pre-calculated later)
if counter in X_log:
# get the result on the whole train data and record them
full_train_preds = network(full_train_images)
full_train_loss = F.cross_entropy(full_train_preds, full_train_labels)
# Record train loss
a_train_loss.append(full_train_loss.item())
# Get a proportion of correct estimates, to make them comparable between train and test data
full_train_num_correct = get_num_correct(full_train_preds, full_train_labels)/train_size
# Record train accuracy
a_train_num_correct.append(full_train_num_correct)
print('Correct predictions of the dataset:', full_train_num_correct)
# Repeat for test predictions
# get the results for the whole test data
full_test_preds = network(full_test_images)
full_test_loss = F.cross_entropy(full_test_preds, full_test_labels)
a_test_loss.append(full_test_loss.item())
full_test_num_correct = get_num_correct(full_test_preds, full_test_labels)/test_size
a_test_num_correct.append(full_test_num_correct)
# update counter
counter = counter + 1
I have googled and checked here for answers to this questions but people either ask about over-fitting or their NNs do not increase accuracy on the training set at all (i.e. they simply don't work), not about finding a good training fit and then completely loosing it, also on the training set. I hope I did not post something obvious, I am relatively new to NN but I did my best to research the topic before posting it here, thank you for your help and understanding!
| The cause is a bug in the code. We need to add optimizator.zero_grad() at the beginning of the training loop and create the optimizator before the outer training loop, i.e.
optimizator = optim.SGD(...)
for b in range(epochs):
Why do we need to call zero_grad() in PyTorch? explains why.
| https://stackoverflow.com/questions/56599871/ |
Mat2cell matlab equivalent in tensorflow or pytorch | I have a square matrix and like to break it into some smaller matrices. For example, assume we have a matrix with the shape of [4,4] and would like to convert it into 4 smaller matrices with size [2,2].
input:
[9, 9, 9, 9,
8, 8, 8, 8,
7, 7, 7, 7,
6, 6, 6, 6]
output:
[[9, 9 | [9, 9,
8, 8] | 8, 8],
---------------
[7, 7 | [7, 7,
6, 6] | 6, 6]]
| Given a tensor with the shape of 4*4 or 1*16 the easiest way to do this is by view function or reshape:
a = torch.tensor([9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 6])
# a = a.view(4,4)
a = a.view(2, 2, 2, 2)
# output:
tensor([[[[9, 9],
[9, 9]],
[[8, 8],
[8, 8]]],
[[[7, 7],
[7, 7]],
[[6, 6],
[6, 6]]]])
| https://stackoverflow.com/questions/56600235/ |
Partitioned matrix multiplication in tensorflow or pytorch | Assume I have matrices P with the size [4, 4] which partitioned (block) into 4 smaller matrices [2,2]. How can I efficiently multiply this block-matrix into another matrix (not partitioned matrix but smaller)?
Let's Assume our original matric is:
P = [ 1 1 2 2
1 1 2 2
3 3 4 4
3 3 4 4]
Which split into submatrices:
P_1 = [1 1 , P_2 = [2 2 , P_3 = [3 3 P_4 = [4 4
1 1] 2 2] 3 3] 4 4]
Now our P is:
P = [P_1 P_2
P_3 p_4]
In the next step, I want to do element-wise multiplication between P and smaller matrices which its size is equal to number of sub-matrices:
P * [ 1 0 = [P_1 0 = [1 1 0 0
0 0 ] 0 0] 1 1 0 0
0 0 0 0
0 0 0 0]
| Following is a general Tensorflow-based solution that works for input matrices p (large) and m (small) of arbitrary shapes as long as the sizes of p are divisible by the sizes of m on both axes.
def block_mul(p, m):
p_x, p_y = p.shape
m_x, m_y = m.shape
m_4d = tf.reshape(m, (m_x, 1, m_y, 1))
m_broadcasted = tf.broadcast_to(m_4d, (m_x, p_x // m_x, m_y, p_y // m_y))
mp = tf.reshape(m_broadcasted, (p_x, p_y))
return p * mp
Test:
import tensorflow as tf
tf.enable_eager_execution()
p = tf.reshape(tf.constant(range(36)), (6, 6))
m = tf.reshape(tf.constant(range(9)), (3, 3))
print(f"p:\n{p}\n")
print(f"m:\n{m}\n")
print(f"block_mul(p, m):\n{block_mul(p, m)}")
Output (Python 3.7.3, Tensorflow 1.13.1):
p:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]
[30 31 32 33 34 35]]
m:
[[0 1 2]
[3 4 5]
[6 7 8]]
block_mul(p, m):
[[ 0 0 2 3 8 10]
[ 0 0 8 9 20 22]
[ 36 39 56 60 80 85]
[ 54 57 80 84 110 115]
[144 150 182 189 224 232]
[180 186 224 231 272 280]]
Another solution that uses implicit broadcasting is the following:
def block_mul2(p, m):
p_x, p_y = p.shape
m_x, m_y = m.shape
p_4d = tf.reshape(p, (m_x, p_x // m_x, m_y, p_y // m_y))
m_4d = tf.reshape(m, (m_x, 1, m_y, 1))
return tf.reshape(p_4d * m_4d, (p_x, p_y))
| https://stackoverflow.com/questions/56601115/ |
Create multiple images with different ratio PyTorch | I'm trying to perform some digit recognition using PyTorch. I have implemented a convolutional version of the sliding window with size 32x32. Which makes me able to identify digits of this range of size in a picture.
But now let's imagine I have an image of size 300x300 with a digit that occupies the whole image. I will never be able to identify it...
I have seen people saying that the image needs to be rescaled and resized. Meaning that I need to create various scaled versions of my initial image and then to feed my network with those "new" images.
Does anyone have any idea how I can perform that?
Here is a part of my code, if it can help..
# loading dataset
size=200
height=200
width= 300
transformer_svhn_test = transforms.Compose([
transforms.Grayscale(3),
transforms.Resize((height, width)),
transforms.CenterCrop((size, size)),
transforms.ToTensor(),
transforms.Normalize([.5,.5,.5], [.5,.5,.5])
])
SVHN_test = SVHN_(train=False, transform=transformer_svhn_test)
SVHN_test_loader = DataLoader(SVHN_test, batch_size=batch_size, shuffle=False, num_workers=3)
#loading network
model = Network()
model.to(device)
model.load_state_dict(torch.load("digit_classifier_gray_scale_weighted.pth"))
# loading one image and feeding the model with it
image = next(iter(SVHN_test_loader))[0]
image_tensor = image.unsqueeze(0) # creating a single-image batch
image_tensor = image_tensor.to(device)
model.eval()
output = model(image_tensor)
| Please correct me if I understand your question wrong:
Your network takes images with size of 300x300 as input, and does 32x32 sliding window operation within your model, and output the locations of any digits in input images? In this setup, you are framing this problem as an object detection task.
I am imaging the digits in your training data have sizes that are similar to 32x32, and you wanted to use multiple scale evaluation to make sure digits on your testing images will also have similar sizes as those in your training data. As for object detection network, the input size of your network is not fixed.
So the thing you need is actually called multi scale evaluation/testing, and you will find it very common in Computer Vision tasks.
A good starting point would be HERE
| https://stackoverflow.com/questions/56604954/ |
NameError: name 'nn' is not defined | Several times when I copy PyTorch code I get this error:
NameError: name 'nn' is not defined
What is missing? What is nn?
To reproduce:
class SLL(nn.Module):
"single linear layer"
def __init__(self):
super().__init__()
self.l1 = nn.Linear(10,100)
def forward(self)->None:
print("SLL:forward")
m1 = SLL()
| If you got this error you can fix it with the following code:
import torch
import torch.nn as nn
You need to include both lines, since if you set just the second one it may not work if the torch package is not imported.
Where torch and torch.nn (or just nn) are two of the main PyTorch packages. You can help(torch.nn) to confirm this.
It is not uncommon when you include nn to include the functional interface as F like this:
import torch
import torch.nn as nn
import torch.nn.functional as F
To bring you the hints what you imported or what is inside the nn package I provided the list:
['AdaptiveAvgPool1d', 'AdaptiveAvgPool2d', 'AdaptiveAvgPool3d', 'AdaptiveLogSoftmaxWithLoss', 'AdaptiveMaxPool1d', 'AdaptiveMaxPool2d', 'AdaptiveMaxPool3d', 'AlphaDropout', 'AvgPool1d', 'AvgPool2d', 'AvgPool3d', 'BCELoss', 'BCEWithLogitsLoss', 'BatchNorm1d', 'BatchNorm2d', 'BatchNorm3d', 'Bilinear', 'CELU', 'CTCLoss', 'ConstantPad1d', 'ConstantPad2d', 'ConstantPad3d', 'Container', 'Conv1d', 'Conv2d', 'Conv3d', 'ConvTranspose1d', 'ConvTranspose2d', 'ConvTranspose3d', 'CosineEmbeddingLoss', 'CosineSimilarity', 'CrossEntropyLoss', 'CrossMapLRN2d', 'DataParallel', 'Dropout', 'Dropout2d', 'Dropout3d', 'ELU', 'Embedding', 'EmbeddingBag', 'FeatureAlphaDropout', 'Fold', 'FractionalMaxPool2d', 'GLU', 'GRU', 'GRUCell', 'GroupNorm', 'Hardshrink', 'Hardtanh', 'HingeEmbeddingLoss', 'InstanceNorm1d', 'InstanceNorm2d', 'InstanceNorm3d', 'KLDivLoss', 'L1Loss', 'LPPool1d', 'LPPool2d', 'LSTM', 'LSTMCell', 'LayerNorm', 'LeakyReLU', 'Linear', 'LocalResponseNorm', 'LogSigmoid', 'LogSoftmax', 'MSELoss', 'MarginRankingLoss', 'MaxPool1d', 'MaxPool2d', 'MaxPool3d', 'MaxUnpool1d', 'MaxUnpool2d', 'MaxUnpool3d', 'Module', 'ModuleDict', 'ModuleList', 'MultiLabelMarginLoss', 'MultiLabelSoftMarginLoss', 'MultiMarginLoss', 'NLLLoss', 'NLLLoss2d', 'PReLU', 'PairwiseDistance', 'Parameter', 'ParameterDict', 'ParameterList', 'PixelShuffle', 'PoissonNLLLoss', 'RNN', 'RNNBase', 'RNNCell', 'RNNCellBase', 'RReLU', 'ReLU', 'ReLU6', 'ReflectionPad1d', 'ReflectionPad2d', 'ReplicationPad1d', 'ReplicationPad2d', 'ReplicationPad3d', 'SELU', 'Sequential', 'Sigmoid', 'SmoothL1Loss', 'SoftMarginLoss', 'Softmax', 'Softmax2d', 'Softmin', 'Softplus', 'Softshrink', 'Softsign', 'Tanh', 'Tanhshrink', 'Threshold', 'TripletMarginLoss', 'Unfold', 'Upsample', 'UpsamplingBilinear2d', 'UpsamplingNearest2d', 'ZeroPad2d', '_VF', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '_functions', '_reduction', 'backends', 'functional', 'grad', 'init', 'modules', 'parallel', 'parameter', 'utils']
Containing many classes where probable the most fundamental one is the PyTorch class nn.Module.
Do not confuse PyTorch class nn.Module with the Python modules.
To fix the SLL model from the question you just have to add the first two lines:
import torch
import torch.nn as nn
class SLL(nn.Module):
"single linear layer"
def __init__(self):
super().__init__()
self.l1 = nn.Linear(10,100)
def forward(self)->None:
print("SLL:forward")
# we create a module instance m1
m1 = SLL()
And you will get the output:
SLL(
(l1): Linear(in_features=10, out_features=100, bias=True)
)
| https://stackoverflow.com/questions/56633138/ |
Efficient metrics evaluation in PyTorch | I am new to PyTorch and want to efficiently evaluate among others F1 during my Training and my Validation Loop.
So far, my approach was to calculate the predictions on GPU, then push them to CPU and append them to a vector for both Training and Validation. After Training and Validation, I would evaluate both for each epoch using sklearn. However, profiling my code it showed, that pushing to cpu is quite a bottleneck.
for epoch in range(n_epochs):
model.train()
avg_loss = 0
avg_val_loss = 0
train_pred = np.array([])
val_pred = np.array([])
# Training loop (transpose X_batch to fit pretrained (features, samples) style)
for X_batch, y_batch in train_loader:
scores = model(X_batch)
y_pred = F.softmax(scores, dim=1)
train_pred = np.append(train_pred, self.get_vector(y_pred.detach().cpu().numpy()))
loss = loss_fn(scores, self.get_vector(y_batch))
optimizer.zero_grad()
loss.backward()
optimizer.step()
avg_loss += loss.item() / len(train_loader)
model.eval()
# Validation loop
for X_batch, y_batch in val_loader:
with torch.no_grad():
scores = model(X_batch)
y_pred = F.softmax(scores, dim=1)
val_pred = np.append(val_pred, self.get_vector(y_pred.detach().cpu().numpy()))
loss = loss_fn(scores, self.get_vector(y_batch))
avg_val_loss += loss.item() / len(val_loader)
# Model Checkpoint for best validation f1
val_f1 = self.calculate_metrics(train_targets[val_index], val_pred, f1_only=True)
if val_f1 > best_val_f1:
prev_best_val_f1 = best_val_f1
best_val_f1 = val_f1
torch.save(model.state_dict(), self.PATHS['xlm'])
evaluated_epoch = epoch
# Calc the metrics
self.save_metrics(train_targets[train_index], train_pred, avg_loss, 'train')
self.save_metrics(train_targets[val_index], val_pred, avg_val_loss, 'val')
I am certain there is a more efficient way to
a) store the predictions without having to push them to cpu each batch. b) calculate the metrics on GPU directly?
As I am new to PyTorch, I am very grateful for any hints and feedback :)
| You can compute the F-score yourself in pytorch. The F1-score is defined for single-class (true/false) classification only. The only thing you need is to aggregating the number of:
Count of the class in the ground truth target data;
Count of the class in the predictions;
Count how many times the class was correctly predicted.
Let's assume you want to compute F1 score for the class with index 0 in your softmax. In every batch, you can do:
predicted_classes = torch.argmax(y_pred, dim=1) == 0
target_classes = self.get_vector(y_batch)
target_true += torch.sum(target_classes == 0).float()
predicted_true += torch.sum(predicted_classes).float()
correct_true += torch.sum(
predicted_classes == target_classes * predicted_classes == 0).float()
When all batches are processed:
recall = correct_true / target_true
precision = correct_true / predicted_true
f1_score = 2 * precission * recall / (precision + recall)
Don't forget to take care of cases when precision and recall are zero and when then desired class was not predicted at all.
| https://stackoverflow.com/questions/56643503/ |
do I need to initialize lstm hidden state when in validation and test set? or just reset it to zero | On training, it is good to initialize hidden state instead of setting it to 0. But I wonder whether initialize hidden state on validation and testing is good or bad. Thanks
| There's absolutely no reason for custom initializing hidden states to zeros; this is actually the case:
def forward(self, input, hx=None):
...
if hx is None:
num_directions = 2 if self.bidirectional else 1
hx = torch.zeros(self.num_layers * num_directions,
max_batch_size, self.hidden_size,
dtype=input.dtype, device=input.device)
else:
# Each batch of the hidden state should match the input sequence that
# the user believes he/she is passing in.
hx = self.permute_hidden(hx, sorted_indices)
It checks first if you have passed any custom hidden states values, if you did not, it initializes it to zeros.
Also, you usually, theoretically speaking, do not need to initialize the model's hidden states in the testing mode (either randomly or using predefined values).
| https://stackoverflow.com/questions/56644700/ |
How to convert 35 classes of cityscapes dataset to 19 classes? | The following is a small snippet of my code. Using this, I can train my model called 'lolnet' on cityscapes dataset. But the dataset contains 35 classes/labels [0-34].
imports ***
trainloader = torch.utils.data.DataLoader(
datasets.Cityscapes('/media/farshid/DataStore/temp/cityscapes/', split='train', mode='fine',
target_type='semantic', target_transform =trans,
transform=input_transform ), batch_size = batch_size, num_workers = 2)
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net = lolNet()
criterion = CrossEntropyLoss2d()
net.to(device)
num_of_classes = 34
for epoch in range(int(0), 200000):
lr = 0.0001
for batch, data in enumerate(trainloader, 0):
inputs, labels = data
labels = labels.long()
inputs, labels = inputs.to(device), labels.to(device)
labels = labels.view([-1, ])
optimizer = optim.Adam(net.parameters(), lr=lr)
optimizer.zero_grad()
outputs = net(inputs)
outputs = outputs.view(-1, num_of_class)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
outputs = outputs.to('cpu')
outputs = outputs.data.numpy()
outputs = outputs.reshape([-1, num_of_class])
mask = np.zeros([outputs.shape[0]])
#
for i in range(len(outputs)):
mask[i] = np.argmax(outputs[i])
mask = mask.reshape([-1, 1])
IoU = jaccard_score(labels.to('cpu').data, mask, average='micro')
But I want to train my model only on the 19 classes. These 19 classes are found here . The labels to train for are stored as "ignoreInEval" = True. This pytorch Dataloader helper for this dataset doesnt provide any clue.
So my question is how can I train my model on the desired 19 classes of this dataset using pytorch's "datasets.Cityscapes" api.
| It's been a time, but leaving an answer as can be useful for others:
Firstly create a mapping to 19 classes + background. Background is related to not so important classes with ignore flag as said here.
# Mapping of ignore categories and valid ones (numbered from 1-19)
mapping_20 = {
0: 0,
1: 0,
2: 0,
3: 0,
4: 0,
5: 0,
6: 0,
7: 1,
8: 2,
9: 0,
10: 0,
11: 3,
12: 4,
13: 5,
14: 0,
15: 0,
16: 0,
17: 6,
18: 0,
19: 7,
20: 8,
21: 9,
22: 10,
23: 11,
24: 12,
25: 13,
26: 14,
27: 15,
28: 16,
29: 0,
30: 0,
31: 17,
32: 18,
33: 19,
-1: 0
}
Then for each label image (the gray images where each pixel contains a class, which has pattern "{city}__{number}_{number}_gtFine_labelIds.png") that you load for training, run function below.
It will convert each pixel according to mapping above and your label images (masks) will have now only 20 (19 classes + 1 background) different values, instead of 35.
def encode_labels(mask):
label_mask = np.zeros_like(mask)
for k in mapping_20:
label_mask[mask == k] = mapping_20[k]
return label_mask
Then you can train your model normally with these new number of classes.
| https://stackoverflow.com/questions/56650201/ |
Most efficient way to prep data for pytorch lstm from pandas dataframe | I am trying to feed data into my lstm. I have the data across multiple csv's, so I created a generator to load it in. However, I am having some issues on prepping the data for my lstm.
I understand this code (I got it from the pytorch docs)
seq_len = 5
batch_size= 3
cols_num = 10
hidden_size=20
num_layers = 2
rnn = nn.LSTM(input_size=cols_num, hidden_size=hidden_size, num_layers=num_layers)
data = torch.randn(seq_len, batch_size, cols_num)
h0 = torch.randn(batch_size, seq_len, hidden_size)
c0 = torch.randn(batch_size, seq_len, hidden_size)
output, (hn, cn) = rnn(data)
However, I think my disconnect is with using actual data not the torch.randn().
This is my current generator:
def data_loader(batch_size, fp, dropcol, seq_len):
while True:
for f in fp:
gc.collect()
df=pd.read_csv(f)
df=df.replace(np.nan, 0)
df=df.drop(dropcol,1)
df['minute'] = df['minute'].apply(lambda x: min_idx(x))
row_count, col_count = df.shape
encoder_input = []
prev = 0
for idx, b in enumerate(range(1, row_count)):
end = prev + batch_size
window = df.iloc[prev:end]
prev = end - 1
w = np.array(window, dtype='float64')
if w.shape[0] != batch_size: break
encoder_input.append(w)
if idx == seq_len:
w0 = encoder_input
encoder_input = []
yield w0
but I get errors when I run this:
loader = data_loader(batch_size=batch_size, fp=<list of csvs>, dropcol=idcol, seq_len=2)
lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=batch_first)
for batch in loader:
b = torch.tensor(batch)
output, hidden = lstm(b)
The error:
RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1'
What is the error in how I am thinking? Also, how should I format an h0 or c0 from the data?
| The error is not in how you are thinking, the error is in how Pytorch models accept input. The default data type created in a Pytorch tensor is torch.float64
where the default (and possibly only) data type accepted by models is torch.float32.
To fix this use:
b = torch.tensor(batch, dtype=torch.float32)
This will convert your inputs to torch.float32.
| https://stackoverflow.com/questions/56652048/ |
What does "Gathers values along an axis specified by dim." mean? | I want to understand what does "Gathers values along an axis specified by dim." mean in the below code. How to structure the operation of function on data in my head. What is this function doing to data and how ?
Please refer this link https://pytorch.org/docs/stable/torch.html#torch.gather
torch.gather(input, dim, index, out=None, sparse_grad=False)
Gathers values along an axis specified by dim.
For a 3-D tensor the output is specified by:
out[i][j][k] = input[index[i][j][k]][j][k] # if dim == 0
out[i][j][k] = input[i][index[i][j][k]][k] # if dim == 1
out[i][j][k] = input[i][j][index[i][j][k]] # if dim == 2
| Yes, it goes through the given dim (dimension) of the tensor, and collects into a new tensor the values specified by the index provided. So if I had a 1D tensor (is that allowed?) as
MyValues = torch.tensor([0,2,4,6,8])
and did
torch.gather(MyValues, 0, torch.tensor([0,1,3]))
I'd expect to return a 1D tensor containing [0,2,6]. i.e. the values located at positions 0, 1 and 3.
So it's just picking out the contents using the index tensor as a pointer to the locations of the contents to be extracted from the input tensor.
The dim is the dimension along which you want to index. So for 2D that'd give you the option of indexing by rows or columns, and you can extrapolate that out into as many dimensions as you like.
| https://stackoverflow.com/questions/56652237/ |
Poor fits for simple 2D Gaussian processes in `GPyTorch` | I'm having a lot of difficulty fitting a simple 2-dimensional GP out-of-the box using GPyTorch. As you can see below, the fit is very poor, and does not improve much with either swapping out the RBF kernel for something like a Matern. The optimization does appear to converge, but not on anything sensible.
class GPRegressionModel(gpytorch.models.ExactGP):
def __init__(self, train_x, train_y, likelihood):
super(GPRegressionModel, self).__init__(train_x, train_y, likelihood)
self.mean_module = gpytorch.means.ConstantMean()
self.covar_module = gpytorch.kernels.ScaleKernel(
gpytorch.kernels.RBFKernel(ard_num_dims=2),
)
def forward(self, x):
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)
Does anyone have good tutorial examples beyond the ones included in the docs?
| I was running into similar issues when trying to fit high-dimensional Gaussian Processes. A couple of suggestions (not sure if these will work):
Try using a ZeroMean, rather than a constant mean. It could be that having more hyperparameters (constant mean hyperparameter values) could lead the -mll objective to a local minima, rather than to a global minima. Using a different optimizer, e.g. lbfgs (which is second-order, rather than adam or sgd, which are both first-order) may help with this as well.
Try normalizing your input data using min-max normalization, and your targets using standard normal N(0,1) normalization. In short, these normalization steps ensure that your data is consistent with the default priors for these GPR models. For more info on this, check out this GitHub issue.
Try changing the learning rate for optimizing your hyperparameters, or the number of epochs you train this for.
If you see any issues with numerical precision (particularly after normalization, if you choose to use it), try changing your model and datasets to double, 64-bit precision by converting torch tensors to double-precision tensors with tensor.double().
Again, can't guarantee that these will fix the issues you're running into, but hopefully they help!
Here are some tutorials I've put together as well.
| https://stackoverflow.com/questions/56657552/ |
How to select parameters for nn.Linear layer while training a CNN? | I am trying to train a CNN to classify images from the Fashion-MNIST data using Conv2d, Maxpool and Linear layers. I came across a code as mentioned below with in_features = 12*4*4 in nn.Linear layer.
Can I please get help on how to select an in_features parameter for nn.Linear layer?
class Network(nn.Module):
def __init__(self):
super(Network, self).__init__()
self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5)
self.conv2 = nn.Conv2d(in_channels=6, out_channels=12, kernel_size=5)
self.fc1 = nn.Linear(in_features=12*4*4, out_features=120)
self.fc2 = nn.Linear(in_features=120, out_features=60)
self.out = nn.Linear(in_features=60, out_features=10)
| Each example in the Fashion-MNIST dataset is a 28 x 28 grayscale image.
Input is 28 x 28
We do a 5 x 5 convolution without padding(since default padding=0) and stride=1(by default), so we lose 2 pixels at each side, we drop down to 24 x 24, i.e.,(28-5)/1 + 1
We then perform maxpooling operation with receptive field of 2 x 2, we cut each dimension by half, down to 12 x 12
We again do another 5 x 5 convolution without padding and stride=1, we drop down to 8 x 8, i.e.,(12-5)/1 + 1
Then, we perform another maxpooling operation, we drop down to 4 x 4
That's why, self.fc1 = nn.Linear(in_features=12*4*4, out_features=120). It's basically, n_features_conv * height * width, where height and width are 4 respectively and n_features_conv is same as out_channels of the conv2D layer lying just above it.
Note if you change the size of input image, then you will have to perform the above calculations and adjust the first Linear layer accordingly.
Hope this helps you!
| https://stackoverflow.com/questions/56660546/ |
Custom cross-entropy loss in pytorch | I have done a custom implementation of the pytorch cross-entropy loss function (as I need more flexibility to be introduced later). The model I intend to train with this will need a considerable amount of time to train and the resources available can't be used to merely test if the function is correct implementation. I have implemented vectorized implementation as it will be quicker to run.
Following is my code for the same:
def custom_cross(my_pred,true,batch_size=BATCH_SIZE):
loss= -torch.mean(torch.sum(true.view(batch_size, -1) * torch.log(my_pred.view(batch_size, -1)), dim=1))
return loss
I will really appreciate if you can suggest a more optimized implementation of the same or if I am making a mistake in the present one. The model will use a Nvidia Tesla K-80 to train.
| If you need just cross entropy you can take the advantage PyTorch defined that.
import torch.nn.functional as F
loss_func = F.cross_entropy
suggest a more optimized implementation
PyTorch has F. loss functions, but you can easily write your own using plain python.
PyTorch will create fast GPU or vectorized CPU code for your function automatically.
So, you may check the PyTorch original implementation but I think is this:
def log_softmax(x):
return x - x.exp().sum(-1).log().unsqueeze(-1)
And here is the original implementation of cross entropy loss, now you may just alter:
nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
To something you need, and you have it.
| https://stackoverflow.com/questions/56664770/ |
How to replace infs to avoid nan gradients in PyTorch | I need to compute log(1 + exp(x)) and then use automatic differentiation on it. But for too large x, it outputs inf because of the exponentiation:
>>> x = torch.tensor([0., 1., 100.], requires_grad=True)
>>> x.exp().log1p()
tensor([0.6931, 1.3133, inf], grad_fn=<Log1PBackward>)
Since log(1 + exp(x)) ≈ x for large x, I thought I could replace the infs with x using torch.where. But when doing this, I still get nan for the gradient of too large values. Do you know why this happens and if there is another way to make it work?
>>> exp = x.exp()
>>> y = x.where(torch.isinf(exp), exp.log1p()) # Replace infs with x
>>> y # No infs
tensor([ 0.6931, 1.3133, 100.0000], grad_fn=<SWhereBackward>)
>>> y.sum().backward() # Automatic differentiation
>>> x.grad # Why is there a nan and how can I get rid of it?
tensor([0.5000, 0.7311, nan])
| A workaround I've found is to manually implement a Log1PlusExp function with its backward counterpart. Yet it does not explain the bad behavior of torch.where in the question.
>>> class Log1PlusExp(torch.autograd.Function):
... """Implementation of x ↦ log(1 + exp(x))."""
... @staticmethod
... def forward(ctx, x):
... exp = x.exp()
... ctx.save_for_backward(x)
... return x.where(torch.isinf(exp), exp.log1p())
... @staticmethod
... def backward(ctx, grad_output):
... x, = ctx.saved_tensors
... return grad_output / (1 + (-x).exp())
...
>>> log_1_plus_exp = Log1PlusExp.apply
>>> x = torch.tensor([0., 1., 100.], requires_grad=True)
>>> log_1_plus_exp(x) # No infs
tensor([ 0.6931, 1.3133, 100.0000], grad_fn=<Log1PlusExpBackward>)
>>> log_1_plus_exp(x).sum().backward()
>>> x.grad # And no nans!
tensor([0.5000, 0.7311, 1.0000])
| https://stackoverflow.com/questions/56667596/ |
CNTK: "inferred dimension cannot be calculated from input and new shape size." | I've set up a model for CIFAR-10 using Pytorch, and saved it as an ONNX file.
But it looks like I can't load it from CNTK.
I've already loaded another ONNX file from the same source code (by mistake), so the dependencies look OK. The problem occurs when I call Function.Load()
var deviceDescriptor = DeviceDescriptor.CPUDevice; ;
var function = Function.Load(ONNX_PATH, deviceDescriptor, ModelFormat.ONNX);
I get this exception (Unhandled exception):
System.ApplicationException : 'Reshape: inferred dimension cannot be calculated from input and new shape size.
[CALL STACK]
- CNTK::TrainingParameterSchedule:: GetMinibatchSize
- CNTK:: XavierInitializer (x6)
- CNTK::Function::Load
- CSharp_CNTK_Function__Load__SWIG_0
- 00007FFB0C41C307 (SymFromAddr() error: Le module spécifié est introuvable.)
| It looks like this model can't be loaded in CNTK. CNTK has good support for exporting (saving) to ONNX, importing (loading) can be problematic for some operations.
CNTK development is frozen, what's your motivation to use it?
The recommended way now is to use ONNX Runtime https://github.com/microsoft/onnxruntime for inference, it has first-class support for ONNX.
| https://stackoverflow.com/questions/56676913/ |
Upsample ONNX gives INVALID_GRAPH when trying to convert bilinear layer to onnx | when i convert network with bilinear layer trained on Pytorch to ONNX, i get following error
RuntimeError: [ONNXRuntimeError] : 10 : INVALID_GRAPH : Load model
from test.onnx failed:Type Error: Type 'tensor(int64)' of input
parameter (11) of operator (Floor) in node () is invalid.
I m not sure on why this error occurs, I tried building ONNX from source but still the issue dosen't seems to go way.
Any ideas on what might cause this error? or how to tackle the issue?
Way to Reproduce-
from torch import nn
import torch
import torch.nn.functional as F
import onnxruntime as rt
class Upsample(torch.nn.Module):
def forward(self, x):
#l = nn.Conv2d(3, 3, kernel_size=1, stride=1, padding=1, bias=True)
return F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False)
m = Upsample()
v = torch.randn(1,3,128,128, dtype=torch.float32, requires_grad=False)
torch.onnx.export(m, v, "test.onnx")
sess = rt.InferenceSession("test.onnx")
| This error has been fixed in https://github.com/pytorch/pytorch/pull/21434 (the fix is in functional.py), so you should be able to get it if you install pytorch's nightly build.
However, in this same PR, converting Upsample in bilinear mode has been disabled; the reason is that Pytorch's bilinear mode does not align with ONNX's, and Nearest mode is the only mode currently supported.
Upsample (Now called Resize) in ONNX is being updated in opset 11 to support a bilinear mode that aligns with Pytorch in https://github.com/onnx/onnx/pull/2057, but this is not yet pushed.
| https://stackoverflow.com/questions/56682815/ |
Equivalence of slicing tensor in Pytorch/ATen C++ | In Python given a 2-D tensor, we can use tensor[:,:2] to slice the a 2x2 matrix of the first two elements in the top left of the matrix, e.g. :
x = torch.tensor([[-1.4673, 0.9980, -2.1427, -1.1798, -0.0646, -0.2635, -2.8930, -0.2563,
0.4559, -0.7947, -0.4540, 3.3224, 0.2295, 5.5568, -8.0451, -2.4529,
4.8724, 2.1640, 3.3255, 0.6693, -1.2362, 4.4713, -3.5547, -0.0528,
0.1031, -1.2472, -1.6014, 1.8134],
[ 2.1636, -1.1497, -5.0298, 2.8261, -0.5684, 0.6389, 2.9009, -5.1609,
1.7358, -3.1819, -0.9877, 5.5598, 6.7142, 4.5704, -1.2683, -5.3046,
3.0454, 3.2757, -3.2541, 3.6619, -3.6391, -0.2002, 5.7175, 5.7130,
0.6632, -0.0744, -0.3502, 4.8116]])
y, z = x[:,:2].chunk(2,1)
print(y)
print(z)
[out]:
tensor([[-1.4673],
[ 2.1636]])
tensor([[ 0.9980],
[-1.1497]])
What is right way to do it in C++ for PyTorch's ATen particularly?
For e.g. in the LSTM, there is the gate.chunk(4,1) function at https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/RNN.cpp#L253
If I want to do a gate[:,:2].chunk(2,1) to extract different parts of the gates, e.g. auto partial_gates = gates[:,:2].chunk(4, 1);, how can it be done?
template <typename cell_params>
struct LSTMCell : Cell<std::tuple<Tensor, Tensor>, cell_params> {
using hidden_type = std::tuple<Tensor, Tensor>;
hidden_type operator()(const Tensor& input, const hidden_type& hidden, const cell_params& params) const override {
auto hx = std::get<0>(hidden);
auto cx = std::get<1>(hidden);
if (input.is_cuda()) {
auto igates = params.matmul_ih(input);
auto hgates = params.matmul_hh(hx);
auto result = at::_thnn_fused_lstm_cell(igates, hgates, cx, params.b_ih, params.b_hh);
// Slice off the workspace argument (it's needed only for AD).
return std::make_tuple(std::get<0>(result), std::get<1>(result));
}
auto gates = params.linear_ih(input) + params.linear_hh(hx);
auto chunked_gates = gates.chunk(4, 1);
auto partial_gates = gates[:,:2].chunk(4, 1);
auto ingate = chunked_gates[0].sigmoid();
auto forgetgate = chunked_gates[1].sigmoid();
auto cellgate = chunked_gates[2].tanh();
auto outgate = chunked_gates[3].sigmoid();
auto cy = (forgetgate * cx) + (ingate * cellgate);
auto hy = outgate * cy.tanh();
return std::make_tuple(hy, cy);
}
};
| It's .narrow() from https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/native/TensorShape.cpp#L364
auto partial_gates = gates.narrow(1,0,2).chunk(4, 1);
| https://stackoverflow.com/questions/56698047/ |
Expected object of backend CPU but got backend CUDA for argument #2 'source' | I have tried other answers but the error is not getting removed. Difference from the other question I am getting is that the last term used in error is 'source' which I did not find in any question. If possible please also explain the term 'source' in error. And running code without CPU is working fine.
I am using Google Colab with GPU enabled.
import torch
from torch import nn
import syft as sy
hook = sy.TorchHook(torch)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = nn.Sequential(nn.Linear(784,256),
nn.ReLU(),
nn.Linear(256,128),
nn.ReLU(),
nn.Linear(128,64),
nn.ReLU(),
nn.Linear(64,10),
nn.LogSoftmax(dim = 1))
model = model.to(device)
output :
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-42-136ec343040a> in <module>()
8 nn.LogSoftmax(dim = 1))
9
---> 10 model = model.to(device)
3 frames
/usr/local/lib/python3.6/dist-packages/syft/frameworks/torch/hook/hook.py in data(self, new_data)
368
369 with torch.no_grad():
--> 370 self.set_(new_data)
371 return self
372
RuntimeError: Expected object of backend CPU but got backend CUDA for argument #2 'source'
| This issue is related to PySyft. As you can see in this Issue#1893, the current workaround is to set:
import torch
torch.set_default_tensor_type(torch.cuda.FloatTensor)
right after import torch.
Code:
import torch
from torch import nn
torch.set_default_tensor_type(torch.cuda.FloatTensor) # <-- workaround
import syft as sy
hook = sy.TorchHook(torch)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(device)
model = nn.Sequential(nn.Linear(784,256),
nn.ReLU(),
nn.Linear(256,128),
nn.ReLU(),
nn.Linear(128,64),
nn.ReLU(),
nn.Linear(64,10),
nn.LogSoftmax(dim = 1))
model = model.to(device)
print(model)
Output:
cuda
Sequential(
(0): Linear(in_features=784, out_features=256, bias=True)
(1): ReLU()
(2): Linear(in_features=256, out_features=128, bias=True)
(3): ReLU()
(4): Linear(in_features=128, out_features=64, bias=True)
(5): ReLU()
(6): Linear(in_features=64, out_features=10, bias=True)
(7): LogSoftmax()
)
| https://stackoverflow.com/questions/56702413/ |
Bert-multilingual in pytorch | I am using bert embedding for french text data. and I have problem with loading model and vocabulary.
I used the following code for tokenization that works well, but to get the vocabulary, it gives me Chinese words!!
tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased')
text = "La Banque Nationale du Canada fête cette année le 110e anniversaire de son bureau de Paris."
marked_text = "[CLS] " + text + " [SEP]"
tokenized_text = tokenizer.tokenize(marked_text)
list(tokenizer.vocab.keys())[5000:5020]
I expected french words in vocabulary but i get chinese words, should i specify the language somewhere in the code?
| You are Getting Chinese text because, you are looking for a specific range of the words from the vocabulary [5000:5020], which corresponds to the Chinese text. Also,bert -base-multilingual-cased is trained on 104 languages.
If you further want to verify your code, you can use this:
tokenizer = BertTokenizer.from_pretrained('bert-base-multilingual-cased')
text = "La Banque Nationale du Canada fête cette année le 110e anniversaire de son bureau de Paris."
marked_text = "[CLS] " + text + " [SEP]"
tokenized_text = tokenizer.tokenize(marked_text)
which is same as your code, followed by:
token_no=[]
for token in tokenized_text:
#print(tokenizer.vocab[token]) ### you can use this to check the corresponding index of the token
token_no.append(tokenizer.vocab[token])
### The below code obtains the tokens from the index, which is similar to what you were trying, but on the correct range.
new_token_list=[]
for i in token_no:
new_token_list.append(list(tokenizer.vocab.keys())[i])
#print(new_token_list); ### you can use it if you want to check back the tokens.
| https://stackoverflow.com/questions/56708296/ |
Difference between Parameter vs. Tensor in PyTorch | I would like to know the difference between PyTorch Parameter and Tensor?
The existing answer is for the old PyTorch where variables are being used?
| This is the whole idea of the Parameter class (attached) in a single image.
Since it is sub-classed from Tensor it is a Tensor.
But there is a trick. Parameters that are inside of a module are added to the list of Module parameters. If m is your module m.parameters() will hold your parameter.
Here is the example:
class M(nn.Module):
def __init__(self):
super().__init__()
self.weights = nn.Parameter(torch.randn(2, 2))
self.bias = nn.Parameter(torch.zeros(2))
def forward(self, x):
return x @ self.weights + self.bias
m=M()
m.parameters()
list(m.parameters())
---
[Parameter containing:
tensor([[ 0.5527, 0.7096],
[-0.2345, -1.2346]], requires_grad=True), Parameter containing:
tensor([0., 0.], requires_grad=True)]
You see how the parameters will show what we defined.
And if we just add a tensor inside a class, like self.t = Tensor, it will not show in the parameters list. That is literally it. Nothing fancy.
| https://stackoverflow.com/questions/56708367/ |
PyTorch Total CUDA time | Autograd profiler is a handy tool to measure the execution time in PyTorch as it is shown in what follows:
import torch
import torchvision.models as models
model = models.densenet121(pretrained=True)
x = torch.randn((1, 3, 224, 224), requires_grad=True)
with torch.autograd.profiler.profile(use_cuda=True) as prof:
model(x)
print(prof)
The output looks like this:
----------------------------------- --------------- --------------- --------------- --------------- ---------------
Name CPU time CUDA time Calls CPU total CUDA total
----------------------------------- --------------- --------------- --------------- --------------- ---------------
conv2d 9976.544us 9972.736us 1 9976.544us 9972.736us
convolution 9958.778us 9958.400us 1 9958.778us 9958.400us
_convolution 9946.712us 9947.136us 1 9946.712us 9947.136us
contiguous 6.692us 6.976us 1 6.692us 6.976us
empty 11.927us 12.032us 1 11.927us 12.032us
Which will include many lines. My questions are:
1) How can I use autograd profiler to get the entire CUDA time? (i.e., sum of CUDA time column)
2) Is there any solution to use it pragmatically? For example, prof[0].CUDA_Time?
| [item.cuda_time for item in prof.function_events]
will give you a list of CUDA times. Modify it depending on your needs. To get the sum of CUDA times for example:
sum([item.cuda_time for item in prof.function_events])
Be careful though, the times in the list are in microseconds, while they are displayed in milliseconds in print(prof).
| https://stackoverflow.com/questions/56711683/ |
How to impove the speed of tf.data.experimental.CsvDataset in tensorflow 1.13.1? | I am coding a toy example for csv data in Tensorflow.
I have implemented three types of data loader in tensorflow and pytorch to compare their speeds. Here is the code:
First, with tensorflow api tf.data.experimental.CsvDataset:
def parse_data(x, n_classes):
x = tf.convert_to_tensor(x)
return x[:-1], tf.one_hot(indices=tf.cast(x[-1], tf.int32), depth=n_classes)
if __name__=='__main__':
dataset_train = tf.data.experimental.CsvDataset('/home/david/Dataset/timit/test.csv', [tf.float32] * 430,
header=False,
field_delim=' ')
dataset_train = dataset_train.map(lambda *x_: parse_data(x_, 1928))
dataset_train = dataset_train.batch(128)
dataset_train = dataset_train.prefetch(1)
iterator = dataset_train.make_initializable_iterator()
x_in, y = iterator.get_next()
x = tf.layers.Dense(units=1024, activation=tf.nn.relu)(x_in)
x = tf.layers.Dense(units=1024, activation=tf.nn.relu)(x)
x = tf.layers.Dense(units=1024, activation=tf.nn.relu)(x)
x = tf.layers.Dense(units=1024, activation=tf.nn.relu)(x)
logits = tf.layers.Dense(units=1928, activation=None)(x)
loss = tf.losses.softmax_cross_entropy(y, logits)
optimizer = tf.train.AdamOptimizer()
optimizer.minimize(loss)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(iterator.initializer)
running_loss = 0.0
time_last = time.time()
epoch = 0
i = 0
while True:
try:
running_loss += sess.run(loss) # , feed_dict={x: data, y: labels})
if (i + 1) % 5 == 0:
print('\r[epoch: %2d, batch: %5d, time: %5f] loss: %.3f' % (
epoch + 1, i + 1, time.time() - time_last, running_loss / i), end=' ')
time_last = time.time()
i += 1
except tf.errors.OutOfRangeError:
pass
Second, using pandas and tf.placeholder:
if __name__ == '__main__':
x_in = tf.placeholder(shape=[128, 429], dtype=tf.float32)
y_in = tf.placeholder(shape=[128], dtype=tf.int32)
y = tf.one_hot(y_in, depth=1928)
x = tf.layers.Dense(units=1024, activation=tf.nn.relu)(x_in)
x = tf.layers.Dense(units=1024, activation=tf.nn.relu)(x)
x = tf.layers.Dense(units=1024, activation=tf.nn.relu)(x)
x = tf.layers.Dense(units=1024, activation=tf.nn.relu)(x)
logits = tf.layers.Dense(units=1928, activation=None)(x)
loss = tf.losses.softmax_cross_entropy(y, logits)
optimizer = tf.train.AdamOptimizer()
optimizer.minimize(loss)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
w = pd.read_csv('/home/david/Dataset/timit/test.csv', header=None, delim_whitespace=True).values
for epoch in range(23):
running_loss = 0.0
time_last = time.time()
i = 0
indexes = np.random.permutation(w.shape[0])
w_ = w[indexes, :]
while True:
if i * 128 + 128 > w.shape[0]:
break
running_loss += sess.run(loss,
feed_dict={x_in: w_[i * 128:i * 128 + 128, :-1],
y_in: w_[i * 128:i * 128 + 128, -1]})
if (i + 1) % 5 == 0:
print('\r[epoch: %2d, batch: %5d, time: %5f] loss: %.3f' % (
epoch + 1, i + 1, time.time() - time_last, running_loss / i), end=' ')
time_last = time.time()
i += 1
Third, with pytorch and pandas:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(429, 1024)
self.fc2 = nn.Linear(1024, 1024)
self.fc3 = nn.Linear(1024, 1024)
self.fc4 = nn.Linear(1024, 1024)
self.fc5 = nn.Linear(1024, 1928)
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = F.relu(self.fc4(x))
x = self.fc5(x)
return x
class CsvDataset(data.Dataset):
"""Face Landmarks dataset."""
def __init__(self, csv_file):
"""
Args:
csv_file (string): Path to the csv file with annotations.
root_dir (string): Directory with all the images.
transform (callable, optional): Optional transform to be applied
on a sample.
"""
self.landmarks_frame = pd.read_csv(csv_file, header=None, delim_whitespace=True)
def __len__(self):
return len(self.landmarks_frame)
def __getitem__(self, idx):
landmarks = self.landmarks_frame.values[idx, :]
return landmarks[:-1], landmarks[-1]
if __name__ == '__main__':
net = Net()
device = torch.device('cuda:0')
print(device)
net.to(device)
optimizer = optim.Adam(net.parameters(), lr=0.001)
criterion = nn.CrossEntropyLoss()
dataset = CsvDataset('/home/david/Dataset/timit/train.csv')
trainloader = torch.utils.data.DataLoader(dataset, batch_size=128, shuffle=True)
for epoch in range(23):
running_loss = 0.0
time_last = time.time()
for i, data in enumerate(trainloader):
inputs, labels = data
inputs = inputs.float().to(device)
labels = labels.long().to(device)
optimizer.zero_grad()
output = net(inputs)
loss = criterion(output, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if (i + 1) % 5 == 0:
print('\r[epoch: %2d, batch: %5d, time: %5f] loss: %.3f' % (
epoch + 1, i + 1, time.time() - time_last, running_loss / i), end=' ')
time_last = time.time()
print('')
print('Finished Training')
I record the time cost for training in five batches:
First, CsvDataset: 1.382647s
Second, tf.placeholder: 0.013263s
Third, pytorch: 0.042086s
I guess it is partly because that tf.data.experimental.CsvDataset do io operations before each batch to extract data from csv file (Is this ture, or there are other reasons?).
However, it is too slow comparing to the other two. Is there any chance for improvement? How can I set the tf.data.experimental.CsvDataset api to load all csv data at the very beginning?
Or can I say that tf.data.experimental.CsvDataset is implemented only for the csv dataset that is too big to store in the memory? Because the time cost seems like intolerable.
| You may play with the batch size in the first example, and if it reads batches from file every time you can prove it if you make it 2x bigger, you may expect 2x speed improvement. I haven't played with (experimental) class CsvDataset in TF.
I am sure Pandas reads your document faster and this is part of the reason why you have these times.
Probable the next step you should unset the loss function nn.CrossEntropyLoss(). Most probable have the regression problem and not the classification problem judging by float labels you have at the end.
So try torch.nn.MSELoss as the loss function.
| https://stackoverflow.com/questions/56714388/ |
PyTorch: Expected input batch_size (12) to match target batch_size (64) | I tried out PyTorch and wanted to write a program for MNIST. But, I got the error message:
Expected input batch_size (12) to match target batch_size (64)
I searched for a solution but I don't understand what's wrong with my code.
#kwargs is empty because I don't use cuda
kwargs = {}
train_data = torch.utils.data.DataLoader(
datasets.MNIST('data', train=True, download=True,
transform=transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,),(0.3081,))])),
batch_size=64, shuffle=True, **kwargs)
test_data = torch.utils.data.DataLoader(
datasets.MNIST('data', train=False,
transform=transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.1307,),(0.3081,))])),
batch_size=64, shuffle=True, **kwargs)
class Netz(nn.Module):
def __init__(self):
super(Netz, self).__init__()
self.conv1 = nn.Conv2d(1,10, kernel_size=5)
self.conv2 = nn.Conv2d(10, 20, kernel_size=5)
self.conv_dropout = nn.Dropout2d()
self.fc1 = nn.Linear(320, 60)
self.fc2 = nn.Linear(60, 10)
def forward(self, x):
x = self.conv1(x)
x = F.max_pool2d(x, 2)
x = F.relu(x)
x = self.conv2(x)
x = self.conv_dropout(x)
x = F.max_pool2d(x, 2)
x = F.relu(x)
print(x.shape)
x = x.view(-1, 320)
x = self.fc1(x)
x = x.view(-1, 320)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return F.log_softmax(x, dim=0)
model = Netz()
optimizer = optim.SGD(model.parameters(), lr=0.1, momentum=0.8)
def train(epoch):
model.train()
for batch_id, (data, target) in enumerate(train_data):
data = Variable(data)
target = Variable(target)
optimizer.zero_grad()
out = model(data)
print(out.shape)
criterion = nn.CrossEntropyLoss()
loss = criterion(out, target)
loss.backward()
optimizer.step()
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'. format(
epoch, batch_id * len(data), len(train_data.dataset),
100. * batch_id / len(train_data), loss.data[0]))
The output should show the epoch and some other information. Actually, I print out the shape of my tensor but I don't know what's wrong. Here is the error message:
/home/michael/Programmierung/Python/PyTorch/venv/bin/python /home/michael/Programmierung/Python/PyTorch/mnist.py
torch.Size([64, 20, 4, 4])
torch.Size([12, 10])
Traceback (most recent call last):
File "/home/michael/Programmierung/Python/PyTorch/mnist.py", line 69, in <module>
train(epoch)
File "/home/michael/Programmierung/Python/PyTorch/mnist.py", line 60, in train
loss = criterion(out, target)
File "/home/michael/Programmierung/Python/PyTorch/venv/lib/python3.6/site-packages/torch/nn/modules/module.py", line 493, in __call__
result = self.forward(*input, **kwargs)
File "/home/michael/Programmierung/Python/PyTorch/venv/lib/python3.6/site-packages/torch/nn/modules/loss.py", line 942, in forward
ignore_index=self.ignore_index, reduction=self.reduction)
File "/home/michael/Programmierung/Python/PyTorch/venv/lib/python3.6/site-packages/torch/nn/functional.py", line 2056, in cross_entropy
return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
File "/home/michael/Programmierung/Python/PyTorch/venv/lib/python3.6/site-packages/torch/nn/functional.py", line 1869, in nll_loss
.format(input.size(0), target.size(0)))
ValueError: Expected input batch_size (12) to match target batch_size (64).
Process finished with exit code 1
| The error occurs because your model output, out, has shape (12, 10), while your target has a length of 64.
Since you are using a batch size of 64 and predicting the probabilities of 10 classes, you would expect your model output to be of shape (64, 10), so clearly there is something amiss in the forward() method.
Going through it line by line and noting the size of x at every step, we can try to find out what is going wrong:
...
# x.shape = (64, 20, 4, 4) at this point as seen in your print statement
x = x.view(-1, 320) # x.shape = (64, 320)
x = self.fc1(x) # x.shape = (64, 60)
x = x.view(-1, 320) # x.shape = (12, 320)
x = F.relu(self.fc1(x)) # x.shape = (12, 60)
x = self.fc2(x) # x.shape = (12, 10)
return F.log_softmax(x, dim=0) # x.shape = (12, 10)
What you actually most likely want is:
...
# x.shape = (64, 20, 4, 4) at this point as seen in your print statement
x = x.view(-1, 320) # x.shape = (64, 320)
x = F.relu(self.fc1(x)) # x.shape = (64, 60)
x = self.fc2(x) # x.shape = (64, 10)
return F.log_softmax(x, dim=1) # x.shape = (64, 10)
Note: While not related to the error, note also that you want to softmax over dim=1 since that is the dimension that contains the logits for the classes.
| https://stackoverflow.com/questions/56719867/ |
Why would we use to() method in pytorch? | I've seen this method multiple times. What are the purposes and advantages of doing this?
|
Why would we use to(device) method in pytorch?
torch.Tensor.to is multipurpose method.
Not only you can do type conversion, but it can also do CPU to GPU tensor move and GPU to CPU tensor move:
tensor = torch.randn(2, 2)
print(tensor)
tensor = tensor.to(torch.float64)
print(tensor) #dtype=torch.float64
tensor = tensor.to("cuda")
print(tensor) #device='cuda:0', dtype=torch.float64)
tensor = tensor.to("cpu")
print(tensor) #dtype=torch.float64
tensor = tensor.to(torch.float32)
print(tensor) # won't print dtype=torch.float32 since it is by default
Since CPU and GPU are different kind memories, there must be a way they communicate.
This is why we have to("cuda"), and to("cpu") that we call on tensor.
Usually when you load training datasets (images):
you download them from URL (like MNIST http://deeplearning.net/data/mnist/mnist.pkl.gz)
unpack them
convert them to numpy arrays
convert numpy arrays to tensors (as this is fast)
move them to GPU for training .to("cuda")
You can create tensors and move them to GPU like this.
torch.zeros(1000).to("cuda")
But there is a trick, sometimes you can even load them directly to GPU without messing the CPU.
torch.zeros(1000, device="gpu")
| https://stackoverflow.com/questions/56722169/ |
Output hidden state in OpenNMT-py | I just have a short question regarding the pytorch version of OpenNMT. There does not seem to be an option to return the hidden state of encoder and decoder in the options. Am I missing a flag or is this not an option in OpenNMT-py?
| What do you mean by the encoder and decoder does not return hidden state?
If you see the RNNEncoder, it returns encoder_final, memory_bank, lengths where the memory_bank represents the hidden state which is of shape seq_len x batch_size x hidden_size. And the encoder_final is in general used by the decoder in a sequence-to-sequence model.
Now, let's see the RNNDecoder. As we see, the forward() method returns a FlaotTensor and a dictionary of FlaotTensors.
(FloatTensor, dict[str, FloatTensor]):
* dec_outs: output from the decoder (after attn)
``(tgt_len, batch, hidden)``.
* attns: distribution over src at each tgt
``(tgt_len, batch, src_len)``.
Usually, we use the dec_outs in sequence-to-sequence tasks. For example, in natural language generation tasks, we feed the dec_outs to a softmax layer to predict tokens.
There are several other types of encoders/decoders which you can explore from the following two links.
https://github.com/OpenNMT/OpenNMT-py/tree/master/onmt/encoders
https://github.com/OpenNMT/OpenNMT-py/tree/master/onmt/decoders
| https://stackoverflow.com/questions/56727702/ |
Can I obtain the expression of derivation by using Pytorch or Tensorflow? | My question is whether I could obtain the expression after I compute the derivation by using PyTorch or TensorFlow. For better understanding my question I provide an example below:
I have a function (x1, x2, and x3 are all the decision variables)
y = x1 + x1*x2 + x1*x3
The derivation of y in terms of x1 should be:
1 + x2 + x3
My question is, if I use PyTorch or TensorFlow do the computation, could I print out the expression of "1 + x2 + x3"? Very much appreciate if the codes are provided no matter by using PyTorch or TensorFlow.
| I don't know if it's possible in Pytorch or Tensorflow, but you can definitely do it using SymPy python library:
import sympy
x1 = sympy.symbols('x1')
x2 = sympy.symbols('x2')
x3 = sympy.symbols('x3')
y = x1 + x1*x2 + x1*x3
res = sympy.diff(y, x1)
print(res)
output:
x2 + x3 + 1
| https://stackoverflow.com/questions/56729293/ |
Best algorithm for multi agent continuous space path finding using Reinforcement learning | I am working on project in which I need to find best optimised path from 1 point to another in continuous space in multi agent scenario. I am looking for best algorithm which suits this problem using Reinforcement learning. I have tried "Multi-agent actor-critic for mixed cooperative-competitive environment" but it does not seems to reach goals in 10000 epesidoes. How can I improve this algorithm or is there any other algorithm that can help me with this.
| Multi-agent reinforcement learning is quite hard to master and has yet to prove effective for general cases.
The problem is that in multi-agent the environment becomes non-stationary from the perspective of each individual agent. This means that an agents action cannot be mapped to the state directly because other agents are performing action seperately, which "confuse" all of the agents.
There is an in-depth collection of multi-agent research here: https://github.com/LantaoYu/MARL-Papers
If you would like you to pursue the actor-critic method you mentioned, I recommend this for you further research: https://arxiv.org/pdf/1706.02275.pdf if you would like to perfect Multi-Agent Actor Critic (MADDPG)
| https://stackoverflow.com/questions/56730118/ |
How to change PyTorch tensor into a half size and/or double size with different dimension? | I'm new to PyTorch and tensor data thing. I have a problem about switching shape of tensors.
I have two questions.
First, what should I do if I have a tensor with torch.Size([8, 512, 16, 16]) and I want to change it into torch.Size([8, 256, 32, 32]) which is double size of the original tensor.
Second, what should I do if I have a tensor with torch.Size([8, 256, 32, 32]) and I want to change it into torch.Size([8, 512, 16, 16]) which is half size of the original tensor.
In the first question, I've tried on ZeroPadding2D(8) function to reshape it into torch.Size([8, 512, 32, 32]) but I don't know how to change the 2nd dimension which is 512 into 256.
The actual usage in the first question is something like this.
x = input # torch.Size([8, 512, 16, 16])
x = layer(x) # torch.Size([8, 256, 32, 32]
x = x + input # what I want to do is adding tensor values before and after passing the layer together (like skip connection)
I expect the output of adding two tensors to be success but the actual output is an error about unequal size in dimensions
|
For the first case, use resize_() to change second dimension from 512 to 256 and then allocate a tensor with your padding value and the target dimensions and assign the portion for which you have data.
import torch
target_output = torch.zeros(8, 256, 32, 32)
in_tensor = torch.randn(8, 512, 16, 16)
out_temp = in_tensor.resize_((8, 256, 16, 16))
target_output[:, :, :16, :16] = out_temp
print(target_output.shape)
# output:
# torch.Size([8, 256, 32, 32])
You can also use torch.nn.ConstantPad2d() and then resize_() as below:
in_tensor = torch.randn(8, 512, 16, 16)
m = nn.ConstantPad2d((8, 8, 8, 8), 0)
out_tensor = m(in_tensor).resize_(8, 256, 16, 16)
print(out_tensor.shape)
# output:
# torch.Size([8, 256, 32, 32])
Alternatively, you can also use torch.nn.ConstantPad2d() and copy_() like below:
import torch.nn as nn
in_tensor = torch.randn(8, 512, 16, 16) # shape [8, 512, 16, 16]
m = nn.ConstantPad2d((8, 8, 8, 8), 0)
temp = m(in_tensor) # shape [8, 512, 32, 32]
out_tensor = torch.zeros(8, 256, 32, 32) # shape [8, 256, 32, 32]
out_tensor = out_tensor[:,:,:,:].copy_(temp[:,:256,:,:]) # shape [8, 256, 32, 32]
You can read more about reshaping a tensor with padding in pytorch from here.
For the second case, you can simply use resize_() for resizing your tensor to half the size.
in_tensor = torch.randn(8, 256, 32, 32)
out_tensor = in_tensor.resize_(8, 512, 16, 16)
print(out_tensor.shape)
# output:
# torch.Size([8, 512, 16, 16])
Alternatively, you can use copy_ as below:
in_tensor = torch.randn(8, 256, 32, 32)
temp_tensor = torch.zeros(8, 512, 16, 16) # shape [8, 512, 16, 16]
temp_tensor[:,:256,:,:].copy_(in_tensor[:,:,:16,:16]) # shape [8, 512, 16, 16]
out_tensor = temp_tensor # shape [8, 512, 16, 16]
Without using copy_():
in_tensor = torch.randn(8, 256, 32, 32)
out_tensor = torch.zeros(8, 512, 16, 16) # shape [8, 512, 16, 16]
out_tensor[:,:256,:,:] = in_tensor[:,:,:16,:16]
| https://stackoverflow.com/questions/56732998/ |
How to fix RuntimeError "Expected object of scalar type Float but got scalar type Double for argument"? | I'm trying to train a classifier via PyTorch. However, I am experiencing problems with training when I feed the model with training data.
I get this error on y_pred = model(X_trainTensor):
RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1'
Here are key parts of my code:
# Hyper-parameters
D_in = 47 # there are 47 parameters I investigate
H = 33
D_out = 2 # output should be either 1 or 0
# Format and load the data
y = np.array( df['target'] )
X = np.array( df.drop(columns = ['target'], axis = 1) )
X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.8) # split training/test data
X_trainTensor = torch.from_numpy(X_train) # convert to tensors
y_trainTensor = torch.from_numpy(y_train)
X_testTensor = torch.from_numpy(X_test)
y_testTensor = torch.from_numpy(y_test)
# Define the model
model = torch.nn.Sequential(
torch.nn.Linear(D_in, H),
torch.nn.ReLU(),
torch.nn.Linear(H, D_out),
nn.LogSoftmax(dim = 1)
)
# Define the loss function
loss_fn = torch.nn.NLLLoss()
for i in range(50):
y_pred = model(X_trainTensor)
loss = loss_fn(y_pred, y_trainTensor)
model.zero_grad()
loss.backward()
with torch.no_grad():
for param in model.parameters():
param -= learning_rate * param.grad
| Reference is from this github issue.
When the error is RuntimeError: Expected object of scalar type Float but got scalar type Double for argument #4 'mat1', you would need to use the .float() function since it says Expected object of scalar type Float.
Therefore, the solution is changing y_pred = model(X_trainTensor) to y_pred = model(X_trainTensor.float()).
Likewise, when you get another error for loss = loss_fn(y_pred, y_trainTensor), you need y_trainTensor.long() since the error message says Expected object of scalar type Long.
You could also do model.double(), as suggested by @Paddy
.
| https://stackoverflow.com/questions/56741087/ |
PyTorch - Getting the 'TypeError: pic should be PIL Image or ndarray. Got ' error | I am getting the error TypeError: pic should be PIL Image or ndarray. Got <class 'numpy.ndarray'> when I try to load a non-image dataset through the DataLoader. The versions of torch and torchvision are 1.0.1, and 0.2.2.post3, respectively. Python's version is 3.7.1 on a Windows 10 machine.
Here is the code:
class AndroDataset(Dataset):
def __init__(self, csv_path):
self.transform = transforms.Compose([transforms.ToTensor()])
csv_data = pd.read_csv(csv_path)
self.csv_path = csv_path
self.features = []
self.classes = []
self.features.append(csv_data.iloc[:, :-1].values)
self.classes.append(csv_data.iloc[:, -1].values)
def __getitem__(self, index):
# the error occurs here
return self.transform(self.features[index]), self.transform(self.classes[index])
def __len__(self):
return len(self.features)
And I set the loader:
training_data = AndroDataset('android.csv')
train_loader = DataLoader(dataset=training_data, batch_size=batch_size, shuffle=True)
Here is the full error stack trace:
Traceback (most recent call last):
File "C:\Program Files\JetBrains\PyCharm 2018.1.2\helpers\pydev\pydevd.py", line 1758, in <module>
main()
File "C:\Program Files\JetBrains\PyCharm 2018.1.2\helpers\pydev\pydevd.py", line 1752, in main
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files\JetBrains\PyCharm 2018.1.2\helpers\pydev\pydevd.py", line 1147, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:\Program Files\JetBrains\PyCharm 2018.1.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/talha/Documents/PyCharmProjects/DeepAndroid/deep_test_conv1d.py", line 231, in <module>
main()
File "C:/Users/talha/Documents/PyCharmProjects/DeepAndroid/deep_test_conv1d.py", line 149, in main
for i, (images, labels) in enumerate(train_loader):
File "C:\Users\talha\Documents\PyCharmProjects\DeepAndroid\venv\lib\site-packages\torch\utils\data\dataloader.py", line 615, in __next__
batch = self.collate_fn([self.dataset[i] for i in indices])
File "C:\Users\talha\Documents\PyCharmProjects\DeepAndroid\venv\lib\site-packages\torch\utils\data\dataloader.py", line 615, in <listcomp>
batch = self.collate_fn([self.dataset[i] for i in indices])
File "C:/Users/talha/Documents/PyCharmProjects/DeepAndroid/deep_test_conv1d.py", line 102, in __getitem__
return self.transform(self.features[index]), self.transform(self.classes[index])
File "C:\Users\talha\Documents\PyCharmProjects\DeepAndroid\venv\lib\site-packages\torchvision\transforms\transforms.py", line 60, in __call__
img = t(img)
File "C:\Users\talha\Documents\PyCharmProjects\DeepAndroid\venv\lib\site-packages\torchvision\transforms\transforms.py", line 91, in __call__
return F.to_tensor(pic)
File "C:\Users\talha\Documents\PyCharmProjects\DeepAndroid\venv\lib\site-packages\torchvision\transforms\functional.py", line 50, in to_tensor
raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))
TypeError: pic should be PIL Image or ndarray. Got <class 'numpy.ndarray'>
| Expanding on @MiriamFarber's answer, you cannot use transforms.ToTensor() on numpy.ndarray objects. You can convert numpy arrays to torch tensors using torch.from_numpy() and then cast your tensor to the required datatype.
Eg:
>>> import numpy as np
>>> import torch
>>> np_arr = np.ones((5289, 38))
>>> torch_tensor = torch.from_numpy(np_arr).long()
>>> type(np_arr)
<class 'numpy.ndarray'>
>>> type(torch_tensor)
<class 'torch.Tensor'>
| https://stackoverflow.com/questions/56741108/ |
PyTorch DataLoader - "IndexError: too many indices for tensor of dimension 0" | I am trying to implement a CNN to identify digits in the MNIST dataset and my code comes up with the error during the data loading process. I don't understand why this is happening.
import torch
import torchvision
import torchvision.transforms as transforms
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5), (0.5))
])
trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=20, shuffle=True, num_workers=2)
testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=20, shuffle=False, num_workers=2)
for i, data in enumerate(trainloader, 0):
inputs, labels = data[0], data[1]
Error:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-6-b37c638b6114> in <module>
2
----> 3 for i, data in enumerate(trainloader, 0):
4 inputs, labels = data[0], data[1]
# ...
IndexError: Traceback (most recent call last):
File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/_utils/worker.py", line 99, in _worker_loop
samples = collate_fn([dataset[i] for i in batch_indices])
File "/opt/conda/lib/python3.6/site-packages/torch/utils/data/_utils/worker.py", line 99, in <listcomp>
samples = collate_fn([dataset[i] for i in batch_indices])
File "/opt/conda/lib/python3.6/site-packages/torchvision/datasets/mnist.py", line 95, in __getitem__
img = self.transform(img)
File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 61, in __call__
img = t(img)
File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 164, in __call__
return F.normalize(tensor, self.mean, self.std, self.inplace)
File "/opt/conda/lib/python3.6/site-packages/torchvision/transforms/functional.py", line 208, in normalize
tensor.sub_(mean[:, None, None]).div_(std[:, None, None])
IndexError: too many indices for tensor of dimension 0
| The problem is that the mean and std have to be sequences (e.g., tuples), therefore you should add a comma after the values:
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
Note the difference between (0.5) and (0.5,). You can check here how these values are used. If you apply the same process you'll see that:
import torch
x1 = torch.as_tensor((0.5))
x2 = torch.as_tensor((0.5,))
print(x1.shape, x1.ndim) # output: torch.Size([]) 0
print(x2.shape, x2.ndim) # output: torch.Size([1]) 1
Maybe you don't know, but they are also different in Python:
type((0.5)) # <type 'float'>
type((0.5,)) # <type 'tuple'>
| https://stackoverflow.com/questions/56745486/ |
Perform max pooling on Integer tensor in Pytorch | I am defining a max pool layer and passing in an integer tensor as follows.
max_pool = nn.MaxPool2d(3, stride=2)
max_pool(torch.IntTensor(3,5,5).random_(0, 10))
It throws the following error:
RuntimeError: _thnn_max_pool2d_with_indices_forward not supported on CPUType for Int
| As the error message suggests, nn.MaxPoll2d only supports floating point input tensors.
You'll need to cast your input int tensor to torch.float before applying the pooling.
| https://stackoverflow.com/questions/56748909/ |
How to vectorize the sum? tensor[i,:,:,:] + tensor[i] | I want to vectorize the following code:
def style_noise(self, y, style):
n = torch.randn(y.shape)
for i in range(n.shape[0]):
n[i] = (n[i] - n.mean(dim=(1, 2, 3))[i]) * style.std(dim=(1, 2, 3))[i] / n.std(dim=(1, 2, 3))[i] + style.mean(dim=(1, 2, 3))[i]
noise = Variable(n, requires_grad=False).to(y.device)
return noise
I didn't find a way nice way of doing so.
y and style are 4d tensors, say style.shape = y.shape = [64, 3, 128, 128].
I want to return the noise tensor, noise.shape = [64, 3, 128, 128].
Please let me know in the comments if the question is not clear.
| Your use case is exactly why the .mean and .std methods come with a keepdim parameter. You can make use of this to enable broadcasting semantics to vectorize things for you:
def style_noise(self, y, style):
n = torch.randn(y.shape)
n_mean = n.mean(dim=(1, 2, 3), keepdim=True)
n_std = n.std(dim=(1, 2, 3), keepdim=True)
style_mean = style.mean(dim=(1, 2, 3), keepdim=True)
style_std = style.std(dim=(1, 2, 3), keepdim=True)
n = (n - n_mean) * style_std / n_std + style_mean
noise = Variable(n, requires_grad=False).to(y.device)
return noise
| https://stackoverflow.com/questions/56750040/ |
Where do I get Visual Studio 15.4 that I need for pyTorch 0.4.1 | I have a problem with the following dependency chain:
MedicalDetectionToolkit (MDT) needs pyTorch 0.4.1 since in pyTorch 1.0 torch.utils.ffi is depricated
pyTorch 0.4.1 needs CUDA 9.0 (does not work with 10.0)
CUDA 9.0 does not work with Visual Studio > 15.4
Visual Studio 15.4 is not available anywhere, the MSVS installer will install 15.9
The Visual Studio Installer allows to install the "Compiler Tools 15.4" side-by.side, but MDT uses torch.utils.ffi at some point, which just uses the 15.9.
So
How do I install Visual Studio 15.4?
Or
How do I tell torch.utils.ffi to use the 15.4 compiler?
(MedicalDetectionToolkit will not be updated by the author. I may try it, but would like to have a working version first.)
| There are the "Build Tools for Visual Studio 2017 (version 15.0)" available on
https://my.visualstudio.com/Downloads?q=Visual%20Studio%202017
You may first have to join the "Essentials" program. After joining the downloads became visible.
| https://stackoverflow.com/questions/56755188/ |
How to permanently install package in GoogleColab using conda? | I am trying yo use a PyTorch library SparseConvNet (https://github.com/facebookresearch/SparseConvNet) in Google Colaboratory. In order to install it properly, you need to first install Conda, and then using Conda install the SparseConvNet package. Here is the code I am using (following the instructions from scn readme file):
!wget -c https://repo.continuum.io/archive/Anaconda3-5.1.0-Linux-x86_64.sh
!chmod +x Anaconda3-5.1.0-Linux-x86_64.sh
!bash ./Anaconda3-5.1.0-Linux-x86_64.sh -b -f -p /usr/local
import sys
sys.path.append('/usr/local/lib/python3.6/site-packages/')
!conda install pytorch torchvision cudatoolkit=10.0 -c pytorch
!conda install google-sparsehash -c bioconda
!conda install -c anaconda pillow
!git clone https://github.com/facebookresearch/SparseConvNet.git
!cd SparseConvNet/
!bash develop.sh
When I run this it is working and I can successfully import sparseconvnet package, but I need to do it every time I enter the notebook or restart runtime, and it's taking a lot of time. Is it possible to install these packages permanently?
There is one similar question, and the answer suggest that I should install it
on my drive, but I don't know how to do it using conda.
Thanks!
| You can specify the directory for conda to install to using
conda install -p path_to_your_dir
So, you can mount your google drive and conda install there to make it permanent.
| https://stackoverflow.com/questions/56760023/ |
Backprop through Pytorch Element-Wise Operation if input contains NaNs | Suppose I'd like to compute the element-wise quotient between two tensors. If one of the tensors contains NaNs, the resulting quotient will also contain NaNs, and this I understand. But why does the gradient becomes non-existent for the entire operation? And how can I preserve the gradient for the non-NaN entries?
For example:
>>> x = torch.tensor([1.0, np.NaN])
>>> y = torch.tensor([2.0, 3.0])
>>> z = torch.div(y, x)
>>> z
tensor([2., nan])
>>> z.backward()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.6/dist-packages/torch/tensor.py", line 107, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/usr/local/lib/python3.6/dist-packages/torch/autograd/__init__.py", line 93, in backward
allow_unreachable=True) # allow_unreachable flag
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
| There are a lot of mistakes in your code, which I hereby address, in hope to enlighten you :)
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn is NOT because of the NaN. It's because none of your input variables require a gradient, therefore z doesn't have the possibility to call backward(). You need to start the backpropagation tree somewhere.
You can't just .backward() on a tensor with multiple values. You need to sum() first, or some similar operation, but that would produce NaN in your case. You can backpropagate both parts of the z separately, by calling .backward(torch.Tensor([1.0,1.0])).
Therefore, if you fix all the bugs, it should work:
import torch
import numpy as np
x = torch.tensor([1.0, np.NaN], requires_grad=True)
y = torch.tensor([2.0, 3.0])
z = torch.div(y, x)
z.backward(torch.Tensor([1.0,1.0]))
print(x.grad)
tensor([-2., nan])
| https://stackoverflow.com/questions/56761865/ |
How to train the original U-Net model with PyTorch? | I’m trying to implement and train the original U-Net model, but I’m stuck in when I’m trying to train the model using the ISBI Challenge Dataset.
According with the original U-Net model, the network outputs an image with 2 channels and size of 388 x 388. So, my data loader for training generates a tensor with size of [batch, channels=1, width=572, height=572] for the input images and [batch, channels=2, width=388, width=388] for target/output images.
My problem actually is that when I’m trying to use the nn.CrossEntropyLoss() the following error is raised:
RuntimeError: invalid argument 3: only batches of spatial targets supported (3D tensors) but got targets of dimension: 4 at /opt/conda/conda-bld/pytorch_1556653099582/work/aten/src/THNN/generic/SpatialClassNLLCriterion.c:59
I’m just starting with PyTorch (newbie here)… so, I’ll really appreciate if someone could help me to overcome this problem.
The sourcecode is available on GitHub:
https://github.com/dalifreire/cnn_unet_pytorch
https://github.com/dalifreire/cnn_unet_pytorch/blob/master/unet_pytorch.ipynb
Best regards!
UPDATE
I just remove the channel dimension from my masks and everything works well… now I’m generating masks with the shape 1 [width=388, height=388].
After that, I’m working with input images (X), target masks (y) and predicted output masks (y_hat) as follow:
X --> torch.Size([10, 1, 572, 572])
y --> torch.Size([10, 388, 388])
y_hat --> torch.Size([10, 2, 388, 388])
But, I don’t understand why target masks (y) and predicted masks (y_hat) must have different shapes? It’s so weird for me…
| From the CrossEntropyLoss docstring of PyTorch:
Shape:
- Input: :math:`(N, C)` where `C = number of classes`, or
:math:`(N, C, d_1, d_2, ..., d_K)` with :math:`K \geq 1`
in the case of `K`-dimensional loss.
- Target: :math:`(N)` where each value is :math:`0 \leq \text{targets}[i] \leq C-1`, or
:math:`(N, d_1, d_2, ..., d_K)` with :math:`K \geq 1` in the case of
K-dimensional loss.
- Output: scalar.
If :attr:`reduction` is ``'none'``, then the same size as the target:
:math:`(N)`, or
:math:`(N, d_1, d_2, ..., d_K)` with :math:`K \geq 1` in the case
of K-dimensional loss.
If your targets contain the class indices already, you should remove the channel dimension.
Source
| https://stackoverflow.com/questions/56764048/ |
AWS tensorboard Segmentation fault (core dumped) | I am trying to use tensorboardX to debug a pytorch NN that is running in a p2.xlarge instance of AWS.
I followed this tutorial to open the port 6006.
The model is running and tensorboardX is making its writer file. I get the following warning there. I am not sure how relevant it is.
WARNING:root:tuple appears in op that does not forward tuples
(VisitNode at /pytorch/torch/csrc/jit/passes/lower_tuples.cpp:117)
frame #0: std::function::operator()() const + 0x11
(0x7fbe3dd04441 in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libc10.so)
frame #1: c10::Error::Error(c10::SourceLocation, std::string const&) +
0x2a (0x7fbe3dd03d7a in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libc10.so)
frame #2: + 0xaf61f5 (0x7fbe3cdc41f5 in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libtorch.so.1)
frame #3: + 0xaf6464 (0x7fbe3cdc4464 in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libtorch.so.1)
frame #4:
torch::jit::LowerAllTuples(std::shared_ptr&) + 0x13
(0x7fbe3cdc44a3 in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libtorch.so.1)
frame #5: + 0x3f84b4 (0x7fbe7d2cb4b4 in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libtorch_python.so)
frame #6: + 0x130cfc (0x7fbe7d003cfc in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libtorch_python.so)
frame #40: __libc_start_main + 0xf0
(0x7fbe8d69c830 in /lib/x86_64-linux-gnu/libc.so.6)
WARNING:root:tuple appears in op that does not forward tuples
(VisitNode at /pytorch/torch/csrc/jit/passes/lower_tuples.cpp:117)
frame #0: std::function::operator()() const + 0x11
(0x7fbe3dd04441 in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libc10.so)
frame #1: c10::Error::Error(c10::SourceLocation, std::string const&) +
0x2a (0x7fbe3dd03d7a in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libc10.so)
frame #2: + 0xaf61f5 (0x7fbe3cdc41f5 in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libtorch.so.1)
frame #3: + 0xaf6464 (0x7fbe3cdc4464 in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libtorch.so.1)
frame #4:
torch::jit::LowerAllTuples(std::shared_ptr&) + 0x13
(0x7fbe3cdc44a3 in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libtorch.so.1)
frame #5: + 0x3f84b4 (0x7fbe7d2cb4b4 in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libtorch_python.so)
frame #6: + 0x130cfc (0x7fbe7d003cfc in
/home/ubuntu/anaconda3/envs/pytorch_p36/lib/python3.6/site-packages/torch/lib/libtorch_python.so)
frame #40: __libc_start_main + 0xf0
(0x7fbe8d69c830 in /lib/x86_64-linux-gnu/libc.so.6)
The problem is that I don't have access to the tensorboard browser user interface. I take the following steps:
$ cd PATH_TO_FOLDER_CONTAINING_runs
$ source activate pytorch_p36
$ tensorboard --logdir=runs
Where I get the error message:
Segmentation fault (core dumped)
When I check the syslog var/log/syslog I see that following:
Jun 26 09:06:40 ip-172-xx-xx-xxx kernel: [515315.598917] tensorboard[1446]: segfault at 0 ip (null) sp 00007ffd64c5f178 error 14 in python2.7[55d8673d1000+1000]
My googling skills were far from enough. How can I access tensorboard through the browser with it running in the ASW instance?
Please let me know if something is unclear or if some info is missing.
| Even though the code has to run in the environment pytorch_p36, tensorboard actually has to run on a different environment.
The sequence of commands in the terminal should be:
$ cd PATH_TO_FOLDER_CONTAINING_runs
$ source activate tensorflow_p27
$ tensorboard --logdir=runs
Then the designated port opens.
| https://stackoverflow.com/questions/56769630/ |
Modifying the forward function in vgg model | I need to modify the existing forward method in VGG16 so that it can pass through the two classifiers and return the value
I tried creating the custom forward method manually and overriding the existing method but I get the following error
vgg.forward = forward
forward() missing 1 required positional argument: 'x'
My custom forward function
def forward(self,x):
x = self.features(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.classifier(x)
y = self.classifier_2(x)
return x,y
I have modified the default vgg16_bn with one additional classifier as
vgg = models.vgg16_bn()
final_in_features = vgg.classifier[6].in_features
mod_classifier = list(vgg.classifier.children())[:-1]
mod_classifier.extend([nn.Linear(final_in_features, 10)])
vgg.add_module('classifier_2',vgg.classifier)
My model looks like this after the addition of above classifier
(classifier): Sequential(
(0): Linear(in_features=25088, out_features=4096, bias=True)
(1): ReLU(inplace)
(2): Dropout(p=0.5)
(3): Linear(in_features=4096, out_features=4096, bias=True)
(4): ReLU(inplace)
(5): Dropout(p=0.5)
(6): Linear(in_features=4096, out_features=10, bias=True)
)
(classifier_2): Sequential(
(0): Linear(in_features=25088, out_features=4096, bias=True)
(1): ReLU(inplace)
(2): Dropout(p=0.5)
(3): Linear(in_features=4096, out_features=4096, bias=True)
(4): ReLU(inplace)
(5): Dropout(p=0.5)
(6): Linear(in_features=4096, out_features=10, bias=True)
)
My convolutional layers results are supposed to be passed through two separate FFN layers. So how do i modify my forward pass
| I think the best way to achieve what you want is to create a new model extending the nn.Module. I'd do something like:
from torchvision import models
from torch import nn
class MyVgg (nn.Module):
def __init__(self):
super(Net, self).__init__()
vgg = models.vgg16_bn(pretrained=True)
# Here you get the bottleneck/feature extractor
self.vgg_feature_extractor = nn.Sequential(*list(vgg.children())[:-1])
# Now you can include your classifiers
self.classifier1 = nn.Sequential(layers1)
self.classifier2 = nn.Sequential(layers2)
# Set your own forward pass
def forward(self, img, extra_info=None):
x = self.vgg_convs(img)
x = x.view(x.size(0), -1)
x1 = self.classifier1(x)
x2 = self.classifier2(x)
return x1, x2
| https://stackoverflow.com/questions/56772637/ |
How to train a CNN model? | When trying to train the CNN model, I came across a code shown below:
def train(n_epochs, loaders, model, optimizer, criterion):
for epoch in range(1,n_epochs):
train_loss = 0
valid_loss = 0
model.train()
for i, (data,target) in enumerate(loaders['train']):
# zero the parameter (weight) gradients
optimizer.zero_grad()
# forward pass to get outputs
output = model(data)
# calculate the loss
loss = criterion(output, target)
# backward pass to calculate the parameter gradients
loss.backward()
# update the parameters
optimizer.step()
Can someone please tell me why is the second for loop used?
i.e; for i, (data,target) in enumerate(loaders['train']):
And why optimizer.zero_grad() and optimizer.step() is used?
|
torch.utils.data.DataLoader comes in handy when you need to prepare data batches (and perhaps shuffle them before every run).
data_train_loader = DataLoader(data_train, batch_size=64, shuffle=True)
In the above code, first for-loop iterates through the number of epochs while second loop iterates through the training dataset converted into batches via above code. For example:
for batch_idx, samples in enumerate(data_train_loader):
# samples will be a 64 x D dimensional tensor
# batch_idx is each batch index
Learn more about torch.utils.data.DataLoader from here.
Optimizer.zero_gradient(): Before the backward pass, use the optimizer object to zero all of the gradients for the tensors it will update (which are the learnable weights of the model)
optimizer.step(): We generally use optimizer.step() to make the gradient descent step. Calling the step function on an Optimizer makes an update to its parameters.
Learn more about these from here.
| https://stackoverflow.com/questions/56778779/ |
RuntimeError: The size of tensor a (133) must match the size of tensor b (10) at non-singleton dimension 1 | I am training a CNN model. I am facing issue while doing the training iteration for my model. The code is as below:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
#convo layers
self.conv1 = nn.Conv2d(3,32,3)
self.conv2 = nn.Conv2d(32,64,3)
self.conv3 = nn.Conv2d(64,128,3)
self.conv4 = nn.Conv2d(128,256,3)
self.conv5 = nn.Conv2d(256,512,3)
#pooling layer
self.pool = nn.MaxPool2d(2,2)
#linear layers
self.fc1 = nn.Linear(512*5*5,2048)
self.fc2 = nn.Linear(2048,1024)
self.fc3 = nn.Linear(1024,133)
#dropout layer
self.dropout = nn.Dropout(0.3)
def forward(self, x):
#first layer
x = self.conv1(x)
x = F.relu(x)
x = self.pool(x)
#x = self.dropout(x)
#second layer
x = self.conv2(x)
x = F.relu(x)
x = self.pool(x)
#x = self.dropout(x)
#third layer
x = self.conv3(x)
x = F.relu(x)
x = self.pool(x)
#x = self.dropout(x)
#fourth layer
x = self.conv4(x)
x = F.relu(x)
x = self.pool(x)
#fifth layer
x = self.conv5(x)
x = F.relu(x)
x = self.pool(x)
#x = self.dropout(x)
#reshape tensor
x = x.view(-1,512*5*5)
#last layer
x = self.dropout(x)
x = self.fc1(x)
x = F.relu(x)
x = self.dropout(x)
x = self.fc2(x)
x = F.relu(x)
x = self.fc3(x)
return x
#loss func
criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr = 0.0001)
#criterion = nn.CrossEntropyLoss()
#optimizer = optim.SGD(net.parameters(), lr = 0.05)
def train(n_epochs,model,loader,optimizer,criterion,save_path):
for epoch in range(n_epochs):
train_loss = 0
valid_loss = 0
#training
net.train()
for batch, (data,target) in enumerate(loaders['train']):
optimizer.zero_grad()
outputs = net(data)
#print(outputs.shape)
loss = criterion(outputs,target)
loss.backward()
optimizer.step()
When I use the CrossEntropy Loss function and SGD optimizer, I able able to train the model with no error.
When I use MSE loss function and Adam optimizer, I am facing the following error:
RuntimeError Traceback (most recent call last) <ipython-input-20-2223dd9058dd> in <module>
1 #train the model
2 n_epochs = 2
----> 3 train(n_epochs,net,loaders,optimizer,criterion,'saved_model/dog_model.pt')
<ipython-input-19-a93d145ef9f7> in train(n_epochs, model, loader, optimizer, criterion, save_path)
22
23 #calculate loss
---> 24 loss = criterion(outputs,target)
25
26 #backward prop
RuntimeError: The size of tensor a (133) must match the size of tensor b (10) at non-singleton dimension 1.
Does the selected loss function and optimizer effect the training of the model? Can anyone please help on this?
| The error message clearly suggests that the error occurred at the line
loss = criterion(outputs,target)
where you are trying to compute the mean-squared error between the input and the target.
See this line: criterion = nn.MSELoss().
I think you should modify your code where you are estimating loss between (output, target) pair of inputs,i.e., loss = criterion(outputs,target) to something like below:
loss = criterion(outputs,target.view(1, -1))
Here, you are making target shape same as outputs from model on line
outputs = net(data)
One more think to notice here is the output of the net model, i.e., outputs will be of shape batch_size X output_channels, where batch size if the first dimension of input images as during the training you will get batches of images, so your shape in the forward method will get an additional batch dimension at dim0: [batch_size, channels, height, width], and ouput_channels is number of output features/channels from the last linear layer in the net model.
And, the the target labels will be of shape batch_size, which is 10 in your case, check batch_size you passed in torch.utils.data.DataLoader(). Therefore, on reshaping it using view(1, -1), it will be of converted into a shape 1 X batch_size, i.e., 1 X 10.
That's why, you are getting the error:
RuntimeError: input and target shapes do not match: input [10 x 133],
target [1 x 10]
So, a way around is to replace loss = criterion(outputs,target.view(1, -1)) with loss = criterion(outputs,target.view(-1, 1)) and change the output_channels of last linear layer to 1 instead of 133. In this way, both of outputs and target shape will be equal and we can compute MSE value then.
Learn more about pytorch MSE loss function from here.
| https://stackoverflow.com/questions/56783182/ |
RuntimeError: Given groups=1, weight of size [64, 3, 3, 3], expected input[4, 5000, 5000, 3] to have 3 channels, but got 5000 channels instead | So, I have a U-Net model and I'm feeding images of 5000x5000x3 into the model and I and getting the error above.
So here is my model.
import torch
import torch.nn as nn
def double_conv(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, 3, padding=1),
nn.ReLU(inplace=True)
)
class UNeT(nn.Module):
def __init__(self, n_class):
super().__init__()
self.dconv_down1 = double_conv(3, 64)
self.dconv_down2 = double_conv(64, 128)
self.dconv_down3 = double_conv(128, 256)
self.dconv_down4 = double_conv(256, 512)
self.maxpool = nn.MaxPool2d(2)
self.upsample = nn.Upsample(scale_factor=2, mode='bilinear',
align_corners=True)
self.dconv_up3 = double_conv(256 + 512, 256)
self.dconv_up2 = double_conv(128 + 256, 128)
self.dconv_up1 = double_conv(128 + 64, 64)
self.conv_last = nn.Conv2d(64, n_class, 1)
def forward(self, x):
conv1 = self.dconv_down1(x)
x = self.maxpool(conv1)
conv2 = self.dconv_down2(x)
x = self.maxpool(conv2)
conv3 = self.dconv_down3(x)
x = self.maxpool(conv3)
x = self.dconv_down4(x)
x = self.upsample(x)
x = torch.cat([x, conv3], dim=1)
x = self.dconv_up3(x)
x = self.upsample(x)
x = torch.cat([x, conv2], dim=1)
x = self.dconv_up2(x)
x = self.upsample(x)
x = torch.cat([x, conv1], dim=1)
x = self.dconv_up1(x)
out = self.conv_last(x)
return out
I tried to do model(inputs.unsqueeze_(0)) but I got a different error.
| The order of dimensions in pytorch is different than what you expect. Your input tensor has shape of 4x5000x5000x3 which you interpret as a batch of size 4, with images of 5000x5000 pixels, each pixel has 3 channels. That is, your dimensions are batch-height-width-channel.
However, pytorch expects tensor dimensions to be in a different order: batch-channel-height-width. That is, the channel dimension should precede the width and height spatial dimensions.
You need to permute the dimensions of your input tensor to solve your problem:
model(inputs.permute(0, 3, 1, 2))
For more information, see the documentation of nn.Conv2d.
| https://stackoverflow.com/questions/56789038/ |
I am trying to install intel optimized pytorch in different ways | I am very first time using pyTorch. I am trying to install it. In how many ways I can do this?
Please provide the steps for that.
| You can install PyTorch in 3 ways.
Using pip
Using conda
From source
1.Intel Optimized Pytorch Installation
Install the stable version (v 1.0) on Linux via Pip for Python 3.6.
pip install https://download.pytorch.org/whl/cpu/torch-1.0.1.post2-cp36-cp36m-linux_x86_64.whl
pip install torchvision
2.Conda Pytorch Installation
conda install pytorch-cpu torchvision-cpu -c pytorch
3.PyTorch Installation from source
Create a new environment:
conda create -n <env_name> python=3.6
export CMAKE_PREFIX_PATH=/home/user/.conda/envs/<env_name>
source activate <env_name>
Install dependencies:
conda install numpy pyyaml mkl mkl-include setuptools cmake cffi typing
conda install -c conda-forge opencv
conda install Pillow
Get the PyTorch source:
git clone --recursive https://github.com/intel/pytorch
cd pytorch
mv caffe2/contrib/cuda-convnet2/ /tmp
# Fix the bug removing the old package out
Install PyTorch:
python setup.py install 2>&1 | tee build.out
Hope this will help you.
| https://stackoverflow.com/questions/56792567/ |
How torch.Tensor.backward() works? | I recently study Pytorch and backward function of the package.
I understood how to use it, but when I try
x = Variable(2*torch.ones(2, 2), requires_grad=True)
x.backward(x)
print(x.grad)
I expect
tensor([[1., 1.],
[1., 1.]])
because it is an identity function. However, it returns
tensor([[2., 2.],
[2., 2.]]).
Why this happens?
| Actually, this is what you are looking for:
Case 1: when z = 2*x**3 + x
import torch
from torch.autograd import Variable
x = Variable(2*torch.ones(2, 2), requires_grad=True)
z = x*x*x*2+x
z.backward(torch.ones_like(z))
print(x.grad)
output:
tensor([[25., 25.],
[25., 25.]])
Case 2: when z = x*x
x = Variable(2*torch.ones(2, 2), requires_grad=True)
z = x*x
z.backward(torch.ones_like(z))
print(x.grad)
output:
tensor([[4., 4.],
[4., 4.]])
Case 3: when z = x (your case)
x = Variable(2*torch.ones(2, 2), requires_grad=True)
z = x
z.backward(torch.ones_like(z))
print(x.grad)
output:
tensor([[1., 1.],
[1., 1.]])
To learn more how to calculate gradient in pytorch, check this.
| https://stackoverflow.com/questions/56799616/ |
Regarding odd image dimensions in Pytorch | So I am currently building a 2-channel (also called double channel) convolution neural network for measuring the similarity between 2 (binary) images.
The problem I am having is the following:
My input images are 40 x 50, and after 1 conv and 1 pooling layer (for example), the output size is 18 x 23. So how does one do more pooling without ending up with non-integer output sizes? For example, pooling a 18 x 23 image with size 2 x 2, the output size is given by 9 x 11.5.
I cannot seem to find any suitable kernel sizes to avoid such a problem, which in my opinion is a result of the fact that the original input image dimensions are not powers of 2. For example, input images of size 64 x 64 doesn't have this issue with the correct padding size and so on.
Any help is much appreciated.
| Regarding your question:
So how does one do more pooling without ending up with non-integer output sizes?
Let's say you have:
import torch
from torch import nn
from torch.nn import functional as F
# equivalent to your (18 x 23) activation volume
x = torch.rand(1, 1, 4, 3)
print(x)
# tensor([[[[0.5005, 0.3433, 0.5252],
# [0.4878, 0.5266, 0.0237],
# [0.8600, 0.8092, 0.8912],
# [0.1623, 0.4863, 0.3644]]]])
If you apply pooling (I will use MaxPooling in this example and I assume you meant a 2x2 pooling with stride=2 based on your expected output shape):
p = nn.MaxPool2d(2, stride=2)
y = p(x)
print(y.shape)
# torch.Size([1, 1, 2, 1])
print(y)
# tensor([[[[0.5266],
# [0.8600]]]])
If you would like to have a [1, 1, 2, 2], you can set the ceil_mode=True of MaxPooling:
p = nn.MaxPool2d(2, stride=2, ceil_mode=True)
y = p(x)
print(y.shape)
# torch.Size([1, 1, 2, 2])
print(y)
# tensor([[[[0.5266, 0.5252],
# [0.8600, 0.8912]]]])
You can also pad the volume to achieve the same (here I assume the volume has min=0 as if it was after a ReLU):
p = nn.MaxPool2d(2, stride=2)
y = p(F.pad(x, (0, 1), "constant", 0))
print(y.shape)
# torch.Size([1, 1, 2, 2])
print(y)
# tensor([[[[0.5266, 0.5252],
# [0.8600, 0.8912]]]])
Regarding:
I cannot seem to find any suitable kernel sizes to avoid such a problem, which in my opinion is a result of the fact that the original input image dimensions are not powers of 2.
Well, if you want to use Pooling operations that change the input size in half (e.g., MaxPooling with kernel=2 and stride=2), then using an input with a power of 2 shape is quite convenient (after all, you'll be able to do many of these /2 operations). However, this is not required. You can change the stride of the pooling, you can always pool with ceil_mode=True, you can also pad asymmetrically, and many other things. All of them are decisions you'll have to make when building your model :)
| https://stackoverflow.com/questions/56803220/ |
Regarding the consistency of convolutional neural networks | I am currently building a 2-channel (also called double-channel) convolutional neural network in order to classify 2 binary images (containing binary objects) as 'similar' or 'different'.
The problem I am having is that it seems as though the network doesn't always converge to the same solution. For example, I can use exactly the same ordering of training pairs and all the same parameters and so forth, and when I run the network multiple times, each time produces a different solution; sometimes converging to below 2% error rates, and other times I get 50% error rates.
I have a feeling that it has something to do with the random initialization of the weights of the network, which results in different optimization paths each time the network is executed. This issue even occurs when I use SGD with momentum, so I don't really know how to 'force' the network to converge to the same solution (global optima) every time?
Can this have something to do with the fact that I am using binary images instead of grey-scale or color images, or is there something intrinsic to neural networks that is causing this issue?
| There are several sources of randomness in training.
Initialization is one. SGD itself is of course stochastic since the content of the minibatches is often random. Sometimes, layers like dropout are inherently random too. The only way to ensure getting identical results is to fix the random seed for all of them.
Given all these sources of randomness and a model with many millions of parameters, your quote
"I don't really know how to 'force' the network to converge to the same solution (global optima) every time?"
is something pretty much something anyone should say - no one knows how to find the same solution every time, or even a local optima, let alone the global optima.
Nevertheless, ideally, it is desirable to have the network perform similarly across training attempts (with fixed hyper-parameters and dataset). Anything else is going to cause problems in reproducibility, of course.
Unfortunately, I suspect the problem is inherent to CNNs.
You may be aware of the bias-variance tradeoff. For a powerful model like a CNN, the bias is likely to be low, but the variance very high. In other words, CNNs are sensitive to data noise, initialization, and hyper-parameters. Hence, it's not so surprising that training the same model multiple times yields very different results. (I also get this phenomenon, with performances changing between training runs by as much as 30% in one project I did.) My main suggestion to reduce this is stronger regularization.
Can this have something to do with the fact that I am using binary images instead of grey-scale or color images, or is there something intrinsic to neural networks that is causing this issue?
As I mentioned, this problem is present inherently for deep models to an extent. However, your use of binary images may also be a factor, since the space of the data itself is rather discontinuous. Perhaps consider "softening" the input (e.g. filtering the inputs) and using data augmentation. A similar approach is known to help in label smoothing, for example.
| https://stackoverflow.com/questions/56803337/ |
torch.argmax() fails to find a maximum value in a tensor containing data | I have a tensor of shape [batch_size, channel, depth, height, width]:
torch.Size([1, 1, 32, 64, 64])
with data:
tensor([[[[[-1.8540, -2.8068, -2.7348, ..., -1.9074, -1.8227, -1.4540],
[-2.7012, -4.2785, -3.7421, ..., -3.1961, -2.7786, -1.8042],
[-2.1924, -4.2202, -4.4361, ..., -3.1203, -2.9282, -2.3800],
...,
[-2.7429, -4.3133, -4.4029, ..., -4.4971, -5.3288, -2.8659],
[-3.0169, -4.0198, -3.6886, ..., -3.7542, -4.5010, -2.4040],
[-1.6174, -2.5340, -2.3974, ..., -1.9249, -2.4107, -1.2664]],
[[-2.7840, -3.2442, -3.6118, ..., -3.1365, -2.8342, -1.9516],
[-3.5764, -4.9253, -5.9196, ..., -4.8373, -4.2233, -3.3809],
[-3.1701, -5.0826, -5.6424, ..., -5.2955, -4.6438, -3.4820],
...,
[-4.0111, -6.1946, -5.6582, ..., -6.7947, -6.5305, -4.2866],
[-4.2103, -6.6177, -6.0420, ..., -5.8076, -6.2128, -3.2093],
[-2.3174, -4.1081, -3.7369, ..., -3.5552, -3.1871, -1.9736]],
[[-2.8441, -4.1575, -3.8233, ..., -3.5065, -3.4313, -2.3030],
[-4.0076, -5.4939, -6.2451, ..., -4.6663, -4.9835, -3.1530],
[-3.4737, -5.6347, -6.0232, ..., -5.6191, -5.2626, -3.6109],
...,
[-3.8026, -5.3676, -6.1460, ..., -7.6695, -6.7640, -4.1681],
[-4.4012, -6.1293, -6.1859, ..., -6.0011, -6.1012, -3.5307],
[-2.7917, -4.2264, -4.1388, ..., -4.2080, -3.5555, -1.6384]],
...,
[[-2.2204, -3.5705, -4.3114, ..., -4.2249, -3.9628, -2.9190],
[-3.6343, -5.3445, -6.1638, ..., -6.3998, -6.7561, -4.8491],
[-3.4870, -5.5835, -5.6436, ..., -6.8527, -7.2536, -4.8143],
...,
[-2.4492, -3.7896, -5.4344, ..., -6.2853, -6.0766, -3.7538],
[-2.4723, -3.8393, -4.8480, ..., -5.6503, -5.0375, -3.5580],
[-1.6161, -2.9843, -3.2865, ..., -3.2627, -3.2887, -2.5750]],
[[-2.1509, -3.8303, -4.2807, ..., -3.7945, -3.7561, -3.0863],
[-3.1012, -5.1321, -6.1387, ..., -6.5191, -6.3268, -4.4283],
[-2.8346, -5.0640, -5.4868, ..., -6.6515, -6.5529, -4.3672],
...,
[-2.7278, -4.2538, -4.9776, ..., -6.4153, -6.0100, -3.9929],
[-2.8002, -4.0473, -4.7455, ..., -5.4203, -4.7286, -3.4111],
[-1.7964, -3.2307, -3.6329, ..., -3.2750, -2.3952, -1.9714]],
[[-1.4447, -2.1572, -2.4487, ..., -2.3859, -2.9540, -1.8451],
[-1.8075, -2.8380, -3.5621, ..., -3.8641, -3.5828, -2.7304],
[-1.7862, -2.9849, -3.8364, ..., -4.3380, -4.4745, -2.8476],
...,
[-1.8043, -2.5662, -2.7296, ..., -4.2772, -3.9882, -2.8654],
[-1.2364, -2.5228, -2.7190, ..., -4.1142, -3.6160, -2.2325],
[-1.0395, -1.7621, -2.5738, ..., -2.0349, -1.5140, -1.1625]]]]]
Now to get the prediction from this I use
torch.argmax(data, 1)
which should give me the location of maximum values in the channel dimension, but instead I get a tensor containing only zeros. Even max(torch.argmax()) produces 0.
How can this be, the tensor is only a single dimension and a single batch, how can it return a 0?
To get rid of the negative values I applied torch.nn.Sigmoid() on it, but still argmax failed to find a maximum value. Which I dont understand, how can there not be a maximum value?
numpy.argmax(output.detach().numpy(), 1) gives the same output, all 0.
Am I not using argmax correctly?
| On this page everything is confusing for argmax.
The example they selected is 4x4 so you cannot spot the difference
a = torch.randn(5, 3)
print(a)
print(torch.argmax(a, dim=0))
print(torch.argmax(a, dim=1))
Out
tensor([[-1.0329, 0.2042, 2.5499],
[ 0.9893, 0.3913, 0.5096],
[ 0.4951, 0.2260, -0.3810],
[-1.8953, -0.6823, 0.8349],
[-0.6217, 0.4068, -1.0846]])
tensor([1, 4, 0])
tensor([2, 0, 0, 2, 1])
See how in dim=0 we have 3 values. This is the dimension of columns.
So it is telling you the element with index 1 in the first column is the max in that column.
The other dim=1 is the dimension of rows, so we have 5 values.
For your example you can calculate the shape of result for argmax:
for i in range(data.dim()):
print("dim", i)
r =torch.argmax(data,i)
print(r.shape)
dim 0
torch.Size([1, 32, 64, 64])
dim 1
torch.Size([1, 32, 64, 64])
dim 2
torch.Size([1, 1, 64, 64])
dim 3
torch.Size([1, 1, 32, 64])
dim 4
torch.Size([1, 1, 32, 64])
And for dim=0 and dim=0 you should have all 0 sine the dim is 1 (index = 0).
I tried that, but then how do I extract the maximum values from argmax and which dimension should it look against?
data = torch.randn(32, 64, 64)
values, indices = data.max(0)
print(values, indices)
values, indices = values.max(0)
print(values, indices)
values, indices = values.max(0)
print(values, indices
)
tensor([[1.9918, 1.6041, 2.6535, ..., 1.5768, 1.7320, 1.8234],
[1.6700, 2.4574, 1.8548, ..., 1.8770, 1.7674, 1.6194],
[1.8361, 1.6800, 1.8982, ..., 1.7983, 2.7109, 2.2166],
...,
[2.7439, 1.6215, 2.9740, ..., 1.7031, 1.4445, 1.6681],
[1.9437, 1.4507, 1.8551, ..., 2.5853, 1.9753, 2.4046],
[1.4198, 2.5250, 1.8949, ..., 3.2618, 2.8547, 2.0487]]) tensor([[ 4, 7, 21, ..., 27, 28, 17],
[16, 27, 18, ..., 29, 30, 19],
[ 6, 16, 14, ..., 22, 24, 29],
...,
[16, 16, 8, ..., 21, 27, 22],
[15, 0, 0, ..., 9, 12, 3],
[30, 14, 9, ..., 23, 20, 14]])
tensor([3.2089, 4.1386, 3.2650, 3.3497, 4.4210, 3.0439, 3.5144, 3.2356, 3.3058,
3.2702, 2.9981, 3.6997, 3.1719, 3.4962, 3.0889, 3.6220, 3.9256, 4.1314,
3.0804, 3.3636, 3.5517, 3.2052, 3.6548, 3.7064, 3.6531, 4.5144, 3.1287,
4.1465, 3.1906, 3.1493, 3.1996, 3.6754, 3.7610, 3.5968, 3.2109, 3.6037,
3.2799, 3.0069, 3.0386, 3.0240, 3.5372, 3.6539, 3.5571, 3.2047, 3.1218,
4.2479, 3.1230, 3.0372, 3.0258, 3.8679, 3.6409, 3.0938, 3.1246, 2.9426,
4.0824, 3.8124, 3.4226, 3.3459, 4.1600, 3.6566, 3.0351, 3.3969, 3.5842,
3.0997]) tensor([17, 21, 30, 62, 62, 63, 43, 31, 45, 63, 20, 4, 58, 23, 22, 43, 54, 30,
15, 28, 13, 4, 4, 28, 6, 52, 53, 19, 33, 20, 3, 1, 14, 40, 0, 0,
46, 62, 58, 45, 28, 50, 4, 55, 25, 5, 21, 16, 27, 32, 10, 19, 38, 30,
48, 27, 20, 9, 2, 39, 55, 58, 32, 6])
tensor(4.5144) tensor(25)
This was by dimension, or simple
m = values.max()
will give you the max value.
a = torch.argmax(values)
idx = np.unravel_index(a, values.shape)
will give you the index.
| https://stackoverflow.com/questions/56810163/ |
Dimensions Not Matching In PyTorch Linear Layer | Following the training lesson in PyTorch on this page: https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py
It's basically their 'Hello World!' version of an image classifier.
What I'm trying to do is manually code the training steps in the network to make sure I understand each one, but I am currently getting a dimension mismatch in one of my linear layers, which has me stumped. Especially since (AFAIK) I'm recreating the steps in the tutorial exactly.
Anyways........
MY NETWORK:
class net(nn.Module):
def __init__(self):
super(net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16*5*5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc2 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = net()
I believe this is exactly as they have it on their own page.
I'm trying to calculate the following step without a loop:
for epoch in range(2): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
# get the inputs; data is a list of [inputs, labels]
inputs, labels = data
# zero the parameter gradients
optimizer.zero_grad()
# forward + backward + optimize
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# print statistics
running_loss += loss.item()
if i % 2000 == 1999: # print every 2000 mini-batches
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
What I'm doing is this:
data = enumerate(trainloader)
inputs, labels = next(data)[1]
outputs = net(inputs)
And the last line gives me the following traceback:
RuntimeError Traceback (most recent call last)
<ipython-input-285-d4be5abf5bb1> in <module>
----> 1 outputs = net(inputs)
~\Anaconda\lib\site-packages\torch\nn\modules\module.py in __call__(self,
*input, **kwargs)
487 result = self._slow_forward(*input, **kwargs)
488 else:
--> 489 result = self.forward(*input, **kwargs)
490 for hook in self._forward_hooks.values():
491 hook_result = hook(self, input, result)
<ipython-input-282-a6eca2e3e9db> in forward(self, x)
14 x = x.view(-1, 16 * 5 * 5)
15 x = F.relu(self.fc1(x))
---> 16 x = F.relu(self.fc2(x))
17 x = self.fc3(x)
Which closes out with:
RuntimeError: size mismatch, m1: [4 x 120], m2: [84 x 10] at
c:\a\w\1\s\tmp_conda_3.7_110206\conda\conda-
bld\pytorch_1550401474361\work\aten\src\th\generic/THTensorMath.cpp:940
I know this means my dimension values don't match, and I suspect it has to do with the line x = x.view(-1, 16 * 5 * 5) where I go from the convolutional to linear layer, but I have two confusions:
As far as I can tell my network matches exactly what's on the PyTorch page
My error occurs on the second linear layer, not the first, and columns of the preceeding layer match the rows of the current one, so I find it confusing why this error is happening.
| Actually, there is no self.fc3(x) in __init__() as you have mentioned in forward() function. Try running you code by changing
self.fc2 = nn.Linear(84, 10) in __init__() function to
self.fc3 = nn.Linear(84, 10).
Above mistake is the reason why you are getting the error. As you are initializing self.fc2 twice in the above code, see below lines:
self.fc2 = nn.Linear(120, 84)
self.fc2 = nn.Linear(84, 10)
Here, first value of self.fc2 is overriden by later value. So, finally it is initialized with a Linear layer with input channels 84 and output channels 10.
Later on, in the forward function you are passing the output channels of x = F.relu(self.fc1(x)), i.e., 120 as an input channels to x = F.relu(self.fc2(x)), which has been changed to 84 because of the above explained reasons, you are getting the error.
Apart from this, I don't think if something wrong with your code.
| https://stackoverflow.com/questions/56810480/ |
ValueError: Only one class present in y_true. ROC AUC score is not defined in that case | I want to calculate AUROC using dataset with all instance zero. However, the following error occurred:
ValueError: Only one class present in y_true. ROC AUC score is not defined in that case
def computeAUROC (dataGT, dataPRED, classCount):
outAUROC = []
datanpGT = dataGT.cpu().numpy()
datanpPRED = dataPRED.cpu().numpy()
for i in range(classCount):
outAUROC.append(roc_auc_score(datanpGT[:, i], datanpPRED[:, i]))
return outAUROC
| You cannot have an ROC curve without both positive and negative examples in your dataset. With only one class in the dataset, you cannot measure your false-positive rate, and therefore cannot plot an ROC curve. This is why you get this error message.
| https://stackoverflow.com/questions/56815698/ |
PyTorch - BCELoss: ValueError: Target and input must have the same number of elements | When I use BCELoss as the loss function of my neural network, getting the ValueError: Target and input must have the same number of elements.
Here is my code for test phase (which is a quite typical test phase code):
network.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for data, target in test_loader:
data, target = data.to(device), target.to(device)
output = network(data)
output = output.to(device)
test_loss += loss_function(output, target).item() # error happens here
_, predicted = torch.max(output.data, 1)
correct += (predicted == target).sum().item()
The shape of the variable output is [1000, 10] as there are 10 target classes (in MNIST dataset), and the shape of the variable target is [1000] as it contains the target classes of the tested batch (the batch size for test is set to 10). So, the question is how can I apply BCELoss as the loss function of a CNN network?
p.s. The dataset I use is the MNIST dataset which is provided by the torchvision library.
p.s. The answer provided to a similar question here does not propose a solution for my case.
| The answer you claim does not propose a solution, does in fact solves your problem:
your targets are incomplete! If there are multiple classes, you should work with torch.nn.CrossEntropyLoss instead of torch.nn.BCELoss()
To recap, torch.nn.BCELoss() is intended to be used for a task of classifying c independant binary attributes per input example. You, on the other hand, have the task of classifying each output into one of c mutually exclusive classes. For this task you need a different loss, torch.nn.CrossEntropyLoss().
The different tasks, represented by the different loss functions call for different supervision (labels). If you want to classify each example to one of c mutually exclusive classes, you only need one integer label for each example (as you have in your mnist example). However, if you want to classify each example into c independent binary attributes, you need, for each example c binary labels - and this is why pytorch gives you an error.
| https://stackoverflow.com/questions/56821729/ |
What is Tensorflow equivalent of pytorch's conv1d? | Just wondering how I can perform 1D convolution in tensorflow. Specifically, looking to replace this code to tensorflow:
inputs = F.pad(inputs, (kernel_size-1,0), 'constant', 0)
output = F.conv1d(inputs, weight, padding=0, groups=num_heads)
| Tensorflow equivalent of PyTorch's
torch.nn.functional.conv1d() is
tf.nn.conv1d() and torch.nn.functional.pad() is tf.pad().
For Example:
(PyTorch code)
import torch.nn as nn
import torch
inputs = torch.tensor([1, 0, 2, 3, 0, 1, 1], dtype=torch.float32)
filters = torch.tensor([2, 1, 3], dtype=torch.float32)
inputs = inputs.unsqueeze(0).unsqueeze(0) # torch.Size([1, 1, 7])
filters = filters.unsqueeze(0).unsqueeze(0) # torch.Size([1, 1, 3])
conv_res = F.conv1d(inputs, filters, padding=0, groups=1) # torch.Size([1, 1, 5])
pad_res = F.pad(conv_res, (1, 1), mode='constant', value=0) # torch.Size([1, 1, 7])
output:
tensor([[[ 0., 8., 11., 7., 9., 4., 0.]]])
(Tensorflow code)
import tensorflow as tf
tf.enable_eager_execution()
i = tf.constant([1, 0, 2, 3, 0, 1, 1], dtype=tf.float32)
k = tf.constant([2, 1, 3], dtype=tf.float32, name='k')
data = tf.reshape(i, [1, int(i.shape[0]), 1], name='data')
kernel = tf.reshape(k, [int(k.shape[0]), 1, 1], name='kernel')
res = tf.nn.conv1d(data, kernel, 1, 'VALID')
res = tf.pad(res[0], [[1, 1], [0, 0]], "CONSTANT")
output:
<tf.Tensor: id=555, shape=(7, 1), dtype=float32, numpy=
array([[ 0.],
[ 8.],
[11.],
[ 7.],
[ 9.],
[ 4.],
[ 0.]], dtype=float32)>
| https://stackoverflow.com/questions/56821925/ |
Pytorch: Is it possible to load model when parameters or size have changed? | A Pytorch model (graph, weights, and biases) is saved with :
torch.save(self.state_dict(), file)
and loaded with :
self.load_state_dict(torch.load(file))
But if parameters are changed, the model won't load with error for example :
RuntimeError: Error(s) in loading state_dict for LeNet5:
size mismatch for conv1.weight:
Is it possible to load to the model with changed size?
Sort of filling the rest of weights like in initialization (if there are more weights) and clip if there are fewer weights?
| There is no automatic way of doing so - because you need to explicitly decide what to do when things do not match.
Personally, when I need to "force" a pre-trained weights on a slightly changed model. I find that working with the state_dict itself is the most convenient way.
new_model = model( ... ) # construct the new model
new_sd = new_model.state_dict() # take the "default" state_dict
pre_trained_sd = torch.load(file) # load the old version pre-trained weights
# merge information from pre_trained_sd into new_sd
# ...
# after merging the state dict you can load it:
new_model.load_state_dict(new_sd)
| https://stackoverflow.com/questions/56825055/ |
Why do I converge only using a parameter wrapper in PyTorch? | I'm writing an implementation of Bayesian Dropout, and the following code worked after several hours of debugging:
class DropoutLayer(nn.Module):
def __init__(self, n_in, n_out, dropout_rate):
super(DropoutLayer,self).__init__()
self.M = Parameter(torch.normal(torch.zeros(n_in,n_out),0.01))
self.m = Parameter(torch.rand(n_out))
# 1-p is used to be consistent with original dropout definition
self.z = Bernoulli(torch.tensor([1-dropout_rate]))
self.W = Parameter(torch.mm(
torch.diagflat(self.z.sample(sample_shape=(n_in,))),
self.M))
def forward(self,x,act):
activation = torch.mm(x,self.W) + self.m
out = act(activation)
return out
However, I do not seem to understand, why the matrix multiplication in self.W needs a parameter wrapping. I would assume once I nominate self.M to be a parameter in autograd, I would not need to do it for any values which use it further down the line. Why do I need it here?
After adding this wrapper, the neural net converges without a problem.
Could you tell me why is it the case and if there is a simpler substitute for this solution which I don't like?
| First of all, you don't need to pass self.M into Parameter, as the gradient does not go through it. You forward function only uses self.W and self.m (plus activation, although you really should pass it to the constructor, not forward...).
All self.M is some kind of random normal tensor created at the same time as module and it's simply initializing your self.W matrix to concrete values. So self.W is a separate tensor, it's not computationally dependent on self.M in any way.
| https://stackoverflow.com/questions/56827780/ |
Discrepancy between tensorflow's conv1d and pytorch's conv1d | I am trying to import some pytorch code to tensorflow, I came to know that torch.nn.functional.conv1d() is tf.nn.conv1d() but I am afraid there are still some discrepancies in tf's versions. Specifically, I cannot find the group parameter in tf.conv1d. For example: the following codes output two different results:
Pytorch:
inputs = torch.Tensor([[[1, 1, 1, 1],[2, 2, 2, 2],[3, 3, 3, 3]]]) #batch_sizex seq_length x embed_dim,
inputs = inputs.transpose(2,1) #batch_size x embed_dim x seq_length
batch_size, embed_dim, seq_length = inputs.size()
kernel_size = 3
in_channels = 2
out_channels = in_channels
weight = torch.ones(out_channels, 1, kernel_size)
inputs = inputs.contiguous().view(-1, in_channels, seq_length) #batch_size*embed_dim/in_channels x in_channels x seq_length
inputs = F.pad(inputs, (kernel_size-1,0), 'constant', 0)
output = F.conv1d(inputs, weight, padding=0, groups=in_channels)
output = output.contiguous().view(batch_size, embed_dim, seq_length).transpose(2,1)
Output:
tensor([[[1., 1., 1., 1.],
[3., 3., 3., 3.],
[6., 6., 6., 6.]]])
Tensorflow:
inputs = tf.constant([[[1, 1, 1, 1],[2, 2, 2, 2],[3, 3, 3, 3]]], dtype=tf.float32) #batch_sizex seq_length x embed_dim
inputs = tf.transpose(inputs, perm=[0,2,1])
batch_size, embed_dim, seq_length = inputs.get_shape()
print(batch_size, seq_length, embed_dim)
kernel_size = 3
in_channels = 2
out_channels = in_channels
weight = tf.ones([kernel_size, in_channels, out_channels])
inputs = tf.reshape(inputs, [(batch_size*embed_dim)//in_channels, in_channels, seq_length], name='inputs')
inputs = tf.transpose(inputs, perm=[0, 2, 1])
padding = [[0, 0], [(kernel_size - 1), 0], [0, 0]]
padded = tf.pad(inputs, padding)
res = tf.nn.conv1d(padded, weight, 1, 'VALID')
res = tf.transpose(res, perm=[0, 2, 1])
res = tf.reshape(res, [batch_size, embed_dim, seq_length])
res = tf.transpose(res, perm=[0, 2, 1])
print(res)
Output:
[[[ 2. 2. 2. 2.]
[ 6. 6. 6. 6.]
[12. 12. 12. 12.]]], shape=(1, 3, 4), dtype=float32)
| Different results
There is no discrepancy between those versions, you are just setting up different things. To get exactly same results as in Tensorflow change the lines specifying weights to:
weight = torch.ones(out_channels, 2, kernel_size)
, because your input has two input channels, as you have correctly declared in TF:
weight = tf.ones([kernel_size, in_channels, out_channels])
Groups parameter
You have misunderstood what is groups parameter responsible for in pytorch. It restricts the number of channels each filter uses (in this case only one as 2 input_channels divided by 2 give us one).
See here for more intuitive explanation for 2D convolution.
| https://stackoverflow.com/questions/56829138/ |
LSTM returning only zeros (PyTorch) | After succesfully implementing a LSTM "from scratch" based on linear layers, I decided to start using the existing LSTM class to make things easier and gain in performance.
But somehow when I try it, it only returns tensors full of zeros.
Here is the model :
class pytorchLSTM(nn.Module):
def __init__(self,input_size,hidden_size):
super().__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.lstm = nn.LSTM(input_size, hidden_size)
self.softmax = nn.LogSoftmax(dim = 1)
def forward(self, input):
out, hidden = self.lstm(input)
out = self.softmax(out)
return out, hidden
the input is a (1,1,60) tensor representing a one-hot encoded letter :
tensor([[[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 1., 0.]]])
and the models returns, invariably (I tried modifying the values inside of the input, but the result is always the same) :
tensor([[[0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]],
grad_fn=<LogSoftmaxBackward>)
Any idea where my mistake is and what I understood wrong about the LSTM class ?
| You are passing input of shape (1,1,60), which can be described as (sequence_length, batch_size, feature_size), where feature_size is binary.
I'm not sure why you are using LogSoftmax at all as it's discouraged and numerically unstable and it's advised to use torch.nn.CrossEntropyLoss taking logits straight out of your network, but that's not the problem here (might be later).
IIUC you are trying to predict another tensor of shape (sequence_length, batch_size, feature_size), e.g. next letter in the word (or the same later as inputted, dunno).
You need to do LogSoftmax(dim=2) (not sure if dim=-1 will work), currently you are softmaxing batch dimension.
| https://stackoverflow.com/questions/56832983/ |
Adding layers and bidirectionality to custom LSTM cell in pytorch | I use a very custom LSTM-cell inspired by http://mlexplained.com/2019/02/15/building-an-lstm-from-scratch-in-pytorch-lstms-in-depth-part-1/.
I use it to look at intermediate gating values. My question is, how would I expand this class to have an option for adding more layers and for adding bidirectionality? Should it be wrapped in a new class or added in the present one?
class Dim(IntEnum):
batch = 0
seq = 1
class simpleLSTM(nn.Module):
def __init__(self, input_sz: int, hidden_sz: int):
super().__init__()
self.input_size = input_sz
self.hidden_size = hidden_sz
# input gate
self.W_ii = Parameter(torch.Tensor(input_sz, hidden_sz))
self.W_hi = Parameter(torch.Tensor(hidden_sz, hidden_sz))
self.b_i = Parameter(torch.Tensor(hidden_sz))
# forget gate
self.W_if = Parameter(torch.Tensor(input_sz, hidden_sz))
self.W_hf = Parameter(torch.Tensor(hidden_sz, hidden_sz))
self.b_f = Parameter(torch.Tensor(hidden_sz))
# ???
self.W_ig = Parameter(torch.Tensor(input_sz, hidden_sz))
self.W_hg = Parameter(torch.Tensor(hidden_sz, hidden_sz))
self.b_g = Parameter(torch.Tensor(hidden_sz))
# output gate
self.W_io = Parameter(torch.Tensor(input_sz, hidden_sz))
self.W_ho = Parameter(torch.Tensor(hidden_sz, hidden_sz))
self.b_o = Parameter(torch.Tensor(hidden_sz))
self.init_weights()
self.out = nn.Linear(hidden_sz, len(TRG.vocab))
def init_weights(self):
for p in self.parameters():
if p.data.ndimension() >= 2:
nn.init.xavier_uniform_(p.data)
else:
nn.init.zeros_(p.data)
def forward(self, x, init_states=None ):
"""Assumes x is of shape (batch, sequence, feature)"""
seq_sz, bs, = x.size()
hidden_seq = []
prediction = []
if init_states is None:
h_t, c_t = torch.zeros(self.hidden_size).to(x.device), torch.zeros(self.hidden_size).to(x.device)
else:
h_t, c_t = init_states
for t in range(seq_sz): # iterate over the time steps
x_t = x[t, :].float()
#LOOK HERE!!!
i_t = torch.sigmoid(x_t @ self.W_ii + h_t @ self.W_hi + self.b_i)
f_t = torch.sigmoid(x_t @ self.W_if + h_t @ self.W_hf + self.b_f)
g_t = torch.tanh(x_t @ self.W_ig + h_t @ self.W_hg + self.b_g)
o_t = torch.sigmoid(x_t @ self.W_io + h_t @ self.W_ho + self.b_o)
c_t = f_t * c_t + i_t * g_t
h_t = o_t * torch.tanh(c_t)
hidden_seq.append(h_t.unsqueeze(Dim.batch))
pred_t = self.out(h_t.unsqueeze(Dim.batch))
#pred_t = F.softmax(pred_t)
prediction.append(pred_t)
hidden_seq = torch.cat(hidden_seq, dim=Dim.batch)
prediction = torch.cat(prediction, dim=Dim.batch)
# reshape from shape (sequence, batch, feature) to (batch, sequence, feature)
hidden_seq = hidden_seq.transpose(Dim.batch, Dim.seq).contiguous()
prediction = prediction.transpose(Dim.batch, Dim.seq).contiguous()
return prediction, hidden_seq, (h_t, c_t)
I call it and train using the following as an example.
lstm = simpleLSTM(1, 100)
hidden_size = lstm.hidden_size
optimizer = optim.Adam(lstm.parameters())
h_0, c_0 = (torch.zeros(hidden_size, requires_grad=True),
torch.zeros(hidden_size, requires_grad=True))
grads = []
h_t, c_t = h_0, c_0
N_EPOCHS = 10
for epoch in range(N_EPOCHS):
epoch_loss = 0
for i, batch in enumerate(train):
optimizer.zero_grad()
src, src_len = batch.src
trg = batch.trg
trg = trg.view(-1)
predict, output, hidden_states = lstm(src)
predict = predict.t().unsqueeze(1)
predict= predict.view(-1, predict.shape[-1])
loss = criterion(predict,trg)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
print(epoch_loss)
| The easiest would be to create another module (say Bidirectional) and pass any cell you want to it.
Implementation itself is quite easy to do. Notice that I'm using concat operation for joining bi-directional output, you may want to specify other modes like summation etc.
Please read the comments in the code below, you may have to change it appropriately.
import torch
class Bidirectional(torch.nn.Module):
def __init__(self, cell):
super().__init__()
self.cell = cell
def __call__(self, x, init_states=None):
prediction, hidden_seq, (h_t, c_t) = self.cell(x, init_states)
backward_prediction, backward_hidden_seq, (
backward_h_t,
backward_c_t,
# Assuming sequence is first dimension, otherwise change 0 appropriately
# Reverses sequences so the LSTM cell acts on the reversed sequence
) = self.cell(torch.flip(x, (0,)), init_states)
return (
# Assuming you transpose so it has (batch, seq, features) dimensionality
torch.cat((prediction, backward_prediction), 2),
torch.cat((hidden_seq, backward_hidden_seq), 2),
# Assuming it has (batch, features) dimensionality
torch.cat((h_t, backward_ht), 1),
torch.cat((c_t, backward_ct), 1),
)
When it comes to multiple layers you could do something similiar in principle:
import torch
class Multilayer(torch.nn.Module):
def __init__(self, *cells):
super().__init__()
self.cells = torch.nn.ModuleList(cells)
def __call__(self, x, init_states=None):
inputs = x
for cell in self.cells:
prediction, hidden_seq, (h_t, c_t) = cell(inputs, init_states)
inputs = hidden_seq
return prediction, hidden_seq, (h_t, c_t)
Please note you have to pass created cell objects into Multilayer e.g.:
# For three layers of LSTM, each needs features to be set up correctly
multilayer_LSTM = Multilayer(LSTM(), LSTM(), LSTM())
You may also pass classes instead of instances into constructor and create those inside Multilayer (so hidden_size matches automatically), but those ideas should get you started.
| https://stackoverflow.com/questions/56835100/ |
'DataLoader' object does not support indexing | I have downloaded the ImageNet dataset via this pytorch api by setting download=True. But I cannot iterate through the dataloader.
The error says "'DataLoader' object does not support indexing"
trainset = torch.utils.data.DataLoader(
datasets.ImageNet('/media/farshid/DataStore/temp/Imagenet/', split='train',
download=False))
trainloader = torch.utils.data.DataLoader(trainset, batch_size=1, shuffle=False, num_workers=1)
I tried a simple approach I just tried to run the following,
trainloader[0]
In the root directory, the pattern is
root/
train/
n01440764/
n01443537/
n01443537_2.jpg
The docs in the official website doesnt say anything else. https://pytorch.org/docs/stable/torchvision/datasets.html#imagenet
What am I doing wrong ?
| Solution
input_transform = standard_transforms.Compose([
transforms.Resize((255,255)), # to Make sure all the
transforms.CenterCrop(224), # imgs are at the same size
transforms.ToTensor()
])
# torch.utils.data.Dataset object
trainset = datasets.ImageNet('/media/farshid/DataStore/temp/Imagenet/',
split='train', download=False, transform = input_transform)
# torch.utils.data.DataLoader object
trainloader =torch.utils.data.DataLoader(trainset, batch_size=2, shuffle=False)
for batch_idx, data in enumerate(trainloader, 0):
x, y = data
break
| https://stackoverflow.com/questions/56838341/ |
Nonexistant pytorch gradients when dotting tensors in loss function | For the purposes of this MWE I'm trying to fit a linear regression using a custom loss function with multiple terms. However, I'm running into strange behavior when trying to weight the different terms in my loss function by dotting a weight vector with my losses. Just summing the losses works as expected; however, when dotting the weights and losses the backpropagation gets broken somehow and the loss function doesn't decrease.
I've tried enabling and disabling requires_grad on both tensors, but have been unable to replicate the expected behavior.
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
# Hyper-parameters
input_size = 1
output_size = 1
num_epochs = 60
learning_rate = 0.001
# Toy dataset
x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
[9.779], [6.182], [7.59], [2.167], [7.042],
[10.791], [5.313], [7.997], [3.1]], dtype=np.float32)
y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
[3.366], [2.596], [2.53], [1.221], [2.827],
[3.465], [1.65], [2.904], [1.3]], dtype=np.float32)
# Linear regression model
model = nn.Linear(input_size, output_size)
# Loss and optimizer
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
def loss_fn(outputs, targets):
l1loss = torch.norm(outputs - targets, 1)
l2loss = torch.norm(outputs - targets, 2)
# This works as expected
# loss = 1 * l1loss + 1 * l2loss
# Loss never changes, no matter what combination of
# requires_grad I set
loss = torch.dot(torch.tensor([1.0, 1.0], requires_grad=False),
torch.tensor([l1loss, l2loss], requires_grad=True))
return loss
# Train the model
for epoch in range(num_epochs):
# Convert numpy arrays to torch tensors
inputs = torch.from_numpy(x_train)
targets = torch.from_numpy(y_train)
# Forward pass
outputs = model(inputs)
loss = loss_fn(outputs, targets)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch+1) % 5 == 0:
print ('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# Plot the graph
predicted = model(torch.from_numpy(x_train)).detach().numpy()
plt.plot(x_train, y_train, 'ro', label='Original data')
plt.plot(x_train, predicted, label='Fitted line')
plt.legend()
plt.show()
Expected result: loss function decreases and the linear regression is fitted (see output below)
Epoch [5/60], Loss: 7.9943
Epoch [10/60], Loss: 7.7597
Epoch [15/60], Loss: 7.6619
Epoch [20/60], Loss: 7.6102
Epoch [25/60], Loss: 7.4971
Epoch [30/60], Loss: 7.4106
Epoch [35/60], Loss: 7.3942
Epoch [40/60], Loss: 7.2438
Epoch [45/60], Loss: 7.2322
Epoch [50/60], Loss: 7.1012
Epoch [55/60], Loss: 7.0701
Epoch [60/60], Loss: 6.9612
Actual result: no change in loss function
Epoch [5/60], Loss: 73.7473
Epoch [10/60], Loss: 73.7473
Epoch [15/60], Loss: 73.7473
Epoch [20/60], Loss: 73.7473
Epoch [25/60], Loss: 73.7473
Epoch [30/60], Loss: 73.7473
Epoch [35/60], Loss: 73.7473
Epoch [40/60], Loss: 73.7473
Epoch [45/60], Loss: 73.7473
Epoch [50/60], Loss: 73.7473
Epoch [55/60], Loss: 73.7473
Epoch [60/60], Loss: 73.7473
I'm pretty confused as to why such a simple operation is breaking the backpropagation gradients and would really appreciate it if anyone had some insights on why this isn't working.
| Use torch.cat((loss1, loss2)), you are creating new Tensor from existing tensors destroying graph.
Anyway you shouldn't do that unless you are trying to generalize your loss function, it's pretty unreadable. Simple addition is way better.
| https://stackoverflow.com/questions/56838750/ |
My custom loss function in Pytorch does not train | My custom loss function in Pytorch does not update during training. The loss stays exactly the same. I am trying to write this custom loss function based on the false positive and negative rates. I am giving you a simplified version of the code. Any idea what could be happening? Does the backpropagation turns to 0? Is this not the correct way of defining a custom loss function?
I have already checked that during backpropagation the Gradient always stays TRUE (assert requires_grad). I have also tried to make a class (torch.nn.module) of the function false_pos_neg_rate, but that did not work. The Assert Requires_grad turned out to be negative and I left it out afterwards.
There is no error, the training does continue.
def false_pos_neg_rate(outputs, truths):
y = truths
y_predicted = outputs
cut_off= torch.tensor(0.5, requires_grad=True)
y_predicted =torch.where(y_predicted <= cut_off, zeros, ones)
tp, fp, tn, fn = confusion_matrix(y_predicted, y)
fp_rate = fp / (fp+tn).float()
fn_rate = fn / (fn+tp).float()
loss = fn_rate + fp_rate
return loss
for i, (samples, truths) in enumerate(train_loader):
samples = Variable(samples)
truths = Variable(truths)
outputs = model(samples)
loss = false_pos_neg_rate_torch(outputs, truths)
loss.backward()
optimizer.step()
I expect the loss function to update the model and be smaller every training step. Instead the loss stays exactly the same and nothing happens.
Please help me, what happens? Why does the model not train during training steps?
| As pointed out by Umang Gupta your loss function is not differentiable. If you write, mathematically, what you are trying to do you'll see that your loss has zero gradient almost everywhere and it behaves like a "step function".
In order to train models using gradient-descent methods you must have meaningful gradients for the loss function.
| https://stackoverflow.com/questions/56839201/ |
Weights of nn.ModuleList() are adjusted even if no forward propagation was applied | I'm trying to use nn.ModuleList() to conduct some multitask learning, but the weights of all list elements (i.e. tasks) are adjusted when they were trained before. The following code (based on this notebook) creates a neural network object called MTL.
import torch
import torch.nn as nn
import numpy as np
import os
from torch.autograd import Variable
import math
import sklearn.preprocessing as sk
from sklearn.model_selection import KFold
from sklearn import metrics
from sklearn.feature_selection import VarianceThreshold
from sklearn.linear_model import Ridge
from sklearn.linear_model import RidgeCV
from sklearn.model_selection import train_test_split
import random
#creating training data
seed = 42
random.seed(seed)
torch.cuda.manual_seed_all(seed)
N = 10000
M = 100
c = 0.5
p = 0.9
k = np.random.randn(M)
u1 = np.random.randn(M)
u1 -= u1.dot(k) * k / np.linalg.norm(k)**2
u1 /= np.linalg.norm(u1)
k /= np.linalg.norm(k)
u2 = k
w1 = c*u1
w2 = c*(p*u1+np.sqrt((1-p**2))*u2)
X = np.random.normal(0, 1, (N, M))
eps1 = np.random.normal(0, 0.01)
eps2 = np.random.normal(0, 0.01)
Y1 = np.matmul(X, w1) + np.sin(np.matmul(X, w1))+eps1
Y2 = np.matmul(X, w2) + np.sin(np.matmul(X, w2))+eps2
split = list(np.random.permutation(N))
X_train = X[split[0:8000],:]
Y1_train = Y1[split[0:8000]]
Y2_train = Y2[split[0:8000]]
X_valid = X[8000:9000,:]
Y1_valid = Y1[8000:9000]
Y2_valid = Y2[8000:9000]
X_test = X[9000:10000,:]
Y1_test = Y1[9000:10000]
Y2_test = Y2[9000:10000]
X_train = torch.from_numpy(X_train)
X_train = X_train.float()
Y1_train = torch.tensor(Y1_train)
Y1_train = Y1_train.float()
Y2_train = torch.tensor(Y2_train)
Y2_train = Y2_train.float()
X_valid = torch.from_numpy(X_valid)
X_valid = X_valid.float()
Y1_valid = torch.tensor(Y1_valid)
Y1_valid = Y1_valid.float()
Y2_valid = torch.tensor(Y2_valid)
Y2_valid = Y2_valid.float()
X_test = torch.from_numpy(X_test)
X_test = X_test.float()
Y1_test = torch.tensor(Y1_test)
Y1_test = Y1_test.float()
Y2_test = torch.tensor(Y2_test)
Y2_test = Y2_test.float()
input_size, feature_size = X.shape
LR = 0.001
epoch = 50
mb_size = 100
#the network
class MTLnet(nn.Module):
def __init__(self):
super(MTLnet, self).__init__()
self.sharedlayer = nn.Sequential(
nn.Linear(feature_size, 64),
nn.ReLU(),
nn.Dropout()
)
output = ['tower1', 'tower2']
self.scoring_list = nn.ModuleList()
for task, lab in enumerate(output):
tower = nn.Sequential(
nn.Linear(64, 32),
nn.ReLU(),
nn.Dropout(),
nn.Linear(32, 16),
nn.ReLU(),
nn.Dropout(),
nn.Linear(16, 1)
)
self.scoring_list.append(tower)
def forward(self, x, task_id):
h_shared = self.sharedlayer(x)
logits = self.scoring_list[task_id](h_shared)
return logits
def random_mini_batches(XE, R1E, R2E, mini_batch_size = 3, seed = 42):
# Creating the mini-batches
np.random.seed(seed)
m = XE.shape[0]
mini_batches = []
permutation = list(np.random.permutation(m))
shuffled_XE = XE[permutation,:]
shuffled_X1R = R1E[permutation]
shuffled_X2R = R2E[permutation]
num_complete_minibatches = math.floor(m/mini_batch_size)
for k in range(0, int(num_complete_minibatches)):
mini_batch_XE = shuffled_XE[k * mini_batch_size : (k+1) * mini_batch_size, :]
mini_batch_X1R = shuffled_X1R[k * mini_batch_size : (k+1) * mini_batch_size]
mini_batch_X2R = shuffled_X2R[k * mini_batch_size : (k+1) * mini_batch_size]
mini_batch = (mini_batch_XE, mini_batch_X1R, mini_batch_X2R)
mini_batches.append(mini_batch)
Lower = int(num_complete_minibatches * mini_batch_size)
Upper = int(m - (mini_batch_size * math.floor(m/mini_batch_size)))
if m % mini_batch_size != 0:
mini_batch_XE = shuffled_XE[Lower : Lower + Upper, :]
mini_batch_X1R = shuffled_X1R[Lower : Lower + Upper]
mini_batch_X2R = shuffled_X2R[Lower : Lower + Upper]
mini_batch = (mini_batch_XE, mini_batch_X1R, mini_batch_X2R)
mini_batches.append(mini_batch)
return mini_batches
MTL = MTLnet()
optimizer = torch.optim.Adam(MTL.parameters(), lr=LR)
loss_func = nn.MSELoss()
The neural network has the following structure:
<bound method Module.parameters of MTLnet(
(sharedlayer): Sequential(
(0): Linear(in_features=100, out_features=64, bias=True)
(1): ReLU()
(2): Dropout(p=0.5)
)
(scoring_list): ModuleList(
(0): Sequential(
(0): Linear(in_features=64, out_features=32, bias=True)
(1): ReLU()
(2): Dropout(p=0.5)
(3): Linear(in_features=32, out_features=16, bias=True)
(4): ReLU()
(5): Dropout(p=0.5)
(6): Linear(in_features=16, out_features=1, bias=True)
)
(1): Sequential(
(0): Linear(in_features=64, out_features=32, bias=True)
(1): ReLU()
(2): Dropout(p=0.5)
(3): Linear(in_features=32, out_features=16, bias=True)
(4): ReLU()
(5): Dropout(p=0.5)
(6): Linear(in_features=16, out_features=1, bias=True)
)
)
)>
The initial values of the weights are (yours will differ):
print(MTL.state_dict()['scoring_list.0.6.weight'])
print(MTL.state_dict()['scoring_list.1.6.weight'])
Output:
tensor([[-0.0240, -0.1798, -0.2393, -0.2149, -0.1393, 0.1718, -0.1476, 0.0346,
0.2485, -0.0305, -0.1574, 0.1500, -0.2356, -0.0597, 0.0291, 0.0521]])
tensor([[ 0.2046, -0.1277, -0.2103, -0.1006, -0.1311, 0.1902, -0.0969, -0.0953,
0.1340, 0.1506, -0.1222, -0.0638, -0.0661, 0.1118, -0.1009, -0.1438]])
The following code trains the neural network and prints the weights after every epoch. The first epoch will train the shared layer and the first element of nn.ModuleList() (i.e. task1). The second epoch will train the shared layer and the second element of the nn.ModuleList() (i.e. task2).
trainTask1 = True
epoch = 2
for it in range(epoch):
minibatches = random_mini_batches(X_train, Y1_train, Y2_train, mb_size)
for minibatch in minibatches:
XE, YE1, YE2 = minibatch
if trainTask1:
Yhat = MTL(XE, 0)
loss = loss_func(Yhat, YE1.view(-1,1))
else:
Yhat = MTL(XE, 1)
loss = loss_func(Yhat, YE2.view(-1,1))
optimizer.zero_grad()
loss.backward()
optimizer.step()
#Shows you the weights of task 1 and they get adjusted during the 2 epoch even if no training has happened
#print("Task 1 weights {}".format(MTL.state_dict()['scoring_list.0.6.weight']))
#@prosti suggested to freeze the layers of the task which aren't trained
if trainTask1:
trainTask1 = False
for param in MTL.scoring_list[0].parameters():
param.requires_grad = False
else:
trainTask1 = True
for param in MTL.scoring_list[1].parameters():
param.requires_grad = False
print(it)
print(MTL.state_dict()['scoring_list.0.6.weight'])
print(MTL.state_dict()['scoring_list.1.6.weight'])
Output:
0
tensor([[-0.0283, -0.2025, -0.2181, -0.2183, -0.1438, 0.1605, -0.1715, 0.0863,
0.2765, -0.0153, -0.1519, 0.1704, -0.2453, -0.0539, 0.0220, 0.0739]])
tensor([[ 0.2046, -0.1277, -0.2103, -0.1006, -0.1311, 0.1902, -0.0969, -0.0953,
0.1340, 0.1506, -0.1222, -0.0638, -0.0661, 0.1118, -0.1009, -0.1438]])
1
tensor([[-0.0311, -0.2114, -0.2162, -0.2214, -0.1463, 0.1614, -0.1800, 0.1003,
0.2850, -0.0148, -0.1576, 0.1809, -0.2511, -0.0575, 0.0221, 0.0844]])
tensor([[ 0.2693, -0.0921, -0.2313, -0.1483, -0.0995, 0.2497, -0.1028, -0.1108,
0.1405, 0.1997, -0.1266, -0.0725, -0.0871, 0.1472, -0.0924, -0.0994]])
After the first epoch the weights of task1 were adjusted but not the weights of task2 (as expected), but after the second epoch the weights of both tasks were adjusted. That shouldn't happen.
You can also see that when you print the weights during the over minibatches (just uncomment the print), they are always get adjusted for the first task even if all layers were freezed and no calculation has happened.
Is there another cache I have to clear besides optimizer.zero_grad()?
| If you monitor MTL.scoring_list[0][6].weight.grad and MTL.scoring_list[1][6].weight.grad during training, you'll notice that, in the first epoch, MTL.scoring_list[1][6].weight.grad is None, while in the second epoch, MTL.scoring_list[0][6].weight.grad is a zero tensor.
Looking at the source of .step() for various optimizers, it appears that they don't check for .requires_grad. They only check if .grad is None. So even if .grad is a zero tensor, optimizer.step will still do its thing. Whether this ends up affecting the frozen weights or not depends on the exact computations that the optimizer performs.
As a quick fix, you can add param.grad = None, after param.requires_grad = False, so that the optimizer ignores those parameters entirely. This seems to fix the problem. But you might still want to think about any implications it might have for the optimizer's calculations for future epochs.
| https://stackoverflow.com/questions/56845542/ |
Nsight Compute can't profile Waveglow (PyTorch application) | I tried to profile https://github.com/NVIDIA/waveglow by this command:
nv-nsight-cu-cli --export ./nsight_output ~/.virtualenvs/waveglow/bin/python3 inference.py -f <(ls mel_spectrograms/*.pt) -w waveglow_256channels.pt -o . --is_fp16 -s 0.6
Python command is from instruction of https://github.com/NVIDIA/waveglow#generate-audio-with-our-pre-existing-model ,
and it works with Nsight System, not Nsight Compute.
Profiling doesn't end printing this log; so I pressed Ctrl+C.
Also, It profiles only one kernel but I have more kernels. (checked by Nsight Systems)
...
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 286: 0%....50%....100% - 48 passes
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 287: 0%....50%....100% - 48 passes
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 288: 0%....50%....100% - 48 passes
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 289: 0%....50%....100% - 48 passes
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 290: 0%....50%....100% - 48 passes
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 291: 0%....50%....100% - 48 passes
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 292: 0%....50%....100% - 48 passes
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 293: 0%....50%....100% - 48 passes
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 294: 0%....50%....100% - 48 passes
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 295: 0%....50%....100% - 48 passes
==PROF== Profiling "weight_norm_fwd_first_dim_ker..." - 296: 0%....50%...^C
==PROF== Received signal, trying to shutdown target application
- 43 passes
==ERROR== Failed to profile kernel "weight_norm_fwd_first_dim_ker..." in process
==ERROR== An error occurred while trying to profile.
==ERROR== An error occurred while trying to profile
==PROF== Report: nsight_compute_result.nsight-cuprof-report
OS: CentOS Linux 7, Nsight Compute (2019.3.1, Build 26317742),
GPU: Tesla V100-PCIE-32GB
How can I fix this?
| I don't think there is any error here, the tool behaves as expected. It does not profile only one kernel, it profiled 296 kernel launches already in your log output (which appear to all be from one kernel function).
You can control the number or types of kernels that are profiled using e.g. the --launch-count or the --kernel-regex options. You can also control the metrics collected for each kernel using --metrics and --section, as collecting fewer metrics reduces the overhead of the tool.
See https://docs.nvidia.com/nsight-compute/NsightComputeCli/index.html#command-line-options for more available command line options.
| https://stackoverflow.com/questions/56847901/ |
LSTM getting caught up in loop | I recently implemented a name generating RNN "from scratch" which was doing ok but far from perfect. So I thought about trying my luck with pytorch's LSTM class to see if it makes a difference. Indeed it does and the outpus looks way better for the first 7 ~ 8 characters. But then the networks gets caught in a loop and outputs things like "laulaulaulau" or "rourourourou" (it is supposed the generate french names).
Is it a often occuring problem ? If so do you know a way to fix it ? I'm concern about the fact the network doesn't produce EOS tokens...
This is an issue which has already been asked here Why does my keras LSTM model get stuck in an infinite loop?
but not really answered hence my post.
here is the model :
class pytorchLSTM(nn.Module):
def __init__(self,input_size,hidden_size):
super(pytorchLSTM,self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.lstm = nn.LSTM(input_size, hidden_size)
self.output_layer = nn.Linear(hidden_size,input_size)
self.tanh = nn.Tanh()
self.softmax = nn.LogSoftmax(dim = 2)
def forward(self, input, hidden)
out, hidden = self.lstm(input,hidden)
out = self.tanh(out)
out = self.output_layer(out)
out = self.softmax(out)
return out, hidden
The input and target are two sequences of one-hot encoded vectors respectively with a start of sequence and end of sequence vector at the start and the end. They represent the characters inside of a name taken from the name list (database).
I use a and token on each name from the database. here are the function I use
def inputTensor(line):
#tensor starts with <start of sequence> token.
tensor = torch.zeros(len(line)+1, 1, n_letters)
tensor[0][0][n_letters - 2] = 1
for li in range(len(line)):
letter = line[li]
tensor[li+1][0][all_letters.find(letter)] = 1
return tensor
# LongTensor of second letter to end (EOS) for target
def targetTensor(line):
letter_indexes = [all_letters.find(line[li]) for li in range(len(line))]
letter_indexes.append(n_letters - 1) # EOS
return torch.LongTensor(letter_indexes)
training loop :
def train_lstm(model):
start = time.time()
criterion = nn.NLLLoss()
optimizer = torch.optim.Adam(model.parameters())
n_iters = 20000
print_every = 1000
plot_every = 500
all_losses = []
total_loss = 0
for iter in range(1,n_iters+1):
line = randomChoice(category_line)
input_line_tensor = inputTensor(line)
target_line_tensor = targetTensor(line).unsqueeze(-1)
optimizer.zero_grad()
loss = 0
output, hidden = model(input_line_tensor)
for i in range(input_line_tensor.size(0)):
l = criterion(output[i], target_line_tensor[i])
loss += l
loss.backward()
optimizer.step()
the sampling function :
def sample():
max_length = 20
input = torch.zeros(1,1,n_letters)
input[0][0][n_letters - 2] = 1
output_name = ""
hidden = (torch.zeros(2,1,lstm.hidden_size),torch.zeros(2,1,lstm.hidden_size))
for i in range(max_length):
output, hidden = lstm(input)
output = output[-1][:][:]
l = torch.multinomial(torch.exp(output[0]),num_samples = 1).item()
if l == n_letters - 1:
break
else:
letter = all_letters[l]
output_name += letter
input = inputTensor(letter)
return output_name
The typical sampled output looks something like that :
Laurayeerauerararauo
Leayealouododauodouo
Courouauurourourodau
Do you know how I can improve that ?
| I found the explanation :
When using instances of the LSTM class as part of a RNN, the default input dimensions are (seq_length,batch_dim,input_size). To be able to interpret the output of the lstm as a probability (over the set of inputs) I needed to pass it to a Linear layer before the Softmax call, which is where the problem happens : Linear instances expects the input to be in the format (batch_dim,seq_length,input_size).
To fix this, one needs to pass batch_first = True as an argument to the LSTM upon creation, and then feed the RNN with an input of the form (batch_dim, seq_length, input_size).
| https://stackoverflow.com/questions/56849552/ |
ImportError: Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training | cannot install apex for distributed and fp16 training of bert model
i have tried to install by cloning the apex from github and tried to install packages using pip
i have tried to install apex by cloning from git hub using following command:
git clone https://github.com/NVIDIA/apex.git
and cd apex to goto apex directory and tried to install package using following pip command:
pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext"
full code is:
def main(server_ip,server_port,local_rank,no_cuda,fp16,train_batch_size,gradient_accumulation_steps,seed,do_train,do_eval,output_dir,task_name,data_dir,do_lower_case,bert_model,num_train_epochs,cache_dir,learning_rate,warmup_proportion,loss_scale,max_seq_length):
if server_ip and server_port:
# Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
import ptvsd
print("Waiting for debugger attach")
ptvsd.enable_attach(address=(server_ip, server_port), redirect_output=True)
ptvsd.wait_for_attach()
processors = {"ner":NerProcessor}
print(processors)
if local_rank == -1 or no_cuda:
device = torch.device("cuda" if torch.cuda.is_available() and not no_cuda else "cpu")
n_gpu = torch.cuda.device_count()
else:
torch.cuda.set_device(local_rank)
device = torch.device("cuda", local_rank)
n_gpu = 1
# Initializes the distributed backend which will take care of sychronizing nodes/GPUs
torch.distributed.init_process_group(backend='nccl')
logger.info("device: {} n_gpu: {}, distributed training: {}, 16-bits training: {}".format(
device, n_gpu, bool(local_rank != -1), fp16))
if gradient_accumulation_steps < 1:
raise ValueError("Invalid gradient_accumulation_steps parameter: {}, should be >= 1".format(
args.gradient_accumulation_steps))
train_batch_size = train_batch_size // gradient_accumulation_steps
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if not do_train and not do_eval:
raise ValueError("At least one of `do_train` or `do_eval` must be True.")
if os.path.exists(output_dir) and os.listdir(output_dir) and do_train:
raise ValueError("Output directory ({}) already exists and is not empty.".format(output_dir))
if not os.path.exists(output_dir):
os.makedirs(output_dir)
task_name = task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
label_list = processor.get_labels()
num_labels = len(label_list) + 1
tokenizer = BertTokenizer.from_pretrained(bert_model, do_lower_case=do_lower_case)
train_examples = None
num_train_optimization_steps = None
if do_train:
train_examples = processor.get_train_examples(data_dir)
num_train_optimization_steps = int(
len(train_examples) / train_batch_size / gradient_accumulation_steps) * num_train_epochs
if local_rank != -1:
num_train_optimization_steps = num_train_optimization_steps // torch.distributed.get_world_size()
# # Prepare model
cache_dir = cache_dir if cache_dir else os.path.join(str(PYTORCH_PRETRAINED_BERT_CACHE), 'distributed_{}'.format(local_rank))
model = Ner.from_pretrained(bert_model,
cache_dir=cache_dir,
num_labels = num_labels)
if fp16:
model.half()
# model.cuda()
model.to(device)
if local_rank != -1:
try:
from apex.parallel import DistributedDataParallel as DDP
except ImportError:
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
model = DDP(model)
elif n_gpu > 1:
model = torch.nn.DataParallel(model)
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)], 'weight_decay': 0.01},
{'params': [p for n, p in param_optimizer if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
if fp16:
try:
from apex.optimizers import FP16_Optimizer
from apex.optimizers import FusedAdam
except ImportError:
raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use distributed and fp16 training.")
optimizer = FusedAdam(optimizer_grouped_parameters,
lr=learning_rate,
bias_correction=False,
max_grad_norm=1.0)
if loss_scale == 0:
optimizer = FP16_Optimizer(optimizer, dynamic_loss_scale=True)
else:
optimizer = FP16_Optimizer(optimizer, static_loss_scale=loss_scale)
else:
optimizer = BertAdam(optimizer_grouped_parameters,
lr=learning_rate,
warmup=warmup_proportion,
t_total=num_train_optimization_steps)
global_step = 0
nb_tr_steps = 0
tr_loss = 0
label_map = {i : label for i, label in enumerate(label_list,1)}
if do_train:
train_features = convert_examples_to_features(
train_examples, label_list, max_seq_length, tokenizer)
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(train_examples))
logger.info(" Batch size = %d", train_batch_size)
logger.info(" Num steps = %d", num_train_optimization_steps)
all_input_ids = torch.tensor([f.input_ids for f in train_features], dtype=torch.long)
all_input_mask = torch.tensor([f.input_mask for f in train_features], dtype=torch.long)
all_segment_ids = torch.tensor([f.segment_ids for f in train_features], dtype=torch.long)
all_label_ids = torch.tensor([f.label_id for f in train_features], dtype=torch.long)
all_valid_ids = torch.tensor([f.valid_ids for f in train_features], dtype=torch.long)
all_lmask_ids = torch.tensor([f.label_mask for f in train_features], dtype=torch.long)
train_data = TensorDataset(all_input_ids, all_input_mask, all_segment_ids, all_label_ids,all_valid_ids,all_lmask_ids)
if local_rank == -1:
train_sampler = RandomSampler(train_data)
else:
train_sampler = DistributedSampler(train_data)
train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=train_batch_size)
model.train()
for _ in trange(int(num_train_epochs), desc="Epoch"):
tr_loss = 0
nb_tr_examples, nb_tr_steps = 0, 0
for step, batch in enumerate(tqdm(train_dataloader, desc="Iteration")):
batch = tuple(t.to(device) for t in batch)
input_ids, input_mask, segment_ids, label_ids, valid_ids,l_mask = batch
loss = model(input_ids, segment_ids, input_mask, label_ids,valid_ids,l_mask)
del loss
if n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu.
if gradient_accumulation_steps > 1:
loss = loss / gradient_accumulation_steps
if fp16:
optimizer.backward(loss)
else:
loss.backward()
tr_loss += loss.item()
nb_tr_examples += input_ids.size(0)
nb_tr_steps += 1
if (step + 1) % gradient_accumulation_steps == 0:
if fp16:
# modify learning rate with special warm up BERT uses
# if args.fp16 is False, BertAdam is used that handles this automatically
lr_this_step = learning_rate * warmup_linear(global_step/num_train_optimization_steps, warmup_proportion)
for param_group in optimizer.param_groups:
param_group['lr'] = lr_this_step
optimizer.step()
optimizer.zero_grad()
global_step += 1
main('','',-1,True,True,8,1,42,True,True,'jpt','ner','data/',True,'bert-base-cased',5,'cache_dir',5e-5,0.4,0,128)
| This worked for me:
import os, sys, shutil
import time
import gc
from contextlib import contextmanager
from pathlib import Path
import random
import numpy as np, pandas as pd
from tqdm import tqdm, tqdm_notebook
@contextmanager
def timer(name):
t0 = time.time()
yield
print(f'[{name}] done in {time.time() - t0:.0f} s')
USE_APEX = True
if USE_APEX:
with timer('install Nvidia apex'):
# Installing Nvidia Apex
os.system('git clone https://github.com/NVIDIA/apex; cd apex; pip install -v --no-cache-dir' +
' --global-option="--cpp_ext" --global-option="--cuda_ext" ./')
os.system('rm -rf apex/.git') # too many files, Kaggle fails
from apex import amp
| https://stackoverflow.com/questions/56850711/ |
Multivariate input LSTM in pytorch | I would like to implement LSTM for multivariate input in Pytorch.
Following this article https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/ which uses keras, the input data are in shape of (number of samples, number of timesteps, number of parallel features)
in_seq1 = array([10, 20, 30, 40, 50, 60, 70, 80, 90])
in_seq2 = array([15, 25, 35, 45, 55, 65, 75, 85, 95])
out_seq = array([in_seq1[i]+in_seq2[i] for i in range(len(in_seq1))])
. . .
Input Output
[[10 15]
[20 25]
[30 35]] 65
[[20 25]
[30 35]
[40 45]] 85
[[30 35]
[40 45]
[50 55]] 105
[[40 45]
[50 55]
[60 65]] 125
[[50 55]
[60 65]
[70 75]] 145
[[60 65]
[70 75]
[80 85]] 165
[[70 75]
[80 85]
[90 95]] 185
n_timesteps = 3
n_features = 2
In keras it seems to be easy:
model.add(LSTM(50, activation='relu', input_shape=(n_timesteps, n_features)))
Can it be done in other way, than creating n_features of LSTMs as first layer and feed each separately (imagine as multiple streams of sequences) and then flatten their output to linear layer?
I'm not 100% sure but by nature of LSTM the input cannot be flattened and passed as 1D array, because each sequence "plays by different rules" which the LSTM is supposed to learn.
So how does such implementation with keras equal to PyTorch
input of shape (seq_len, batch, input_size)(source https://pytorch.org/docs/stable/nn.html#lstm)
Edit:
Can it be done in other way, than creating n_features of LSTMs as first layer and feed each separately (imagine as multiple streams of sequences) and then flatten their output to linear layer?
According to PyTorch docs the input_size parameter actually means number of features (if it means number of parallel sequences)
| I hope that problematic parts are commented to make sense:
Data preparation
import random
import numpy as np
import torch
# multivariate data preparation
from numpy import array
from numpy import hstack
# split a multivariate sequence into samples
def split_sequences(sequences, n_steps):
X, y = list(), list()
for i in range(len(sequences)):
# find the end of this pattern
end_ix = i + n_steps
# check if we are beyond the dataset
if end_ix > len(sequences):
break
# gather input and output parts of the pattern
seq_x, seq_y = sequences[i:end_ix, :-1], sequences[end_ix-1, -1]
X.append(seq_x)
y.append(seq_y)
return array(X), array(y)
# define input sequence
in_seq1 = array([x for x in range(0,100,10)])
in_seq2 = array([x for x in range(5,105,10)])
out_seq = array([in_seq1[i]+in_seq2[i] for i in range(len(in_seq1))])
# convert to [rows, columns] structure
in_seq1 = in_seq1.reshape((len(in_seq1), 1))
in_seq2 = in_seq2.reshape((len(in_seq2), 1))
out_seq = out_seq.reshape((len(out_seq), 1))
# horizontally stack columns
dataset = hstack((in_seq1, in_seq2, out_seq))
Multivariate LSTM Network
class MV_LSTM(torch.nn.Module):
def __init__(self,n_features,seq_length):
super(MV_LSTM, self).__init__()
self.n_features = n_features
self.seq_len = seq_length
self.n_hidden = 20 # number of hidden states
self.n_layers = 1 # number of LSTM layers (stacked)
self.l_lstm = torch.nn.LSTM(input_size = n_features,
hidden_size = self.n_hidden,
num_layers = self.n_layers,
batch_first = True)
# according to pytorch docs LSTM output is
# (batch_size,seq_len, num_directions * hidden_size)
# when considering batch_first = True
self.l_linear = torch.nn.Linear(self.n_hidden*self.seq_len, 1)
def init_hidden(self, batch_size):
# even with batch_first = True this remains same as docs
hidden_state = torch.zeros(self.n_layers,batch_size,self.n_hidden)
cell_state = torch.zeros(self.n_layers,batch_size,self.n_hidden)
self.hidden = (hidden_state, cell_state)
def forward(self, x):
batch_size, seq_len, _ = x.size()
lstm_out, self.hidden = self.l_lstm(x,self.hidden)
# lstm_out(with batch_first = True) is
# (batch_size,seq_len,num_directions * hidden_size)
# for following linear layer we want to keep batch_size dimension and merge rest
# .contiguous() -> solves tensor compatibility error
x = lstm_out.contiguous().view(batch_size,-1)
return self.l_linear(x)
Initialization
n_features = 2 # this is number of parallel inputs
n_timesteps = 3 # this is number of timesteps
# convert dataset into input/output
X, y = split_sequences(dataset, n_timesteps)
print(X.shape, y.shape)
# create NN
mv_net = MV_LSTM(n_features,n_timesteps)
criterion = torch.nn.MSELoss() # reduction='sum' created huge loss value
optimizer = torch.optim.Adam(mv_net.parameters(), lr=1e-1)
train_episodes = 500
batch_size = 16
Training
mv_net.train()
for t in range(train_episodes):
for b in range(0,len(X),batch_size):
inpt = X[b:b+batch_size,:,:]
target = y[b:b+batch_size]
x_batch = torch.tensor(inpt,dtype=torch.float32)
y_batch = torch.tensor(target,dtype=torch.float32)
mv_net.init_hidden(x_batch.size(0))
# lstm_out, _ = mv_net.l_lstm(x_batch,nnet.hidden)
# lstm_out.contiguous().view(x_batch.size(0),-1)
output = mv_net(x_batch)
loss = criterion(output.view(-1), y_batch)
loss.backward()
optimizer.step()
optimizer.zero_grad()
print('step : ' , t , 'loss : ' , loss.item())
Results
step : 499 loss : 0.0010267728939652443 # probably overfitted due to 500 training episodes
| https://stackoverflow.com/questions/56858924/ |
Does batch normalisation work with a small batch size? | I'm using batch normalization with a batch size of size 10 for face detection, I wanted to know if it is better to remove the batch norm layers or keep them.
And if it is better to remove them what can I use instead?
| Yes, it works for the smaller size, it will work even with the smallest possible size you set.
The trick is the bach size also adds to the regularization effect, not only the batch norm.
I will show you few pics:
We are on the same scale tracking the bach loss. The left-hand side is a module without the batch norm layer (black), the right-hand side is with the batch norm layer.
Note how the regularization effect is evident even for the bs=10.
When we set the bs=64 the batch loss regularization is super evident. Note the y scale is always [0, 4].
My examination was purely on nn.BatchNorm1d(10, affine=False) without learnable parameters gamma and beta i.e. w and b.
This is why when you have low batch size, it has sense to use the BatchNorm layer.
| https://stackoverflow.com/questions/56859748/ |
ModuleNotFoundError: No module named 'tools.nnwrap' | I tried to install torch using:
pip install torch
Installation started, but after a few seconds I got the error:
from tools.nnwrap import generate_wrappers as generate_nn_wrappers
ModuleNotFoundError: No module named 'tools.nnwrap'
OS: Windows
| Anyone who is looking for the solution refer below:
It seems command to install torch not is working as expected, instead, you can try to install PyTorch using below command.
It's working and solved my above-mentioned issue.
Run below command(for below-specified OS, package-manager, Language):
# for OS: Windows, package-manager: pip, Language: python3.6 (below command is valid for only mentioned python 3.6)
pip3 install https://download.pytorch.org/whl/cu90/torch-1.1.0-cp36-cp36m-win_amd64.whl
pip3 install https://download.pytorch.org/whl/cu90/torchvision-0.3.0-cp36-cp36m-win_amd64.whl
For another version/type of the software (OS, package, Language) installed, the command must be generated from the below-mentioned link.
https://pytorch.org/get-started/locally/
Also, look for the Python version in your IDE(If you are using PyCharm) from the terminal using the command: python. If it returns 32bit this could happen, instead install Python 64-bit.
| https://stackoverflow.com/questions/56859803/ |
Image data cannot be converted to float | I have a code for predicting dog breed after training on CNN model, I get the class index from the below function. I want to display an random image from the class idx folder obtained from the function.
class_name = [item for item in loaders['train'].dataset.classes]
def predict_dog_breed(img,model,class_names):
image = Image.open(img).convert('RGB')
transform = transforms.Compose([
transforms. RandomResizedCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485,0.456,0.406],
std=[0.229, 0.224, 0.225])])
image = transform(image)
test_image = image.unsqueeze(0)
net.eval()
output = net(test_image)
idx = torch.argmax(output)
a = random.choice(os.listdir("./dogImages/train/{}/".format (class_name[idx])))
imshow(a)
return class_name[idx]
When I tried to display the random image, I am getting the below error:
TypeError Traceback (most recent call last) in 1 for img_file in os.listdir('./images'): 2 image = os.path.join('./images', img_file) ----> 3 dog_or_human(image)
in dog_or_human(img) 5 plt.show() 6 if dog_detector(img) == True: ----> 7 predict_dog = predict_dog_breed(img, net, class_name) 8 print("Dog Detected!The breed is {}".format(predict_dog)) 9 elif face_detector(img) > 0:
in predict_dog_breed(img, model, class_name) 18 a = random.choice(os.listdir("./dogImages/train/{}/".format(class_name[idx]))) 19 print(a) ---> 20 imshow(a) 21 #subdir = ''.join(["/dogImages/train/", class_name[idx]]) 22 #print(file)
~/Library/Python/3.7/lib/python/site-packages/matplotlib/pyplot.py in imshow(X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, data, **kwargs) 2697 filternorm=filternorm, filterrad=filterrad, imlim=imlim, 2698 resample=resample, url=url, **({"data": data} if data is not -> 2699 None else {}), **kwargs) 2700 sci(__ret) 2701 return __ret
~/Library/Python/3.7/lib/python/site-packages/matplotlib/init.py in inner(ax, data, *args, **kwargs) 1808 "the Matplotlib list!)" % (label_namer, func.name), 1809 RuntimeWarning, stacklevel=2) -> 1810 return func(ax, *args, **kwargs) 1811 1812 inner.doc = _add_data_doc(inner.doc,
~/Library/Python/3.7/lib/python/site-packages/matplotlib/axes/_axes.py in imshow(self, X, cmap, norm, aspect, interpolation, alpha, vmin, vmax, origin, extent, shape, filternorm, filterrad, imlim, resample, url, **kwargs) 5492 resample=resample, **kwargs) 5493 -> 5494 im.set_data(X) 5495 im.set_alpha(alpha) 5496 if im.get_clip_path() is None:
~/Library/Python/3.7/lib/python/site-packages/matplotlib/image.py in set_data(self, A) 632 if (self._A.dtype != np.uint8 and 633 not np.can_cast(self._A.dtype, float, "same_kind")): --> 634 raise TypeError("Image data cannot be converted to float") 635 636 if not (self._A.ndim == 2
TypeError: Image data cannot be converted to float
Any help on this would be appreciated!
| So, I tried to reproduced the error in your code here and was successful in doing that. You are getting error because of these lines in your code:
a = random.choice(os.listdir("./dogImages/train/{}/".format(class_name[idx])))
imshow(a)
random.choice(os.listdir("./dogImages/train/{}/".format(class_name[idx]))) basically returns an image filename, which is a string. You are not reading the image, just passing the filename to imshow function, which is incorrect. Check below figures for clarification.
Code with error:
Code without error:
Hence, change your predict_do_breed function to following:
def predict_dog_breed(img,model,class_name):
image = Image.open(img).convert('RGB')
transform = transforms.Compose([transforms.RandomResizedCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])])
image = transform(image)
test_image = image.unsqueeze(0)
net.eval()
output = net(test_image)
idx = torch.argmax(output)
a = random.choice(os.listdir("./dogImages/train/{}/".format(class_name[idx])))
print(a)
img = cv2.imread("./dogImages/train/{}/".format(class_name[idx])+a)
imshow(img)
return class_name[idx]
In the above code, cv2.imread function has been used to read the image filename, outputted by random.choice(os.listdir("./dogImages/train/{}/".format(class_name[idx]))).
| https://stackoverflow.com/questions/56862204/ |
PyTorch batch Size suddenly reduced after n epochs | I have a pytorch nn model running on win 10 cpu.
batch size is 42
After 67 iterations, a strange thing happens: batch size is suddenly reduced to 28, and I get
RuntimeError: Expected hidden[0] size (1, 28, 256), got (1, 42, 256)
| Is it possible the number of training examples in the dataset is not divisible by 42? Could it be that the reminder is 28?
If your model cannot handle online change of batch size, you should consider setting drop_last=True in your torch.utils.data.DataLoader, thus only full batches will be processed during training.
| https://stackoverflow.com/questions/56864159/ |
How to fix "“TypeError: img should be PIL Image. Got ”? | I am a beginner and I am learning to code an image classifier. My goal is to create a predict function.
Any suggestion to fix it?
In this project, I want to use the predict function to recognize different flower species. So I could check their labels later.
Attempt to fix: I have already used the unsqueeze_(0) method and changing from numpy to torch method . I usually get the same error message shown below:
TypeError: img should be PIL
Code:
# Imports here
import pandas as pd
import numpy as np
import torch
from torch import nn
from torchvision import datasets, transforms, models
import torchvision.models as models
import torch.nn.functional as F
import torchvision.transforms.functional as F
from torch import optim
import json
from collections import OrderedDict
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
from PIL import Image
def process_image(image):
#Scales, crops, and normalizes a PIL image for a PyTorch model,
#returns an Numpy array
# Process a PIL image for use in a PyTorch model
process = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
])
image = process(image)
return image
# Predict
#Predict the class (or classes) of an image using a trained deep learning model.
def predict(image, model, topk=5):
img = process_image(image)
img = img.unsqueeze(0)
output = model.forward(img)
probs, labels = torch.topk(output, topk)
probs = probs.exp()
# Reverse the dict
idx_to_class = {val: key for key, val in model.class_to_idx.items()}
# Get the correct indices
top_classes = [idx_to_class[each] for each in classes]
return labels, probs
#Passing
probs, classes = predict(image, model)
print(probs)
print(classes)
Error:
TypeError Traceback (most recent call last)
<ipython-input-92-b49fdcab5791> in <module>()
----> 1 probs, classes = predict(image, model)
2 print(probs)
3 print(classes)
<ipython-input-91-05809355bfe0> in predict(image, model, topk)
2 ‘’' Predict the class (or classes) of an image using a trained deep learning model.
3 ‘’'
----> 4 img = process_image(image)
5 img = img.unsqueeze(0)
6
<ipython-input-20-02663a696e34> in process_image(image)
11 std=[0.229, 0.224, 0.225])
12 ])
---> 13 image = process(image)
14 return image
/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/transforms.py in __call__(self, img)
47 def __call__(self, img):
48 for t in self.transforms:
---> 49 img = t(img)
50 return img
51
/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/transforms.py in __call__(self, img)
173 PIL Image: Rescaled image.
174 “”"
--> 175 return F.resize(img, self.size, self.interpolation)
176
177 def __repr__(self):
/opt/conda/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/transforms/functional.py in resize(img, size, interpolation)
187 “”"
188 if not _is_pil_image(img):
--> 189 raise TypeError(‘img should be PIL Image. Got {}’.format(type(img)))
190 if not (isinstance(size, int) or (isinstance(size, collections.Iterable) and len(size) == 2)):
191 raise TypeError(‘Got inappropriate size arg: {}’.format(size))
TypeError: img should be PIL Image. Got <class ‘str’>
All I want is to get these similar result. Thank you!
predict(image,model)
print(probs)
print(classes)
tensor([[ 0.5607, 0.3446, 0.0552, 0.0227, 0.0054]], device='cuda:0')
tensor([[ 8, 1, 31, 24, 7]], device='cuda:0')
| You are getting the above error because of the below line in predict function:
img = process_image(image)
The input to the process_image function should be Image.open(image), not image which is basically the path to an image(string) and hence the error message TypeError: img should be PIL Image. Got <class ‘str’>.
So, change img = process_image(image) to img = process_image(Image.open(image))
Modified predict function:
def predict(image, model, topk=5):
'''
Predict the class (or classes) of an image using a trained deep learning model.
Here, image is the path to an image file, but input to process_image should be
Image.open(image)
'''
img = process_image(Image.open(image))
img = img.unsqueeze(0)
output = model.forward(img)
probs, labels = torch.topk(output, topk)
probs = probs.exp()
# Reverse the dict
idx_to_class = {val: key for key, val in model.class_to_idx.items()}
# Get the correct indices
top_classes = [idx_to_class[each] for each in classes]
return labels, probs
| https://stackoverflow.com/questions/56875663/ |
Looping over pytorch LSTM | I am training a seq2seq model for machine translation in pytorch. I would like to gather the cell state at every time step, while still having the flexibility of multiple layers and bidirectionality, that you can find in the LSTM module of pytorch, for example.
To this end, I have the following encoder and forward method, where I loop over the LSTM module. The problem is, that the model does not train very well. Right after the loop terminates, you can see the normal way to use the LSTM module and with that, the model trains.
So, is the loop not a valid way to do this?
class encoder(nn.Module):
def __init__(self, input_dim, emb_dim, hid_dim, n_layers, dropout):
super().__init__()
self.input_dim = input_dim
self.emb_dim = emb_dim
self.hid_dim = hid_dim
self.n_layers = n_layers
self.dropout = dropout
self.embedding = nn.Embedding(input_dim, emb_dim)
self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout = dropout)
self.dropout = nn.Dropout(dropout)
def forward(self, src):
#src = [src sent len, batch size]
embedded = self.dropout(self.embedding(src))
#embedded = [src sent len, batch size, emb dim]
hidden_all = []
for i in range(len(embedded[:,1,1])):
outputs, hidden = self.rnn(embedded[i,:,:].unsqueeze(0))
hidden_all.append(hidden)
#outputs, hidden = self.rnn(embedded)
#outputs = [src sent len, batch size, hid dim * n directions]
#hidden = [n layers * n directions, batch size, hid dim]
#cell = [n layers * n directions, batch size, hid dim]
None
#outputs are always from the top hidden layer
return hidden
| Okay, so the fix is very simple, you can just run the first timestep outside, to get a hidden tuple to input in the LSTM module.
| https://stackoverflow.com/questions/56875731/ |
Multiply every row of a matrix with every row of another matrix | In numpy / PyTorch, I have two matrices, e.g. X=[[1,2],[3,4],[5,6]], Y=[[1,1],[2,2]]. I would like to dot product every row of X with every row of Y, and have the results
[[3, 6],[7, 14], [11,22]]
How do I achieve this?, Thanks!
| I think this is what you are looking for:
import numpy as np
x= [[1,2],[3,4],[5,6]]
y= [[1,1],[2,2]]
x = np.asarray(x) #convert list to numpy array
y = np.asarray(y) #convert list to numpy array
product = np.dot(x, y.T)
.T transposes the matrix, which is neccessary in this case for the multiplication (because of the way dot products are defined). print(product) will output:
[[ 3 6]
[ 7 14]
[11 22]]
| https://stackoverflow.com/questions/56896427/ |
Copy a chunk of one tensor into another one in C++ API | I need to copy a row of one tensor (in c++ API) into some part of another tensor, form which the begin and end indexes are available. Within C++ we can use something like:
int myints[] = {10, 20, 30, 40, 50, 60, 70};
std::vector<int> myvector(18);
std::copy(myints, myints + 3, myvector.begin() + 4);
to copy three values from myints into myvector, starting at the fourth index.
I was wondering if there is a similar API in libtorch (i.e., C++)?
| The C++ API provides the Python slice equivalent function
at::Tensor at::Tensor::slice(int64_t dim, int64_t start, int64_t end, int64_t step);
You can thus do something like:
auto myints = torch::Tensor({10, 20, 30, 40, 50, 60, 70});
auto myvector = torch::ones({18});
myvector.slice(0, 3, 7) = myints.slice(0, 0, 3);
in your case using dim=0 first dimension
| https://stackoverflow.com/questions/56908893/ |
Why there's no .train() method in this Pytorch official tutorial? | So, I just learned Pytorch and they say that you must put the NN in train mode by .train() method, then while inferencing .eval() mode. I'm reading this tutorial and there's no .train() at all. Why is that?
https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#sphx-glr-beginner-blitz-cifar10-tutorial-py
| .train() sets the self.training property of the module to True. .eval() sets it to False.
As can be seen in the source for nn.Module, this property is initially set to True. So, unless you have called eval() before you start training, you do not necessarily (as per the current implementation) need to call train(). But the important point is that the module should be in the self.training=True state at the time of training, so it is probably a good practice to do so anyway.
Also, currently, only some modules (such as dropout and batchnorm) change their behavior based on the self.training property. So you don't necessarily have to call .train() and .eval() if you are not using those specific modules, but again, it is probably good practice to do so anyway for future-proofing your code.
| https://stackoverflow.com/questions/56917895/ |
Pytorch - how do I index a 2-D matrix row wise? | I would like to index a 2-D matrix row-wise and re-assign values.
For example, first consider a 1-D vector case where we have three 1-D tensors t1, indexes, t2 with the same shape. We can do this indexing and re-assignment as follows:
indexes = torch.tensor([0, 2, 1, 3])
t1 = torch.tensor([0.0, 0.0, 0.0, 0.0])
t2 = torch.tensor([0.1, 0.2, 0.3, 0.4])
t1[indexes] = t2
Now, say that t1, indexes, t2 are 2-D matrices instead of 1-D vectors and have the same shape (R X C). I would like to do similar indexing as above for every row in these matrices where:
for i in range(R):
t1[i][indexes[i]] = t2[i]
I would like to vectorize this operation instead of using a for loop. How do I do this?
| Similiar to @Anubhav's answer with a slight change in dimension of scatter_, this did the job. Source: PyTorch Discussion
indexes = torch.tensor([[0, 2, 1, 3],
[1, 0, 3, 2]])
t1 = torch.zeros_like(indexes).float()
t2 = torch.tensor([[0.1, 0.2, 0.3, 0.4],
[0.5, 0.6, 0.7, 0.8]])
t1.scatter_(1, indexes, t2)
| https://stackoverflow.com/questions/56920264/ |
Why does the pytorch Docker image not come with torch? | I am trying to build a docker container that will enable me to run my code that requires the python torch module.
I have chosen to start my image from the pytorch/pytorch:latest base image and add a few required modules manually. The build, push, and pull to the remote server were successful (no error messages at least).
Currently my Dockerfile looks like this:
FROM pytorch/pytorch:latest
RUN apt-get update \
&& apt-get install -y \
libgl1-mesa-glx \
libx11-xcb1 \
&& apt-get clean all \
&& rm -r /var/lib/apt/lists/*
RUN /opt/conda/bin/conda install --yes \
astropy \
matplotlib \
pandas \
glob2 \
PIL \
scikit-learn \
scikit-image \
numpy
However, when running my python script within the container, I get ImportError: No module named torch. This strikes me as rather weird, as it leads me to assume that the pytorch base image does not include the torch module...?
I have nevertheless tried to add torch to the list of modules to install in the Dockerfile, but then the initial build will already fail with the error message PackagesNotFoundError: The following packages are not available from current channels: - torch. Following the advice given here did unfortunately not help me.
I'd appreciate any explanation as to why the torch module could not be found within the built container, and of course any help to fix this problem! Thanks!
| First thing, your assumption is false, to verify this you just need to run the container from the base image, as you can check the official Dockerfile or run first the base image that is pytorch/pytorch:latest
and verify does the base image working as you need?
Here is the list of installed modules in the official image and at bottom of the list, you can see the torch.
Here is a simple example from the torch using the base image.
As for your Dockerfile, so the package PIL is breaking the docker build from scratch, but this not visible if PyTorch is the base image.
For some reason, I am failed in the child image to find the torch so installed it using pip install and then its able to work.
Here is the Dockerfile:
FROM pytorch/pytorch:latest
RUN apt-get update \
&& apt-get install -y \
libgl1-mesa-glx \
libx11-xcb1 \
&& apt-get clean all \
&& rm -r /var/lib/apt/lists/*
RUN /opt/conda/bin/conda install --yes \
astropy \
matplotlib \
pandas \
glob2 \
scikit-learn \
scikit-image \
numpy \
torch
Updated
Here is the way to make torch available
FROM pytorch/pytorch:latest
RUN apt-get update \
&& apt-get install -y \
libgl1-mesa-glx \
libx11-xcb1 \
&& apt-get clean all \
&& rm -r /var/lib/apt/lists/*
RUN /opt/conda/bin/conda install --yes \
astropy \
matplotlib \
pandas \
scikit-learn \
scikit-image
RUN pip install torch
| https://stackoverflow.com/questions/56920535/ |
How can torch multiply two 10000*10000 matrices in almost zero time? Why does the speed change so much from 349 ms down to 999 µs? | Here is an excerpt from Jupyter:
In [1]:
import torch, numpy as np, datetime
cuda = torch.device('cuda')
In [2]:
ac = torch.randn(10000, 10000).to(cuda)
bc = torch.randn(10000, 10000).to(cuda)
%time cc = torch.matmul(ac, bc)
print(cc[0, 0], torch.sum(ac[0, :] * bc[:, 0]))
Wall time: 349 ms
tensor(17.0374, device='cuda:0') tensor(17.0376, device='cuda:0')
The time is low but still reasonable (0.35 sec for 1e12 multiplications)
But if we repeat the same:
ac = torch.randn(10000, 10000).to(cuda)
bc = torch.randn(10000, 10000).to(cuda)
%time cc = torch.matmul(ac, bc)
print(cc[0, 0], torch.sum(ac[0, :] * bc[:, 0]))
Wall time: 999 µs
tensor(-78.7172, device='cuda:0') tensor(-78.7173, device='cuda:0')
1e12 multiplications in 1ms?!
Why did the time change from 349ms to 1ms?
Info:
Tested on GeForce RTX 2070;
Can be reproduced on Google Colab.
| There is already a discussion about this on Discuss PyTorch: Measuring GPU tensor operation speed.
I'd like to highlight two comments from that thread:
From @apaszke:
[...] the GPU executes all operations asynchronously, so you need to insert proper barriers for your benchmarks to be correct
From @ngimel:
I believe cublas handles are allocated lazily now, which means that first operation requiring cublas will have an overhead of creating cublas handle, and that includes some internal allocations. So there’s no way to avoid it other than calling some function requiring cublas before the timing loop.
Basically, you have to synchronize() to have a proper measurement:
import torch
x = torch.randn(10000, 10000).to("cuda")
w = torch.randn(10000, 10000).to("cuda")
# ensure that context initialization finish before you start measuring time
torch.cuda.synchronize()
%time y = x.mm(w.t()); torch.cuda.synchronize()
CPU times: user 288 ms, sys: 191 ms, total: 479 ms
Wall time: 492 ms
x = torch.randn(10000, 10000).to("cuda")
w = torch.randn(10000, 10000).to("cuda")
# ensure that context initialization finish before you start measuring time
torch.cuda.synchronize()
%time y = x.mm(w.t()); torch.cuda.synchronize()
CPU times: user 237 ms, sys: 231 ms, total: 468 ms
Wall time: 469 ms
| https://stackoverflow.com/questions/56922099/ |
Reinforcement Learning with Pytorch. [Error: KeyError ] | I am new to reinforcement learning as well as pytorch. I am learning it from Udemy. However, the code I have is the same as it is shown but I am having an error. I guess it is a pytorch error but can't debug it. If anyone helps it is really appreciated.
import gym
import time
import torch
import matplotlib.pyplot as plt
from gym.envs.registration import register
register(id='FrozenLakeNotSlippery-v0',entry_point='gym.envs.toy_text:FrozenLakeEnv',kwargs={'map_name': '4x4', 'is_slippery':False})
env = gym.make('FrozenLakeNotSlippery-v0')
number_of_states = env.observation_space.n
number_of_actions = env.action_space.n
Q = torch.zeros([number_of_states,number_of_actions])
num_episodes = 1000
steps_total = []
gamma = 1
for i in range(num_episodes):
state = env.reset()
step = 0
while True:
step += 1
#action = env.action_space.sample()
random_values = Q[state]+torch.rand(1,number_of_actions)/1000
action = torch.max(random_values,1)[1][0]
new_state, reward, done, info = env.step(action)
Q[state, action] = reward + gamma * torch.max(Q[new_state])
state = new_state
#time.sleep(0.4)
#env.render()
if done:
steps_total.append(step)
print ("Episode Finished after %i steps" %step)
break
print ("Average Num Steps: %2f" %(sum(steps_total)/num_episodes))
plt.plot(steps_total)
plt.show()
The error I am having is the below one
KeyError Traceback (most recent call last)
<ipython-input-11-a6aa419c3767> in <module>
8 random_values = Q[state]+torch.rand(1,number_of_actions)/1000
9 action = torch.max(random_values,1)[1][0]
---> 10 new_state, reward, done, info = env.step(action)
11 Q[state, action] = reward + gamma * torch.max(Q[new_state])
12 state = new_state
c:\users\souradip\appdata\local\programs\python\python36\lib\site-packages\gym\envs\toy_text\discrete.py in step(self, a)
53
54 def step(self, a):
---> 55 transitions = self.P[self.s][a]
56 i = categorical_sample([t[0] for t in transitions], self.np_random)
57 p, s, r, d= transitions[i]
KeyError: tensor(3)
| The below code
action = torch.max(random_values,1)[1][0]
results in a 0-dim tensor, but env.step() expects a python number, which is basically an action from the action space. So, as @a_guest mentioned in the comment, use a.item() to convert a 0-dim tensor to a python number like below:
new_state, reward, done, info = env.step(action.item())
| https://stackoverflow.com/questions/56926882/ |
python - Machine Learning 2D Regression with confidence bands | I have measures of a variable versus time.
I want to obtain a regression with confidence bands so that the plot sounds like this:
Given an arbitrary x, I "predicted" the y and its confidence by evaluating mean and std of N closest measured points. But I feel like this is quite naive.
I was wondering if it is possible to obtain a similar result with Machine Learning, Neural Network, ...
I'm quite familiar with python, sklearn and pytorch so if you please could suggest a solution that implements those tools I would be very thankfull.
| You can achieve something like that with Gaussian Processes. For regression problems, you can use GaussianProcessRegressor from sklearn.
This is an example of how to use it to obtain the plot you are looking for.
| https://stackoverflow.com/questions/56934495/ |
Combination of torch.cat and torchvision.transforms leeds to zero tensor | I want to add some more information to an image in a fourth layer of a tensor which first three layers are based on an image. Afterwards I want to cut a peace out of an image (data augmentation) and have to resize the image to a given size.
For this I created a tensor from a picture and joined it with a tensor with one layer of additional information using torch.cat. (Almost but not all entries of the second tensor have been zeros.)
I sent the result through a transforms.compose (to cut and resize the tensor) But after that the tensor completely consisted out of zeros.
Here I have built a reproducible example.
import torch
from torchvision import transforms
height = 2
width = 4
resize = 2
tensor3 = torch.rand(3,height,width)
tensor1 = torch.zeros(1,height,width)
#tensor1 = torch.rand(1,height,width)
imageToTensor = transforms.ToTensor()
tensorToImage = transforms.ToPILImage()
train_transform = transforms.Compose([
transforms.RandomResizedCrop(resize, scale=(0.9, 1.0)),
transforms.ToTensor(),
])
tensor4 = torch.cat((tensor3,tensor1),0)
image4 = tensorToImage(tensor4)
transformed_image4 = train_transform(image4)
print(tensor4)
print(transformed_image4)
tensor([[[0.6774, 0.5293, 0.4420, 0.2463],
[0.1391, 0.7481, 0.3436, 0.9391]],
[[0.0652, 0.2061, 0.2931, 0.6126],
[0.2618, 0.3506, 0.5095, 0.7351]],
[[0.8555, 0.6320, 0.9461, 0.0928],
[0.2094, 0.3944, 0.0528, 0.7900]],
[[0.0000, 0.0000, 0.0000, 0.0000],
[0.0000, 0.0000, 0.0000, 0.0000]]])
tensor([[[0., 0.],
[0., 0.]],
[[0., 0.],
[0., 0.]],
[[0., 0.],
[0., 0.]],
[[0., 0.],
[0., 0.]]])
If I choose “tensor1 = torch.rand(1,height,width)” I do not have this problem. But if most entries are zero I have.
With scale=(0.5, 1.0) I don't have the problem either.
No some questions:
How may I get the first three layers just resized with non zero entries?
Did I misunderstand something, or is it really weird?
| I created an issue:
https://github.com/pytorch/pytorch/issues/22611
And the answer was that only PIL-Images are supported in Torchvision.
An alternative is the albumentations-library for transformations.
| https://stackoverflow.com/questions/56940524/ |
Subsets and Splits