instruction
stringlengths 13
150
| input
stringlengths 36
29.1k
| output
stringlengths 31
29.5k
| source
stringlengths 45
45
|
---|---|---|---|
PyTorch custom loss function | How should a custom loss function be implemented ? Using below code is causing error :
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import numpy as np
import matplotlib.pyplot as plt
import torch.utils.data as data_utils
import torch.nn as nn
import torch.nn.functional as F
num_epochs = 20
x1 = np.array([0,0])
x2 = np.array([0,1])
x3 = np.array([1,0])
x4 = np.array([1,1])
num_epochs = 200
class cus2(torch.nn.Module):
def __init__(self):
super(cus2,self).__init__()
def forward(self, outputs, labels):
# reshape labels to give a flat vector of length batch_size*seq_len
labels = labels.view(-1)
# mask out 'PAD' tokens
mask = (labels >= 0).float()
# the number of tokens is the sum of elements in mask
num_tokens = int(torch.sum(mask).data[0])
# pick the values corresponding to labels and multiply by mask
outputs = outputs[range(outputs.shape[0]), labels]*mask
# cross entropy loss for all non 'PAD' tokens
return -torch.sum(outputs)/num_tokens
x = torch.tensor([x1,x2,x3,x4]).float()
y = torch.tensor([0,1,1,0]).long()
train = data_utils.TensorDataset(x,y)
train_loader = data_utils.DataLoader(train , batch_size=2 , shuffle=True)
device = 'cpu'
input_size = 2
hidden_size = 100
num_classes = 2
learning_rate = .0001
class NeuralNet(nn.Module) :
def __init__(self, input_size, hidden_size, num_classes) :
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(input_size , hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size , num_classes)
def forward(self, x) :
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
for i in range(0 , 1) :
model = NeuralNet(input_size, hidden_size, num_classes).to(device)
criterion = nn.CrossEntropyLoss()
# criterion = Regress_Loss()
# criterion = cus2()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
total_step = len(train_loader)
for epoch in range(num_epochs) :
for i,(images , labels) in enumerate(train_loader) :
images = images.reshape(-1 , 2).to(device)
labels = labels.to(device)
outputs = model(images)
loss = criterion(outputs , labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# print(loss)
outputs = model(x)
print(outputs.data.max(1)[1])
makes perfect predictions on training data :
tensor([0, 1, 1, 0])
Using a custom loss function from here:
is implemented in above code as cus2
Un-commenting code # criterion = cus2() to use this loss function returns :
tensor([0, 0, 0, 0])
A warning is also returned :
UserWarning: invalid index of a 0-dim tensor. This will be an error in
PyTorch 0.5. Use tensor.item() to convert a 0-dim tensor to a Python
number
I've not implemented the custom loss function correctly ?
| Your loss function is programmatically correct except for below:
# the number of tokens is the sum of elements in mask
num_tokens = int(torch.sum(mask).data[0])
When you do torch.sum it returns a 0-dimensional tensor and hence the warning that it can't be indexed. To fix this do int(torch.sum(mask).item()) as suggested or int(torch.sum(mask)) will work too.
Now, are you trying to emulate the CE loss using the custom loss? If yes, then you are missing the log_softmax
To fix that add outputs = torch.nn.functional.log_softmax(outputs, dim=1) before statement 4. Note that in case of tutorial that you have attached, log_softmax is already done in the forward call. You can do that too.
Also, I noticed that the learning rate is slow and even with CE loss, results are not consistent. Increasing the learning rate to 1e-3 works well for me in case of custom as well as CE loss.
| https://stackoverflow.com/questions/53980031/ |
How to multiply a tensor row-wise by a vector in PyTorch? | When I have a tensor m of shape [12, 10] and a vector s of scalars with shape [12], how can I multiply each row of m with the corresponding scalar in s?
| You need to add a corresponding singleton dimension:
m * s[:, None]
s[:, None] has size of (12, 1) when multiplying a (12, 10) tensor by a (12, 1) tensor pytorch knows to broadcast s along the second singleton dimension and perform the "element-wise" product correctly.
| https://stackoverflow.com/questions/53987906/ |
How to store switch locations during max-pooling layer | I am implementing the article https://arxiv.org/abs/1311.2901 by Zeiler and Fergus on visualizing and understanding convolutional Networks. To be able reflect hidden layers back to the image space we need deconvolution kernels, rectified linear functions and switch locations. I couldn't find how to store switch locations during max-pooling. I would be glad if you can explain how to do it in pytorch or tensorflow. Thanks in advance.
| The pytorch max pool operation takes an optional argument return_indices which is set to False by default. If you set that to True, the output will be the max pooled tensor as well the indices of the maximum items.
| https://stackoverflow.com/questions/53989912/ |
what is the first initialized weight in pytorch convolutional layer | I do self-studying in Udacity PyTorch
Regarding to the last paragraph
Learning
In the code you've been working with, you've been setting the values of filter weights explicitly, but neural networks will actually learn the best filter weights as they train on a set of image data. You'll learn all about this type of neural network later in this section, but know that high-pass and low-pass filters are what define the behavior of a network like this, and you know how to code those from scratch!
In practice, you'll also find that many neural networks learn to detect the edges of images because the edges of object contain valuable information about the shape of an object.
I have studied all through the last 44th sections. But I couldn't be able to answer the following questions
What is the initialized weight when I do torch.nn.Conv2d? And how to define it myself?
How does PyTorch update weights in the convolutional layer?
| When you declared nn.Conv2d the weights are initialized via this code.
In particular, if you give bias it uses initialization as proposed by Kaiming et.al. It initializes as uniform distribution between (-bound, bound) where bound=\sqrt{6/((1+a^2)fan_in)} (See here).
You can initialize weight manually too. This has been answered elsewhere (See here) and I won't repeat it.
When you call optimizer.step and optimizer has parameters of convolutional filter registered they are updated.
| https://stackoverflow.com/questions/53990652/ |
How can i process multi loss in pytorch? |
Such as this, I want to using some auxiliary loss to promoting my model performance.
Which type code can implement it in pytorch?
#one
loss1.backward()
loss2.backward()
loss3.backward()
optimizer.step()
#two
loss1.backward()
optimizer.step()
loss2.backward()
optimizer.step()
loss3.backward()
optimizer.step()
#three
loss = loss1+loss2+loss3
loss.backward()
optimizer.step()
Thanks for your answer!
| First and 3rd attempt are exactly the same and correct, while 2nd approach is completely wrong.
In Pytorch, low layer gradients are Not "overwritten" by subsequent backward() calls, rather they are accumulated, or summed. This makes first and 3rd approach identical, though 1st approach might be preferable if you have low-memory GPU/RAM (a batch size of 1024 with one backward() + step() call is same as having 8 batches of size 128 and 8 backward() calls, with one step() call in the end).
To illustrate the idea, here is a simple example. We want to get our tensor x close to 40,50 and 60 simultaneously:
x = torch.tensor([1.0],requires_grad=True)
loss1 = criterion(40,x)
loss2 = criterion(50,x)
loss3 = criterion(60,x)
Now the first approach: (we use tensor.grad to get current gradient for our tensor x)
loss1.backward()
loss2.backward()
loss3.backward()
print(x.grad)
This outputs : tensor([-294.]) (EDIT: put retain_graph=True in first two backward calls for more complicated computational graphs)
The third approach:
loss = loss1+loss2+loss3
loss.backward()
print(x.grad)
Again the output is : tensor([-294.])
2nd approach is different because we don't call opt.zero_grad after calling step() method. This means in all 3 step calls gradients of first backward call is used. For example, if 3 losses provide gradients 5,1,4 for same weight, instead of having 10 (=5+1+4), now your weight will have 5*3+1*2+4*1=21 as gradient.
For further reading : Link 1,Link 2
| https://stackoverflow.com/questions/53994625/ |
axes don't match array in pytorch | I am new to pytorch and i am stuck in this for more than a week now.
i am trying to use AlexNet to make a 'gta san Andreas' self driving car and i am having alot of problems with preparing the data.
for now i am getting this error.
Traceback (most recent call last):
File "training_script.py", line 19, in <module>
transformed_data = transform(all_data)
File "C:\Users\Mukhtar\Anaconda3\lib\site-packages\torchvision\transforms\transforms.py", line 49, in __call__
img = t(img)
File "C:\Users\Mukhtar\Anaconda3\lib\site-packages\torchvision\transforms\transforms.py", line 76, in __call__
return F.to_tensor(pic)
File "C:\Users\Mukhtar\Anaconda3\lib\site-packages\torchvision\transforms\functional.py", line 48, in to_tensor
img = torch.from_numpy(pic.transpose((2, 0, 1)))
ValueError: axes don't match array
this is the training script
from AlexNetPytorch import*
import torchvision
import torchvision.transforms as transforms
import torch.optim as optim
import torch.utils.data
import numpy as np
import torch
AlexNet = AlexNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(AlexNet.parameters(), lr=0.001, momentum=0.9)
all_data = np.load('training_data.npy')
transform = transforms.Compose([
# you can add other transformations in this list
transforms.ToTensor()
])
transformed_data = transform(all_data)
# # data_set = torchvision.datasets.ImageFolder('training_data.npy' ,transform = transforms.ToTensor() )
data_loader = torch.utils.data.DataLoader(training_data, batch_size=4,shuffle=True, num_workers=2)
# training_data = all_data[:-500]lk
# testing_data = all_data[-500:]
if __name__ == '__main__':
for epoch in range(8):
runing_loss = 0.0
for i,data in enumerate(data_loader , 0):
inputs= data[0]
inputs = torch.FloatTensor(inputs)
labels= data[1]
labels = torch.FloatTensor(labels)
optimizer.zero_grad()
outputs = AlexNet(inputs)
loss = criterion(outputs , labels)
loss.backward()
optimizer.step()
runing_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')
and this is how i am preparing the data
import cv2
from PIL import ImageGrab
import numpy as np
import time
from directKeys import PressKey,W,A,S,D
from getKeys import key_check
import os
def keys_to_output(keys):
output = [0,0,0]
if 'A' in keys:
output[0] = 1
elif 'D' in keys:
output[2] = 1
else:
output[1] = 1
return output
file_name = "training_data.npy"
if os.path.isfile(file_name):
print("file exists , loading previous data!")
training_data = list(np.load(file_name))
else:
print("file does not exist , starting fresh")
training_data = []
last_time = time.time()
while True:
kernel = np.ones((15 , 15) , np.float32)/225
get_screen = ImageGrab.grab(bbox=(10,10,1280,720))
screen_shot = np.array(get_screen)
hsv = cv2.cvtColor(screen_shot , cv2.COLOR_BGR2HSV)
lower_color = np.array([90 , 0 , 70])
upper_color = np.array([100 , 100 , 100])
output = cv2.inRange(hsv , lower_color , upper_color)
kernel = np.ones((1,20), np.uint8) # note this is a horizontal kernel
dilation = cv2.dilate(output, kernel, iterations=1)
output = cv2.erode(dilation, kernel, iterations=1)
# output = cv2.Canny(output , threshold1 = 50 , threshold2 = 300)
# output = cv2.GaussianBlur(output , (15,15) , 0)
resized = cv2.resize(output , (640 , 480))
print('loop took {} seconds'.format(time.time()-last_time))
last_time = time.time()
cv2.imshow('manipulated' , resized)
screen_output = cv2.resize(output , (32 ,32))
keys = key_check()
Keys_output = keys_to_output(keys)
training_data.append([screen_output,Keys_output])
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
if len(training_data) % 500 == 0:
print(len(training_data))
np.save(file_name,training_data)
I tried a lot of solutions but none of them work, but I feel like I am missing something.
i am way over my head so please help
| You are applying the transformation to a list of numpy arrays instead of to a single PIL image (which is usually what ToTensor() transforms expects).
| https://stackoverflow.com/questions/53995708/ |
How does the "number of workers" parameter in PyTorch dataloader actually work? |
If num_workers is 2, Does that mean that it will put 2 batches in the RAM and send 1 of them to the GPU or Does it put 3 batches in the RAM then sends 1 of them to the GPU?
What does actually happen when the number of workers is higher than the number of CPU cores? I tried it and it worked fine but How does it work? (I thought that the maximum number of workers I can choose is the number of cores).
If I set num_workers to 3 and during the training there were no batches in the memory for the GPU, Does the main process waits for its workers to read the batches or Does it read a single batch (without waiting for the workers)?
|
When num_workers>0, only these workers will retrieve data, main process won't. So when num_workers=2 you have at most 2 workers simultaneously putting data into RAM, not 3.
Well our CPU can usually run like 100 processes without trouble and these worker processes aren't special in anyway, so having more workers than cpu cores is ok. But is it efficient? it depends on how busy your cpu cores are for other tasks, speed of cpu, speed of your hard disk etc. In short, its complicated, so setting workers to number of cores is a good rule of thumb, nothing more.
Nope. Remember DataLoader doesn't just randomly return from what's available in RAM right now, it uses batch_sampler to decide which batch to return next. Each batch is assigned to a worker, and main process will wait until the desired batch is retrieved by assigned worker.
Lastly to clarify, it isn't DataLoader's job to send anything directly to GPU, you explicitly call cuda() for that.
EDIT: Don't call cuda() inside Dataset's __getitem__() method, please look at @psarka's comment for the reasoning
| https://stackoverflow.com/questions/53998282/ |
How to use AlexNet with one channel | I am new to pytorch and had a problem with channels in AlexNet.
I am using it for a ‘gta san andreas self driving car’ project, I collected the dataset from a black and white image that has one channel and trying to train AlexNet using the script:
from AlexNetPytorch import*
import torchvision
import torchvision.transforms as transforms
import torch.optim as optim
import torch.utils.data
import numpy as np
import torch
from IPython.core.debugger import set_trace
AlexNet = AlexNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(AlexNet.parameters(), lr=0.001, momentum=0.9)
all_data = np.load('training_data.npy')
inputs= all_data[:,0]
labels= all_data[:,1]
inputs_tensors = torch.stack([torch.Tensor(i) for i in inputs])
labels_tensors = torch.stack([torch.Tensor(i) for i in labels])
data_set = torch.utils.data.TensorDataset(inputs_tensors,labels_tensors)
data_loader = torch.utils.data.DataLoader(data_set, batch_size=3,shuffle=True, num_workers=2)
if __name__ == '__main__':
for epoch in range(8):
runing_loss = 0.0
for i,data in enumerate(data_loader , 0):
inputs= data[0]
inputs = torch.FloatTensor(inputs)
labels= data[1]
labels = torch.FloatTensor(labels)
optimizer.zero_grad()
# set_trace()
inputs = torch.unsqueeze(inputs, 1)
outputs = AlexNet(inputs)
loss = criterion(outputs , labels)
loss.backward()
optimizer.step()
runing_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')
I am using AlexNet from the link:
https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py
But changed line 18 from :
nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2)
To :
nn.Conv2d(1, 64, kernel_size=11, stride=4, padding=2)
Because I am using only one channel in training images, but I get this error:
File "training_script.py", line 44, in <module>
outputs = AlexNet(inputs)
File "C:\Users\Mukhtar\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "C:\Users\Mukhtar\Documents\AI_projects\gta\AlexNetPytorch.py", line 34, in forward
x = self.features(x)
File "C:\Users\Mukhtar\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "C:\Users\Mukhtar\Anaconda3\lib\site-packages\torch\nn\modules\container.py", line 91, in forward
input = module(input)
File "C:\Users\Mukhtar\Anaconda3\lib\site-packages\torch\nn\modules\module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "C:\Users\Mukhtar\Anaconda3\lib\site-packages\torch\nn\modules\pooling.py", line 142, in forward
self.return_indices)
File "C:\Users\Mukhtar\Anaconda3\lib\site-packages\torch\nn\functional.py", line 396, in max_pool2d
ret = torch._C._nn.max_pool2d_with_indices(input, kernel_size, stride, padding, dilation, ceil_mode)
RuntimeError: Given input size: (256x1x1). Calculated output size: (256x0x0). Output size is too small at c:\programdata\miniconda3\conda-bld\pytorch-cpu_1532499824793\work\aten\src\thnn\generic/SpatialDilatedMaxPooling.c:67
I don't know what is wrong, is it wrong to change the channel size like this, and if it is wrong can you please lead me to a neural network that work with one channel , as I said I am a newbie in pytorch and I don't want to write the nn myself.
| Your error is not related to using gray-scale images instead of RGB. Your error is about the spatial dimensions of the input: while "forwarding" an input image through the net, its size (in feature space) became zero - this is the error you see. You can use this nice guide to see what happens to the output size of each layer (conv/pooling) as a function of kernel size, stride and padding.
Alexnet expects its input images to be 224 by 224 pixels - make sure your inputs are of the same size.
Other things you overlooked:
You are using Alexnet architecture, but you are initializing it to random weights instead of using pretrained weights (trained on imagenet). To get a trained copy of alexnet you'll need to instantiate the net like this
AlexNet = alexnet(pretrained=True)
Once you decide to use pretrained net, you cannot change its first layer from 3 input channels to three (the trained weight simply won't fit). The easiest fix is to make your input images "colorful" by simply repeating the single channel three times. See repeat() for more info.
| https://stackoverflow.com/questions/53999587/ |
How do I implement a PyTorch Dataset for use with AWS SageMaker? | I have implemented a PyTorch Dataset that works locally (on my own desktop), but when executed on AWS SageMaker, it breaks. My Dataset implementation is as follows.
class ImageDataset(Dataset):
def __init__(self, path='./images', transform=None):
self.path = path
self.files = [join(path, f) for f in listdir(path) if isfile(join(path, f)) and f.endswith('.jpg')]
self.transform = transform
if transform is None:
self.transform = transforms.Compose([
transforms.Resize((128, 128)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
def __len__(self):
return len(files)
def __getitem__(self, idx):
img_name = self.files[idx]
# we may infer the label from the filename
dash_idx = img_name.rfind('-')
dot_idx = img_name.rfind('.')
label = int(img_name[dash_idx + 1:dot_idx])
image = Image.open(img_name)
if self.transform:
image = self.transform(image)
return image, label
I am following this example and this one too, and I run the estimator as follows.
inputs = {
'train': 'file://images',
'eval': 'file://images'
}
estimator = PyTorch(entry_point='pytorch-train.py',
role=role,
framework_version='1.0.0',
train_instance_count=1,
train_instance_type=instance_type)
estimator.fit(inputs)
I get the following error.
FileNotFoundError: [Errno 2] No such file or directory: './images'
In the example that I am following, they upload the CFAIR dataset (which is downloaded locally) to S3.
inputs = sagemaker_session.upload_data(path='data', bucket=bucket, key_prefix='data/cifar10')
If I take a peek at inputs, it is just a string literal s3://sagemaker-us-east-3-184838577132/data/cifar10. The code to create a Dataset and a DataLoader is shown here, which does not help unless I track down the source and step through the logic.
I think what needs to happen inside my ImageDataset is to supply the S3 path and use the AWS CLI or something to query the files and acquire their content. I do not think the AWS CLI is the right approach as this relies on the console and I will have to execute some sub-process commands and then parse through.
There must be a recipe or something to create a custom Dataset backed by S3 files, right?
| I was able to create a PyTorch Dataset backed by S3 data using boto3. Here's the snippet if anyone is interested.
class ImageDataset(Dataset):
def __init__(self, path='./images', transform=None):
self.path = path
self.s3 = boto3.resource('s3')
self.bucket = self.s3.Bucket(path)
self.files = [obj.key for obj in self.bucket.objects.all()]
self.transform = transform
if transform is None:
self.transform = transforms.Compose([
transforms.Resize((128, 128)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
def __len__(self):
return len(files)
def __getitem__(self, idx):
img_name = self.files[idx]
# we may infer the label from the filename
dash_idx = img_name.rfind('-')
dot_idx = img_name.rfind('.')
label = int(img_name[dash_idx + 1:dot_idx])
# we need to download the file from S3 to a temporary file locally
# we need to create the local file name
obj = self.bucket.Object(img_name)
tmp = tempfile.NamedTemporaryFile()
tmp_name = '{}.jpg'.format(tmp.name)
# now we can actually download from S3 to a local place
with open(tmp_name, 'wb') as f:
obj.download_fileobj(f)
f.flush()
f.close()
image = Image.open(tmp_name)
if self.transform:
image = self.transform(image)
return image, label
| https://stackoverflow.com/questions/54003052/ |
How to set a variable as an attribute? | I'm getting error when trying to set variable as an atribute.
parser = argparse.ArgumentParser()
parser.add_argument('--arch', action='store',
dest='arch', default='alexnet',
help='Store a simple value')
args = parser.parse_args()
model = models.args.arch(pretrained=True)
I know models.args.arch prodocues an error but how syntax should looke like to set a variable as an attribute? I could do it with if statements but it would be lot's of code and I guess it's possible in 1 line.
| You want to access the internal dict to update:
model = models.__dict__[args.arch](pretrained=True)
or using getattr:
getattr(models, args.arch)(pretrained=True)
| https://stackoverflow.com/questions/54012820/ |
pytorch dataloader stucked if using opencv resize method | I can run all the cells of the tutorial notebook of Pytorch about dataloading (pytorch tutorial).
But when I use OpenCV in place of Skimage to resize the image, the dataloader gets stuck, i.e nothing happens.
In the Rescale class:
class Rescale(object):
.....
def __call__(self, sample):
....
#img = transform.resize(image, (new_h, new_w))
img = cv2.resize(image, (new_h, new_w))
.....
The dataloader and the for loop are defined with:
dataloader = DataLoader(transformed_dataset, batch_size=4,
shuffle=True, num_workers=4)
for i_batch, sample_batched in enumerate(dataloader):
print(i_batch, sample_batched['image'].size(),
sample_batched['landmarks'].size())
I can get the iterator to print something if num_workers=0. It looks like opencv does not play well with the Multiprocessing of pytorch.
I would really prefer to use same package to transform the images at train time and test time (and I am already using OpenCV for the image rescale at test time).
Any suggestions would be greatly appreciated.
| I had a very similar problem and that's how I solved it:
when you import cv2 set cv2.setNumThreads(0)
and then you can set num_workers>0 in the dataloader in PyTorch.
Seems like OpenCV tries to multithread and somewhere something goes into a deadlock.
Hope it helps.
| https://stackoverflow.com/questions/54013846/ |
Selection/Filter with indices using pytorch | I have a 3-dimensional numpy array, for example:
x = [[[0.3, 0.2, 0.5],
[0.1, 0.2, 0.7],
[0.2, 0.2, 0.6]]]
The indices array is also 3-dimensional, like:
indices = [[[0],
[1],
[2]]]
I expect the output is:
output= [[[0.3],
[0.2],
[0.6]]]
I tried the torch.index_select and torch.gather function, but I couldn't find a right way to deal with the dimension. Thanks for any help!
| How about using x.gather(dim=2, indices)? That works for me.
| https://stackoverflow.com/questions/54028810/ |
What does the & operator do in PyTorch and why does it change the shape? | I have code that contains x and y, both of the type torch.autograd.variable.Variable. Their shape is
torch.Size([30, 1, 9])
torch.Size([1, 9, 9])
What I don't understand is, why the following results in a different size/shape
z = x & y
print(z.shape)
which outputs
torch.Size([30, 9, 9])
Why is the shape of z 30*9*9, after x & y? The shape of x is 30*1*9, and the shape of y is 1*9*9, what does & do in x & y?
| This has nothing to do with the & operator, but with how broadcasting works in Python. To quote Eric Wieser's excellent documentation on broadcasting in NumPy:
In order to broadcast, the size of the trailing axes for both arrays in an operation must either be the same size or one of them must be one.
See the following image from the quoted page as an example:
This translates to your problem as follows:
a has the shape 30 x 1 x 9
b has the shape 1 x 9 x 9
Therefore the result is created like this:
result1 is a1, because a1 > b1
result2 is b2, because a2 < b2
result3 is both a3 and b3, because a3 = b3
Therefore result has the shape 30 x 9 x 9.
Please also note that the & operator implements logical conjunction on a binary encoding of the tensors' items.
| https://stackoverflow.com/questions/54032221/ |
The correct way to build a binary classifier for CNN | I created a neural network on pytorch using the pretraining model VGG16 and added my own extra layer to define belonging to one of two classes. For example bee or ant.
model = models.vgg16(pretrained=True)
# Freeze early layers
for param in model.parameters():
param.requires_grad = False
n_inputs = model.classifier[6].in_features
# Add on classifier
model.classifier[6] = nn.Sequential(
nn.Linear(n_inputs, 256), nn.ReLU(), nn.Dropout(0.2),
nn.Linear(256, 2), nn.LogSoftmax(dim=1))
The model works well with two classes, but if to upload a crocodile image into it, it is likely to take it for a bee)
Now I want to make a binary classifier based on this model, which defines for example a bee or not a bee (absolutely any image without a bee)
I am just starting to understand neural networks and I need advice on whether the correct way would be training in two groups of images in one of which will only bees and in the other several thousand random images. Or should it be done in another way?
| It is indeed not surprising that a 2-class classifier fails with an image not belonging to any class.
To train your new one-class classifier, yes, use in our test set bees images and a set of non bee images. You need to accommodate for the imbalance between the classes as well to avoid overfitting just the bees images you have. The test accuracy would show such a bias.
| https://stackoverflow.com/questions/54040574/ |
A vector and matrix rows cosine similarity in pytorch | In pytorch, I have multiple (scale of hundred thousand) 300 dim vectors (which I think I should upload in a matrix), I want to sort them by their cosine similarity with another vector and extract the top-1000. I want to avoid for loop as it is time consuming. I was looking for an efficient solution.
| You can use torch.nn.functional.cosine_similarity function for computing cosine similarity. And torch.argsort to extract top 1000.
Here is an example:
x = torch.rand(10000,300)
y = torch.rand(1,300)
dist = F.cosine_similarity(x,y)
index_sorted = torch.argsort(dist)
top_1000 = index_sorted[:1000]
Please note the shape of y, don't forget to reshape before calling similarity function. Also note that argsort simply returns the indexes of closest vectors. To access those vectors themselves, just write x[top_1000], which will return a matrix shaped (1000,300).
| https://stackoverflow.com/questions/54042307/ |
There is an error with LSTM Hidden state dimension: RuntimeError: Expected hidden[0] size (4, 1, 256), got (1, 256) | I'm experimenting with seq2seq_tutorial in PyTorch. There appears to be a dimension error with the encoder's lstm hidden state size.
With bidirectional=True and num_layers = 2, the hidden state's shape is supposed to be (num_layers*2, batch_size, hidden_size).
However, an error occurs with the following message:
RuntimeError: Expected hidden[0] size (4, 1, 256), got (1, 256)
I have tried reshaping the hidden state to initializing the hidden state with a different shape, to begin with, but nothing seems to work.
Here is the train method of my code:
def train(self, input, target, encoder, decoder, encoder_optim, decoder_optim, criterion):
enc_optimizer = encoder_optim
dec_optimizer = decoder_optim
enc_optimizer.zero_grad()
dec_optimizer.zero_grad()
pair = (input, target)
input_len = input.size(0)
target_len = target.size(0)
enc_output_tensor = torch.zeros(self.opt['max_seq_len'], encoder.hidden_size, device=device)
enc_hidden = encoder.cuda().initHidden(device)
for word_idx in range(input_len):
print('Input:', input[word_idx], '\nHidden shape:', enc_hidden.size())
enc_output, enc_hidden = encoder(input[word_idx], enc_hidden)
enc_output_tensor[word_idx] = enc_output[0,0]
Here is the encoder method of my code:
class EncoderBRNN(nn.Module):
# A bidirectional rnn based encoder
def __init__(self, input_size, hidden_size, emb_size, batch_size=1, num_layers=2, bidir=True):
super(EncoderBRNN, self).__init__()
self.input_size = input_size
self.hidden_size = hidden_size
self.batch_size = batch_size
self.embedding_dim = emb_size
self.num_layers = num_layers
self.bidir = bidir
self.embedding_layer = nn.Embedding(self.input_size, self.embedding_dim)
self.enc_layer = nn.LSTM(self.embedding_dim, self.hidden_size, num_layers=self.num_layers, bidirectional=self.bidir)
def forward(self, input, hidden):
embed = self.embedding_layer(input).view(1, 1, -1)
output, hidden = self.enc_layer(embed, hidden)
return output, hidden
def initHidden(self, device):
if self.bidir:
num_stacks = self.num_layers * 2
else:
num_stacks = self.num_layers
return torch.zeros(num_stacks, self.batch_size, self.hidden_size, device=device)
| I know this was asked a while ago but I think I found the answer to this in this torch discussion. Relevant info:
LSTM takes a tuple of hidden states: self.rnn(x, (h_0, c_0)) it looks like you haven’t sent in the second hidden state?
You can also see this in the documentation for LSTM
| https://stackoverflow.com/questions/54042737/ |
Gradually decay the weight of loss function | I am not sure is the right place to ask this question, feel free to tell me if I need to remove the post.
I am quite new in pyTorch and currently working with CycleGAN (pyTorch implementation) as a part of my project and I understand most of the implementation of cycleGAN.
I read the paper with the name ‘CycleGAN with better Cycles’ and I am trying to apply the modification which mentioned in the paper. One of modification is Cycle consistency weight decay which I don’t know how to apply.
optimizer_G.zero_grad()
# Identity loss
loss_id_A = criterion_identity(G_BA(real_A), real_A)
loss_id_B = criterion_identity(G_AB(real_B), real_B)
loss_identity = (loss_id_A + loss_id_B) / 2
# GAN loss
fake_B = G_AB(real_A)
loss_GAN_AB = criterion_GAN(D_B(fake_B), valid)
fake_A = G_BA(real_B)
loss_GAN_BA = criterion_GAN(D_A(fake_A), valid)
loss_GAN = (loss_GAN_AB + loss_GAN_BA) / 2
# Cycle consistency loss
recov_A = G_BA(fake_B)
loss_cycle_A = criterion_cycle(recov_A, real_A)
recov_B = G_AB(fake_A)
loss_cycle_B = criterion_cycle(recov_B, real_B)
loss_cycle = (loss_cycle_A + loss_cycle_B) / 2
# Total loss
loss_G = loss_GAN +
lambda_cyc * loss_cycle + #lambda_cyc is 10
lambda_id * loss_identity #lambda_id is 0.5 * lambda_cyc
loss_G.backward()
optimizer_G.step()
My question is how can I gradually decay the weight of cycle consistency loss?
Any help in implementing this modification would be appreciated.
This is from the paper:
Cycle consistency loss helps to stabilize training a lot in early stages but becomes an obstacle towards realistic images in later stages. We propose to gradually decay the weight of cycle consistency loss λ as training progress. However, we should still make sure that λ is
not decayed to 0 so that generators won’t become unconstrained and go completely wild.
Thanks in advance.
| Below is a prototype function you can use!
def loss (other params, decay params, initial_lambda, steps):
# compute loss
# compute cyclic loss
# function that computes lambda given the steps
cur_lambda = compute_lambda(step, decay_params, initial_lamdba)
final_loss = loss + cur_lambda*cyclic_loss
return final_loss
compute_lambda function for linearly decaying from 10 to 1e-5 in 50 steps
def compute_lambda(step, decay_params):
final_lambda = decay_params["final"]
initial_lambda = decay_params["initial"]
total_step = decay_params["total_step"]
start_step = decay_params["start_step"]
if (step < start_step+total_step and step>start_step):
return initial_lambda + (step-start_step)*(final_lambda-initial_lambda)/total_step
elif (step < start_step):
return initial_lambda
else:
return final_lambda
# Usage:
compute_lambda(i, {"final": 1e-5, "initial":10, "total_step":50, "start_step" : 50})
| https://stackoverflow.com/questions/54047725/ |
pytorch:RuntimeError: dimension out of range (expected to be in range of [-1, 0], but got 1) | When i using the cross-entropy loss as a loss function,i get this dimension out of range error.
This is my code:
self.ce = nn.CrossEntropyLoss()
def forward(self, pred, y):
loss = 0
for w_, p_, y_ in zip(self.weights, pred, y):
loss += w_ * self.ce(p_, y_)
return loss
when i run this code :
the value of p_:tensor(1.00000e-02 *[-0.7625, 5.8737], device='cuda:0')
the value of w_:tensor(1., device='cuda:0')
the value of y_:tensor(0, device='cuda:0')
| For cross entropy there should be the same number of labels as predictions.
In your specific case the dimensions of y_ and p_ should match which they don't as y_ is a 0 dimensional scalar and p_ is 1x2.
| https://stackoverflow.com/questions/54052653/ |
Pytorch: AttributeError: cannot assign module before Module.__init__() call even if initialized | I'm getting the following error:
AttributeError: cannot assign module before Module.init() call
I'm trying to create an instance of my class :
class ResNetGenerator(nn.Module):
def __init__(self, input_nc=3, output_nc=3, n_residual_blocks=9, use_dropout=False):
# super(ResNetGenerator, self).__init__()
super().__init__()
I'm calling super().__init__() but in vain.
What I am doing wrong here?
Complete Traceback:
File "train.py", line 40, in <module>
model = ColorizationCycleGAN(args)
File "/path/cycle_gan.py", line 27, in __init__
self.G_A2B = ResNetGenerator(input_nc=self.input_nc, output_nc=self.output_nc, n_residual_blocks=9, use_dropout=False)
File "/path/.local/lib/python3.6/site packages/torch/nn/modules/module.py", line 544, in __setattr__
"cannot assign module before Module.__init__() call")
AttributeError: cannot assign module before Module.__init__() call
| In fact, I realized that i wasn't calling super().__init__() in the main class ColorizationCycleGAN. Adding this solved the problem.
I hope that this answer will have the effect of reminding you to check to call the super().__init__() function in all classes that inherits from nn.Module.
| https://stackoverflow.com/questions/54053256/ |
Index pytorch tensor with different dimension index array | I have the following function, which does what I want using numpy.array, but breaks when feeding a torch.Tensor due to indexing errors.
import torch
import numpy as np
def combination_matrix(arr):
idxs = np.arange(len(arr))
idx = np.ix_(idxs, idxs)
mesh = np.stack(np.meshgrid(idxs, idxs))
def np_combination_matrix():
output = np.zeros((len(arr), len(arr), 2, *arr.shape[1:]), dtype=arr.dtype)
num_dims = len(output.shape)
output[idx] = arr[mesh].transpose((2, 1, 0, *np.arange(3, num_dims)))
return output
def torch_combination_matrix():
output = torch.zeros(len(arr), len(arr), 2, *arr.shape[1:], dtype=arr.dtype)
num_dims = len(output.shape)
print(arr[mesh].shape) # <-- This is wrong/different to numpy!
output[idx] = arr[mesh].permute(2, 1, 0, *np.arange(3, num_dims))
return output
if isinstance(arr, np.ndarray):
return np_combination_matrix()
elif isinstance(arr, torch.Tensor):
return torch_combination_matrix()
The problem is that arr[mesh] results in different dimensions, depending on numpy and torch. Apparently, pytorch does not support indexing with index arrays of different dimensionality than the array being indexed. Ideally, the following should work:
features = np.arange(9).reshape(3, 3)
np_combs = combination_matrix(features)
features = torch.from_numpy(features)
torch_combs = combination_matrix(features)
assert np.array_equal(np_combs, torch_combs.numpy())
But the dimensions are different:
(2, 3, 3, 3)
torch.Size([3, 3])
Which results in an error (logically):
Traceback (most recent call last):
File "/home/XXX/util.py", line 226, in <module>
torch_combs = combination_matrix(features)
File "/home/XXX/util.py", line 218, in combination_matrix
return torch_combination_matrix()
File "/home/XXX/util.py", line 212, in torch_combination_matrix
output[idx] = arr[mesh].permute(2, 1, 0, *np.arange(3, num_dims))
RuntimeError: number of dims don't match in permute
How do I match the torch behavior to numpy?
I've read various questions on the torch forums (e.g. this one with only one dimension), but could find how to apply this here. Similarly, index_select only works for one dimension, but I need it to work for at least 2 dimensions.
| It is actually embarrassingly easy. You just need to flatten the indices, then reshape and permute the dimensions.
This is the full working version:
import torch
import numpy as np
def combination_matrix(arr):
idxs = np.arange(len(arr))
idx = np.ix_(idxs, idxs)
mesh = np.stack(np.meshgrid(idxs, idxs))
def np_combination_matrix():
output = np.zeros((len(arr), len(arr), 2, *arr.shape[1:]), dtype=arr.dtype)
num_dims = len(output.shape)
output[idx] = arr[mesh].transpose((2, 1, 0, *np.arange(3, num_dims)))
return output
def torch_combination_matrix():
output_shape = (2, len(arr), len(arr), *arr.shape[1:]) # Note that this is different to numpy!
return arr[mesh.flatten()].reshape(output_shape).permute(2, 1, 0, *range(3, len(output_shape)))
if isinstance(arr, np.ndarray):
return np_combination_matrix()
elif isinstance(arr, torch.Tensor):
return torch_combination_matrix()
I used pytest to run this on random arrays of different dimensions, and it seems to work in all cases:
import pytest
@pytest.mark.parametrize('random_dims', range(1, 5))
def test_combination_matrix(random_dims):
dim_size = np.random.randint(1, 40, size=random_dims)
elements = np.random.random(size=dim_size)
np_combs = combination_matrix(elements)
features = torch.from_numpy(elements)
torch_combs = combination_matrix(features)
assert np.array_equal(np_combs, torch_combs.numpy())
if __name__ == '__main__':
pytest.main(['-x', __file__])
| https://stackoverflow.com/questions/54054163/ |
Indexing the max elements in a multidimensional tensor in PyTorch | I'm trying to index the maximum elements along the last dimension in a multidimensional tensor. For example, say I have a tensor
A = torch.randn((5, 2, 3))
_, idx = torch.max(A, dim=2)
Here idx stores the maximum indices, which may look something like
>>>> A
tensor([[[ 1.0503, 0.4448, 1.8663],
[ 0.8627, 0.0685, 1.4241]],
[[ 1.2924, 0.2456, 0.1764],
[ 1.3777, 0.9401, 1.4637]],
[[ 0.5235, 0.4550, 0.2476],
[ 0.7823, 0.3004, 0.7792]],
[[ 1.9384, 0.3291, 0.7914],
[ 0.5211, 0.1320, 0.6330]],
[[ 0.3292, 0.9086, 0.0078],
[ 1.3612, 0.0610, 0.4023]]])
>>>> idx
tensor([[ 2, 2],
[ 0, 2],
[ 0, 0],
[ 0, 2],
[ 1, 0]])
I want to be able to access these indices and assign to another tensor based on them. Meaning I want to be able to do
B = torch.new_zeros(A.size())
B[idx] = A[idx]
where B is 0 everywhere except where A is maximum along the last dimension. That is B should store
>>>>B
tensor([[[ 0, 0, 1.8663],
[ 0, 0, 1.4241]],
[[ 1.2924, 0, 0],
[ 0, 0, 1.4637]],
[[ 0.5235, 0, 0],
[ 0.7823, 0, 0]],
[[ 1.9384, 0, 0],
[ 0, 0, 0.6330]],
[[ 0, 0.9086, 0],
[ 1.3612, 0, 0]]])
This is proving to be much more difficult than I expected, as the idx does not index the array A properly. Thus far I have been unable to find a vectorized solution to use idx to index A.
Is there a good vectorized way to do this?
| An ugly hackaround is to create a binary mask out of idx and use it to index the arrays. The basic code looks like this:
import torch
torch.manual_seed(0)
A = torch.randn((5, 2, 3))
_, idx = torch.max(A, dim=2)
mask = torch.arange(A.size(2)).reshape(1, 1, -1) == idx.unsqueeze(2)
B = torch.zeros_like(A)
B[mask] = A[mask]
print(A)
print(B)
The trick is that torch.arange(A.size(2)) enumerates the possible values in idx and mask is nonzero in places where they equal the idx. Remarks:
If you really discard the first output of torch.max, you can use torch.argmax instead.
I assume that this is a minimal example of some wider problem, but be aware that you are currently reinventing torch.nn.functional.max_pool3d with kernel of size (1, 1, 3).
Also, be aware that in-place modification of tensors with masked assignment can cause issues with autograd, so you may want to use torch.where as shown here.
I would expect that somebody comes up with a cleaner solution (avoiding the intermedia allocation of the mask array), likely making use of torch.index_select, but I can't get it to work right now.
| https://stackoverflow.com/questions/54057112/ |
Weight decay loss | I need to write a code to gradually decay the weight of my loss function by computes lambda with given steps, But I don't have any idea. Any help will be appreciated.
This is my Loss function:
loss_A = criterion(recov_A, real_A)
loss_Final = lambda_A * loss_A + #lambda_A is a fixed number: 10
I don't want the lambda_A to be fixed. I need to gradually decay the lambda after passing the specified number of steps
# write function that computes lambda given the steps
cur_lambda = compute_lambda(step, decay_params, initial_lamdba)
Loss_Final = cur_lambda * loss_A
| To decay the fixed number depends on the number of steps or even the number of epochs you can use the following code or you can write the code as a function and call it whenever you want.
final_value = 1e-3 # Small number because dont end up with 0
initial_value = 20
starting_step = 25
total_step = 100
for i in range(total_step):
if i <= starting_step:
print(i, initial_value)
else:
print (i, initial_value + i * (final_value-initial_value)/total_step)
| https://stackoverflow.com/questions/54057338/ |
RuntimeError: Error(s) in loading state_dict for ResNet: | I am loading my model using the following code.
def load_model(checkpoint_path):
'''
Function that loads a checkpoint and rebuilds the model
'''
checkpoint = torch.load(checkpoint_path, map_location = 'cpu')
if checkpoint['architecture'] == 'resnet18':
model = models.resnet18(pretrained=True)
# Freezing the parameters
for param in model.parameters():
param.requires_grad = False
else:
print('Wrong Architecture!')
return None
model.class_to_idx = checkpoint['class_to_idx']
classifier = nn.Sequential(OrderedDict([
('fc1', nn.Linear(512, 1024)),
('relu1', nn.ReLU()),
('dropout', nn.Dropout(0.2)),
('fc2', nn.Linear(1024, 102))
]))
model.fc = classifier
model.load_state_dict(checkpoint['state_dict'])
return model
And while running
# Load your model to this variable
model = load_model('checkpoint.pt')
I get the following error,
RuntimeError Traceback (most recent call
last)
in ()
1 # Load your model to this variable
----> 2 model = load_model('checkpoint.pt')
3
4 # If you used something other than 224x224 cropped images, set the
correct size here
5 image_size = 224
<ipython-input-11-81aef50793cb> in load_model(checkpoint_path)
30 model.fc = classifier
31
---> 32 model.load_state_dict(checkpoint['state_dict'])
33
34 return model
/opt/conda/lib/python3.6/site-packages/torch/nn/modules/module.py in
load_state_dict(self, state_dict, strict)
719 if len(error_msgs) > 0:
720 raise RuntimeError('Error(s) in loading state_dict for
{}:\n\t{}'.format(
--> 721 self.__class__.__name__,
"\n\t".join(error_msgs)))
722
723 def parameters(self):
RuntimeError: Error(s) in loading state_dict for ResNet:
Unexpected key(s) in state_dict: "bn1.num_batches_tracked",
"layer1.0.bn1.num_batches_tracked", "layer1.0.bn2.num_batches_tracked",
"layer1.1.bn1.num_batches_tracked", "layer1.1.bn2.num_batches_tracked",
"layer2.0.bn1.num_batches_tracked", "layer2.0.bn2.num_batches_tracked",
"layer2.0.downsample.1.num_batches_tracked",
"layer2.1.bn1.num_batches_tracked", "layer2.1.bn2.num_batches_tracked",
"layer3.0.bn1.num_batches_tracked", "layer3.0.bn2.num_batches_tracked",
"layer3.0.downsample.1.num_batches_tracked",
"layer3.1.bn1.num_batches_tracked", "layer3.1.bn2.num_batches_tracked",
"layer4.0.bn1.num_batches_tracked", "layer4.0.bn2.num_batches_tracked",
"layer4.0.downsample.1.num_batches_tracked",
"layer4.1.bn1.num_batches_tracked", "layer4.1.bn2.num_batches_tracked".
| I was using Pytorch 0.4.1 but Jupyter Notebook which I loaded uses 0.4.0. So I added strict=False attribute to load_state_dict().
model.load_state_dict(checkpoint['state_dict'], strict=False)
| https://stackoverflow.com/questions/54058256/ |
I can't adapt my dataset to VGG-net, getting size mismatch | I’m trying to implement the pre-trained VGG net to my script, in order to recognize faces from my dataset in RGB [256,256], but I’m getting a “size mismatch, m1: [1 x 2622], m2: [4096 x 2]” even if i'm resizing my images it doesn't work, as you can see my code work with resnet and alexnet.
I've tryed resizing the images with the function interpolate but the size mismatch persist.
def training(model_conv, learning_rate, wd, net):
criterion = nn.CrossEntropyLoss(weight= torch.FloatTensor([1,1]))
optimizer = torch.optim.Adam(model_conv.fc.parameters(), lr=learning_rate, weight_decay = wd)
total_step = len(train_loader)
loss_list = []
acc_list = []
print("Inizio il training")
for epoch in range(num_epochs):
for i, (im, labels) in enumerate(train_loader):
images = torch.nn.functional.interpolate(im, 224, mode = 'bilinear')
outputs = model_conv(images)
loss = criterion(outputs, labels)
loss_list.append(loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i + 1) % 100 == 0:
print('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch + 1, num_epochs, i + 1, total_step, loss.item()))
torch.save(model_conv, 'TrainedModel.pt')
return images, labels
def main():
net = "vgg"
learning_rate = 10e-6
wd = 10e-4
if net == "vgg":
print("Hai selezionato VGG")
model_conv = VGG_FACE.vgg_face
data = torch.load("VGG_FACE.pth")
model_conv.load_state_dict(data)
model_conv.fc = nn.Linear(4096, 2)
model_conv[-1] = model_conv.fc
if __name__ == '__main__':
main()
For example this is another code where I used correctly my VGG with some random images
def test():
N=5
net = VGG_FACE.vgg_face
data = torch.load("VGG_FACE.pth")
net.load_state_dict(data)
net.eval()
names = open("names.txt").read().split()
with torch.no_grad():
mean = np.array([93.5940, 104.7624, 129.1863])
images = scipy.misc.imread("cooper2.jpg", mode="RGB")
images = scipy.misc.imresize(images, [224, 224])
images = images.astype(np.float32)
images -= mean[np.newaxis, np.newaxis, :]
images = np.transpose(images, (2, 0, 1))
images = images[np.newaxis, ...]
images = torch.tensor(images, dtype=torch.float32)
y = net(images)
y = torch.nn.functional.softmax(y, 1)
rank = torch.topk(y[0, :], N)
for i in range(N):
index = rank[1][i].item()
score = rank[0][i].item()
print("{}) {} ({:.2f})".format(i + 1, names[index], score))
print()
numero_classi = 2
net[-1] = torch.nn.Linear(4096, numero_classi)
if __name__ == "__main__":
test()
the error i'm gettin is
File "/Users/danieleligato/PycharmProjects/parametral/VGGTEST.py", line 53, in training
outputs = model_conv(images)
RuntimeError: size mismatch, m1: [4 x 2622], m2: [4096 x 2] at /Users/soumith/code/builder/wheel/pytorch-src/aten/src/TH/generic/THTensorMath.cpp:2070
THIS IS THE VGG NET THAT I'M USING
class LambdaBase(nn.Sequential):
def __init__(self, fn, *args):
super(LambdaBase, self).__init__(*args)
self.lambda_func = fn
def forward_prepare(self, input):
output = []
for module in self._modules.values():
output.append(module(input))
return output if output else input
class Lambda(LambdaBase):
def forward(self, input):
return self.lambda_func(self.forward_prepare(input))
class LambdaMap(LambdaBase):
def forward(self, input):
return map(self.lambda_func,self.forward_prepare(input))
class LambdaReduce(LambdaBase):
def forward(self, input):
return reduce(self.lambda_func,self.forward_prepare(input))
vgg_face = nn.Sequential( # Sequential,
nn.Conv2d(3,64,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.Conv2d(64,64,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.MaxPool2d((2, 2),(2, 2),(0, 0),ceil_mode=True),
nn.Conv2d(64,128,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.Conv2d(128,128,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.MaxPool2d((2, 2),(2, 2),(0, 0),ceil_mode=True),
nn.Conv2d(128,256,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.Conv2d(256,256,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.Conv2d(256,256,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.MaxPool2d((2, 2),(2, 2),(0, 0),ceil_mode=True),
nn.Conv2d(256,512,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.Conv2d(512,512,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.Conv2d(512,512,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.MaxPool2d((2, 2),(2, 2),(0, 0),ceil_mode=True),
nn.Conv2d(512,512,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.Conv2d(512,512,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.Conv2d(512,512,(3, 3),(1, 1),(1, 1)),
nn.ReLU(),
nn.MaxPool2d((2, 2),(2, 2),(0, 0),ceil_mode=True),
Lambda(lambda x: x.view(x.size(0),-1)), # View,
nn.Sequential(Lambda(lambda x: x.view(1,-1) if 1==len(x.size()) else x ),nn.Linear(25088,4096)), # Linear,
nn.ReLU(),
nn.Dropout(0.5),
nn.Sequential(Lambda(lambda x: x.view(1,-1) if 1==len(x.size()) else x ),nn.Linear(4096,4096)), # Linear,
nn.ReLU(),
nn.Dropout(0.5),
nn.Sequential(Lambda(lambda x: x.view(1,-1) if 1==len(x.size()) else x ),nn.Linear(4096,2622)), # Linear,
)
| The error comes from this line:
model_conv.fc = nn.Linear(4096, 2)
Change to:
model_conv.fc = nn.Linear(2622, 2)
| https://stackoverflow.com/questions/54059953/ |
Gradient disappearing after first epoch in manual linear regression | I'm new to Pytorch and I've been working through the tutorials and playing around with toy examples. I wanted to just make a super simple model to get a better handle on autograd, but I'm running into issues.
I'm trying to train a linear regression model but I keep running into the following error,
----------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-80-ba5ca34a3a54> in <module>()
9 loss = torch.dot(delta, delta)
10
---> 11 loss.backward()
12 with torch.no_grad():
13 w, b = w - learning_rate*w.grad.data, b - learning_rate*b.grad.data
/usr/local/lib/python3.6/dist-packages/torch/tensor.py in backward(self, gradient, retain_graph, create_graph)
91 products. Defaults to ``False``.
92 """
---> 93 torch.autograd.backward(self, gradient, retain_graph, create_graph)
94
95 def register_hook(self, hook):
/usr/local/lib/python3.6/dist-packages/torch/autograd/__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables)
87 Variable._execution_engine.run_backward(
88 tensors, grad_tensors, retain_graph, create_graph,
---> 89 allow_unreachable=True) # allow_unreachable flag
90
91
RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
And for reference, the code is here,
# dataset for training
X = torch.randn(100, 3)
y = -3*X[:,0] + 2.2*X[:,1] + 0.002*X[:,2] + 1
w = torch.randn(3, requires_grad=True, dtype=torch.float) # model weights
b = torch.randn(1, requires_grad=True, dtype=torch.float) # model bias
num_epochs = 10
learning_rate = 1e-4
for i in range(num_epochs):
y_hat = torch.mv(X, w) + b
delta = y_hat - y
loss = torch.dot(delta, delta)
loss.backward()
with torch.no_grad():
w, b = w - learning_rate*w.grad, b - learning_rate*b.grad
The issue seems to be that after the first epoch the gradient attribute is set to None, but I'm a little confused why this would be the case.
If I try to zero the gradient after updating the weights, then I get a similar error.
| The answer lies in locally disabling gradient computation. As you can see in the first example, computations carried out with the torch.no_grad() context manager result in tensors for which requires_grad == False. Since you create "fresh" w and b instead of updating them in place, these tensors lose the requires_grad property after the first iteration and you get the error on 2nd iteration. A simple fix is to reenable gradients
with torch.no_grad():
w, b = w - learning_rate*w.grad, b - learning_rate*b.grad
w.requires_grad_(True)
b.requires_grad_(True)
If you look up the source of optimizers in pytorch optim module, such as SGD, you will see that they use the in-place operators such as add_. You can rewrite your loop in this manner
with torch.no_grad():
w.sub_(learning_rate*w.grad)
b.sub_(learning_rate*b.grad)
which will not touch the requires_grad flag, since the tensors keep their "identity" - just change values. In this case, you will need to remember to call w.zero_grad() and b.zero_grad() in each iteration or the gradient values will keep additively growing.
| https://stackoverflow.com/questions/54064934/ |
Why does this semantic segmentation network have no softmax classification layer in Pytorch? | I am trying to use the following CNN architecture for semantic pixel classification. The code I am using is here
However, from my understanding this type of semantic segmentation network typically should have a softmax output layer for producing the classification result.
I could not find softmax used anywhere within the script. Here is the paper I am reading on this segmentation architecture. From Figure 2, I am seeing softmax being used. Hence I would like to find out why this is missing in the script. Any insight is welcome.
| You are using quite a complex code to do the training/inference. But if you dig a little you'll see that the loss functions are implemented here and your model is actually trained using cross_entropy loss. Looking at the doc:
This criterion combines log_softmax and nll_loss in a single function.
For numerical stability it is better to "absorb" the softmax into the loss function and not to explicitly compute it by the model.
This is quite a common practice having the model outputs "raw" predictions (aka "logits") and then letting the loss (aka criterion) do the softmax internally.
If you really need the probabilities you can add a softmax on top when deploying your model.
| https://stackoverflow.com/questions/54083220/ |
Bicubic interpolation in pytorch | I'm trying to do bicubic interpolation on a torch.Tensor.
I know about torch.nn.functional.interpolate, but that method doesn't support bicubic interpolation yet.
I know that PIL images support bicubic interpolation, so I created this snippet (part of torch.nn.Module).
def build_transform(self, shape):
h, w = shape[2] * self.scale_factor, shape[3] * self.scale_factor
return Compose([
ToPILImage(),
Resize((h, w), interpolation=PIL.Image.BICUBIC),
ToTensor()
])
def forward(self, x: Tensor):
if self.transform is None:
self.transform = self.build_transform(x.shape)
shape = x.shape[0], x.shape[1], x.shape[2] * self.scale_factor, x.shape[3] * self.scale_factor
new = Tensor(size=shape, device=x.device)
for i in range(x.shape[0]):
new[i] = self.transform(x[i])
new.requires_grad_()
return new
My assumption is that this method is slower than interpolating the Tensor in one pass.
My Question: Is there no other way to compute this without the loop? I assume that the difference would be noticeable (correct me if I'm wrong).
| torch.nn.functional.interpolate() with mode='bicubic' is supported since pytorch 1.2.0.
| https://stackoverflow.com/questions/54083474/ |
Expect FloatTensors but got LongTensors in MNIST-like task | I am performing a MNIST-like task, the input is 10-class images, and the expected output is the predicted class of the images.
But now the output is like [-2.3274, -2.2723, ...], which the length is the batch_size. And the target is [4., 2., 2., 8., ...]
Error message: RuntimeError: expected object for scalar type Long but got scalar type float for argument #2 'target'
class Net(nn.Module):
...
...
def forward(self, x):
...
...
return F.log_softmax(x, dim = 1)
criterion = torch.nn.NLLLoss()
Can anyone give me some advice? Thanks.
| The error you got refers to the second (#2) argument of the loss: the target.
NLLLoss expects (for each element) to have a float vector of probabilities, and a single long (i.e., integer) target per element.
In your case, your "target" values are [4., 2., 2., 8., ...] which are of type float. you need to convert your target to long:
target = target.to(dtype=torch.long)
| https://stackoverflow.com/questions/54085357/ |
In PyTorch, what makes a tensor have non-contiguous memory? | According to this SO and this PyTorch discussion, PyTorch's view function works only on contiguous memory, while reshape does not. In the second link, the author even claims:
[view] will raise an error on a non-contiguous tensor.
But when does a tensor have non-contiguous memory?
| This is a very good answer, which explains the topic in the context of NumPy. PyTorch works essentially the same. Its docs don't generally mention whether function outputs are (non)contiguous, but that's something that can be guessed based on the kind of the operation (with some experience and understanding of the implementation). As a rule of thumb, most operations preserve contiguity as they construct new tensors. You may see non-contiguous outputs if the operation works on the array inplace and change its striding. A couple of examples below
import torch
t = torch.randn(10, 10)
def check(ten):
print(ten.is_contiguous())
check(t) # True
# flip sets the stride to negative, but element j is still adjacent to
# element i, so it is contiguous
check(torch.flip(t, (0,))) # True
# if we take every 2nd element, adjacent elements in the resulting array
# are not adjacent in the input array
check(t[::2]) # False
# if we transpose, we lose contiguity, as in case of NumPy
check(t.transpose(0, 1)) # False
# if we transpose twice, we first lose and then regain contiguity
check(t.transpose(0, 1).transpose(0, 1)) # True
In general, if you have non-contiguous tensor t, you can make it contiguous by calling t = t.contiguous(). If t is contiguous, call to t.contiguous() is essentially a no-op, so you can do that without risking a big performance hit.
| https://stackoverflow.com/questions/54095351/ |
How to fix 'cannot initialize type TensorProto DataType' error while importing torch? | I installed pytorch using pip3 command for my windows pc without GPU support.
But when I tried to import torch it is giving an error.
At first, there was a different error saying numpy version not matching and I updated the numpy to the latest version.
import torch
RuntimeError Traceback (most recent call last)
<ipython-input-10-c031d3dd82fc> in <module>()
----> 1 import torch
C:\Users\iamuraptha\Anaconda3\lib\site-packages\torch\__init__.py in <module>()
82 pass
83
---> 84 from torch._C import *
85
86 __all__ += [name for name in dir(_C)
RuntimeError: generic_type: cannot initialize type "TensorProtoDataType": an object with that name is already defined
| I reinstalled anaconda and then created a virtual environment for pytorch.Now everything works fine
| https://stackoverflow.com/questions/54096158/ |
Implementing dropout from scratch | This code attempts to utilize a custom implementation of dropout :
%reset -f
import torch
import torch.nn as nn
# import torchvision
# import torchvision.transforms as transforms
import torch
import torch.nn as nn
import torch.utils.data as data_utils
import numpy as np
import matplotlib.pyplot as plt
import torch.nn.functional as F
num_epochs = 1000
number_samples = 10
from sklearn.datasets import make_moons
from matplotlib import pyplot
from pandas import DataFrame
# generate 2d classification dataset
X, y = make_moons(n_samples=number_samples, noise=0.1)
# scatter plot, dots colored by class value
x_data = [a for a in enumerate(X)]
x_data_train = x_data[:int(len(x_data) * .5)]
x_data_train = [i[1] for i in x_data_train]
x_data_train
y_data = [y[i[0]] for i in x_data]
y_data_train = y_data[:int(len(y_data) * .5)]
y_data_train
x_test = [a[1] for a in x_data[::-1][:int(len(x_data) * .5)]]
y_test = [a for a in y_data[::-1][:int(len(y_data) * .5)]]
x = torch.tensor(x_data_train).float() # <2>
print(x)
y = torch.tensor(y_data_train).long()
print(y)
x_test = torch.tensor(x_test).float()
print(x_test)
y_test = torch.tensor(y_test).long()
print(y_test)
class Dropout(nn.Module):
def __init__(self, p=0.5, inplace=False):
# print(p)
super(Dropout, self).__init__()
if p < 0 or p > 1:
raise ValueError("dropout probability has to be between 0 and 1, "
"but got {}".format(p))
self.p = p
self.inplace = inplace
def forward(self, input):
print(list(input.shape))
return np.random.binomial([np.ones((len(input),np.array(list(input.shape))))],1-dropout_percent)[0] * (1.0/(1-self.p))
def __repr__(self):
inplace_str = ', inplace' if self.inplace else ''
return self.__class__.__name__ + '(' \
+ 'p=' + str(self.p) \
+ inplace_str + ')'
class MyLinear(nn.Linear):
def __init__(self, in_feats, out_feats, drop_p, bias=True):
super(MyLinear, self).__init__(in_feats, out_feats, bias=bias)
self.custom_dropout = Dropout(p=drop_p)
def forward(self, input):
dropout_value = self.custom_dropout(self.weight)
return F.linear(input, dropout_value, self.bias)
my_train = data_utils.TensorDataset(x, y)
train_loader = data_utils.DataLoader(my_train, batch_size=2, shuffle=True)
my_test = data_utils.TensorDataset(x_test, y_test)
test_loader = data_utils.DataLoader(my_train, batch_size=2, shuffle=True)
# Device configuration
device = 'cpu'
print(device)
# Hyper-parameters
input_size = 2
hidden_size = 100
num_classes = 2
learning_rate = 0.0001
pred = []
# Fully connected neural network with one hidden layer
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size, num_classes, p):
super(NeuralNet, self).__init__()
# self.drop_layer = nn.Dropout(p=p)
# self.drop_layer = MyLinear()
# self.fc1 = MyLinear(input_size, hidden_size, p)
self.fc1 = MyLinear(input_size, hidden_size , p)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, num_classes)
def forward(self, x):
# out = self.drop_layer(x)
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
model = NeuralNet(input_size, hidden_size, num_classes, p=0.9).to(device)
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# Move tensors to the configured device
images = images.reshape(-1, 2).to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch) % 100 == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
Custom dropout is implemented as :
class Dropout(nn.Module):
def __init__(self, p=0.5, inplace=False):
# print(p)
super(Dropout, self).__init__()
if p < 0 or p > 1:
raise ValueError("dropout probability has to be between 0 and 1, "
"but got {}".format(p))
self.p = p
self.inplace = inplace
def forward(self, input):
print(list(input.shape))
return np.random.binomial([np.ones((len(input),np.array(list(input.shape))))],1-dropout_percent)[0] * (1.0/(1-self.p))
def __repr__(self):
inplace_str = ', inplace' if self.inplace else ''
return self.__class__.__name__ + '(' \
+ 'p=' + str(self.p) \
+ inplace_str + ')'
class MyLinear(nn.Linear):
def __init__(self, in_feats, out_feats, drop_p, bias=True):
super(MyLinear, self).__init__(in_feats, out_feats, bias=bias)
self.custom_dropout = Dropout(p=drop_p)
def forward(self, input):
dropout_value = self.custom_dropout(self.weight)
return F.linear(input, dropout_value, self.bias)
It seems I've implemented the dropout function incorrectly ? :
np.random.binomial([np.ones((len(input),np.array(list(input.shape))))],1-dropout_percent)[0] * (1.0/(1-self.p))
How to modify in order to correctly utilize dropout ?
These posts were useful in getting to this point :
Hinton's Dropout in 3 Lines of Python :
https://iamtrask.github.io/2015/07/28/dropout/
Making a Custom Dropout Function : https://discuss.pytorch.org/t/making-a-custom-dropout-function/14053/2
|
It seems I've implemented the dropout function incorrectly?
np.random.binomial([np.ones((len(input),np.array(list(input.shape))))],1 dropout_percent)[0] * (1.0/(1-self.p))
In fact, the above implementation is known as Inverted Dropout. Inverted Dropout is how Dropout is implemented in practice in the various deep learning frameworks.
What is inverted dropout?
Before jump into the inverted dropout, it can be helpful to see how Dropout works for a single neuron:
Since during train phase a neuron is kept on with probability q (=1-p), during the testing phase we have to emulate the behavior of the ensemble of networks used in the training phase. To this end, the authors suggest scaling the activation function by a factor of q during the test phase in order to use the expected output produced in the training phase as the single output required in the test phase (Section 10, Multiplicative Gaussian Noise). Thus:
Inverted dropout is a bit different. This approach consists in the scaling of the activations during the training phase, leaving the test phase untouched. The scale factor is the inverse of the keep probability 1/1-p = 1/q, thus:
Inverted dropout helps to define the model once and just change a parameter (the keep/drop probability) to run train and test on the same model. Direct Dropout, instead, force you to modify the network during the test phase because if you don’t multiply by q the output the neuron will produce values that are higher respect to the one expected by the successive neurons (thus the following neurons can saturate or explode): that’s why Inverted Dropout is the more common implementation.
References:
Dropout Regularization, coursera by Andrew NG
What is inverted dropout?
Dropout: scaling the activation versus inverting the dropout
Analysis of Dropout
How implement inverted dropout Pytorch?
class MyDropout(nn.Module):
def __init__(self, p: float = 0.5):
super(MyDropout, self).__init__()
if p < 0 or p > 1:
raise ValueError("dropout probability has to be between 0 and 1, " "but got {}".format(p))
self.p = p
def forward(self, X):
if self.training:
binomial = torch.distributions.binomial.Binomial(probs=1-self.p)
return X * binomial.sample(X.size()) * (1.0/(1-self.p))
return X
How to implement in Numpy?
import numpy as np
pKeep = 0.8
weights = np.ones([1, 5])
binary_value = np.random.rand(weights.shape[0], weights.shape[1]) < pKeep
res = np.multiply(weights, binary_value)
res /= pKeep # this line is called inverted dropout technique
print(res)
How to implement in Tensorflow?
import tensorflow as tf
tf.enable_eager_execution()
weights = tf.ones(shape=[1, 5])
keep_prob = 0.8
random_tensor = keep_prob
random_tensor += tf.random_uniform(weights.shape)
# 0. if [keep_prob, 1.0) and 1. if [1.0, 1.0 + keep_prob)
binary_tensor = tf.floor(random_tensor)
ret = tf.div(weights, keep_prob) * binary_tensor
print(ret)
| https://stackoverflow.com/questions/54109617/ |
Why listing model components in pyTorch is not useful? | I am trying to create Feed forward neural networks with N layers
So idea is suppose If I want 2 inputs 3 hidden and 2 outputs than I will just pass [2,3,2] to neural network class and neural network model will get created so if I want [100,1000,1000,2]
where in this case 100 is inputs, two hidden layers contains 1000 neuron each and 2 outputs so I want fully connected neural network where I just wanted to pass list which contains number of neuron in each layer.
So for that I have written following code
class FeedforwardNeuralNetModel(nn.Module):
def __init__(self, layers):
super(FeedforwardNeuralNetModel, self).__init__()
self.fc=[]
self.sigmoid=[]
self.activationValue = []
self.layers = layers
for i in range(len(layers)-1):
self.fc.append(nn.Linear(layers[i],layers[i+1]))
self.sigmoid.append(nn.Sigmoid())
def forward(self, x):
out=x
for i in range(len(self.fc)):
out=self.fc[i](out)
out = self.sigmoid[i](out)
return out
when I tried to use it I found it kind of empty model
model=FeedforwardNeuralNetModel([3,5,10,2])
print(model)
>>FeedforwardNeuralNetModel()
and when I used following code
class FeedforwardNeuralNetModel(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(FeedforwardNeuralNetModel, self).__init__()
# Linear function
self.fc1 = nn.Linear(input_dim, hidden_dim)
# Non-linearity
self.tanh = nn.Tanh()
# Linear function (readout)
self.fc2 = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
# Linear function
out = self.fc1(x)
# Non-linearity
out = self.tanh(out)
# Linear function (readout)
out = self.fc2(out)
return out
and when I tried to print this model I found following result
print(model)
>>FeedforwardNeuralNetModel(
(fc1): Linear(in_features=3, out_features=5, bias=True)
(sigmoid): Sigmoid()
(fc2): Linear(in_features=5, out_features=10, bias=True)
)
in my code I am just creating lists that is what difference
I just wanted to understand why in torch listing model components is not useful?
| If you do print(FeedForwardNetModel([1,2,3]) it gives the following error
AttributeError: 'FeedforwardNeuralNetModel' object has no attribute '_modules'
which basically means that the object is not able to recognize modules that you have declared.
Why does this happen?
Currently, modules are declared in self.fc which is list and hence torch has no way of knowing if it is a model unless it does a deep search which is bad and inefficient.
How can we let torch know that self.fc is a list of modules?
By using nn.ModuleList (See modified code below). ModuleList and ModuleDict are python list and dictionaries respectively, but they tell torch that the list/dict contains a nn module.
#modified init function
def __init__(self, layers):
super().__init__()
self.fc=nn.ModuleList()
self.sigmoid=[]
self.activationValue = []
self.layers = layers
for i in range(len(layers)-1):
self.fc.append(nn.Linear(layers[i],layers[i+1]))
self.sigmoid.append(nn.Sigmoid())
| https://stackoverflow.com/questions/54143427/ |
pytorch instance tensor not moved to gpu even with explicit cuda() call | I'm working on a project where the model requires access to a tensor that i declare in the constructor init of the class (im sub-classing torch.nn.Module class) and then i need to use this tensor in the forward() method via a simple matmul() , the model is sent to gpu via a cuda() call:
model = Model()
model.cuda()
However when i do forward-propagation of a simple input X through:
model(X) # or model.forward(X)
I get
RuntimeError: Expected object of type torch.cuda.FloatTensor but found
type torch.FloatTensor for argument #2 'mat2'
Indicating that the second argument of matmul(the instance tensor i declared) is on CPU and it was expected on GPU (as the rest of the model and data).
In matmul, the tensor is transposed via matrix.t()
I even tried overriding the cuda() method thorugh:
def cuda(self):
super().cuda()
self.matrix.cuda()
The data is already in the GPU ,meaning the following line of code was already executed:
X = X.cuda()
Also the error explcitly says argument 2 of matmul which for this case is the tensor(called matrix) not X.
| Let's assume the following:
X is moved correctly to the GPU
The tensor declared in the Model class is a simple attribute.
i.e. Something like the following:
class Model(nn.Module):
def __init__(self):
super().__init__()
self.matrix = torch.randn(784, 10)
def forward(self, x):
return torch.matmul(x, self.matrix)
If so, your first attempt wouldn't work because the nn.Module.cuda() method only moves all of the Parameters and Buffers to the GPU.
You would need to make Model.matrix a Parameter instead of regular attribute.
Wrap it in the parameter class.
Something like:
self.matrix = nn.Parameter(torch.randn(784, 10))
Now, instead of automatically casting to the GPU like above, you tried to manually call the .cuda() method on Model.matrix within the override.
This doesn't work either because of a subtle difference between the nn.Module.cuda() method and the torch.Tensor.cuda() method.
While nn.Module.cuda() moves all the Parameters and Buffers of the Module to GPU and returns itself, torch.Tensor.cuda() only returns a copy of the tensor on the GPU.
The original tensor is unaffected.
In summary, either:
Wrap your matrix attribute as a Parameter or
Assign the GPU copy back to matrix via:
self.matrix = self.matrix.cuda()
In your override.
I would suggest the first.
| https://stackoverflow.com/questions/54155969/ |
RuntimeError: The shape of the mask [1682] at index 0 does not match the shape of the indexed tensor [1, 1682] at index 0 | I am designing an stacked autoencoder trying to train my neural network on movie rating if the user doesnt rate any movie it will not consider it
My training set runs perfectly but when i run test set it shows me this error
RuntimeError: The shape of the mask [1682] at index 0 does not match the shape of the indexed tensor [1, 1682] at index 0
I got error at the end test block i have commented there
CODE:-
# Auto Encoder
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
# Importing dataset
movies= pd.read_csv('ml-1m/movies.dat',sep ='::', header= None,engine ='python', encoding= 'latin-1')
users= pd.read_csv('ml-1m/users.dat',sep ='::', header= None,engine ='python', encoding= 'latin-1')
ratings = pd.read_csv('ml-1m/ratings.dat',sep ='::', header= None,engine ='python', encoding= 'latin-1')
# preparing the training set and the dataset
training_set =pd.read_csv('ml-100k/u1.base',delimiter ='\t')
training_set =np.array(training_set, dtype= 'int')
test_set =pd.read_csv('ml-100k/u1.test',delimiter ='\t')
test_set =np.array(test_set, dtype= 'int')
# Getting the number of users and movies
# we are taking the maximum no of values from training set and test set
nb_users = int(max(max(training_set[:,0]), max(test_set[:,0])))
nb_movies = int(max(max(training_set[:,1]), max(test_set[:,1])))
# converting the data into an array within users in lines and movies in columns
def convert(data):
new_data = []
for id_users in range(1, nb_users +1):
id_movies = data[:,1][data[:,0]==id_users]#movies id from data
id_ratings = data[:,2][data[:,0]==id_users] #ratings
ratings= np.zeros(nb_movies)
ratings[id_movies-1] = id_ratings # -1 for making it start from 1
new_data.append(list(ratings))
return new_data
training_set =convert(training_set)
test_set =convert(test_set)
# Converting the data into Torch tensor
training_set = torch.FloatTensor(training_set)
test_set = torch.FloatTensor(test_set)
# creating the architecture of the neural network
class SAE(nn.Module):
def __init__(self, ): # after comma it will consider parameters of module ie parent class
super(SAE,self).__init__()#parent class inheritence
self.fc1 = nn.Linear(nb_movies, 20) #20 nodes in hidden layer
self.fc2= nn.Linear(20,10)
self.fc3 = nn.Linear(10,20) #decoding
self.fc4= nn.Linear(20, nb_movies) #decoding
self.activation= nn.Sigmoid()
#self.myparameters= nn.ParameterList(self.fc1,self.fc2,self.fc3,self.fc4,self.activation)
def forward(self, x):
x=self.activation(self.fc1(x))#encoding
x=self.activation(self.fc2(x))#encoding
x=self.activation(self.fc3(x)) #decoding
x=self.fc4(x) #last layer machine understand automaically
return x
sae= SAE()
criterion = nn.MSELoss()
optimizer= optim.RMSprop(sae.parameters(), lr= 0.01 , weight_decay =0.5)
# Training the SAE
nb_epoch = 200
for epoch in range(1, nb_epoch + 1):
train_loss = 0
s = 0.
for id_user in range(nb_users):
input = Variable(training_set[id_user]).unsqueeze(0)
target = input.clone()
if torch.sum(target.data > 0) > 0:
output = sae(input)
target.require_grad = False
output[target == 0] = 0
loss = criterion(output, target)
mean_corrector = nb_movies/float(torch.sum(target.data > 0) + 1e-10)
loss.backward()
train_loss += np.sqrt(loss.data.item()*mean_corrector)
s += 1.
optimizer.step()
print('epoch: '+str(epoch)+' loss: '+str(train_loss/s))
# Testing the SAE
test_loss = 0
s = 0.
for id_user in range(nb_users):
input = Variable(training_set[id_user]).unsqueeze(0)
target = Variable(test_set[id_user])
if torch.sum(target.data > 0) > 0:
output = sae(input)
target.require_grad = False
output[target == 0] = 0 # I get error at this line
loss = criterion(output, target)
mean_corrector = nb_movies/float(torch.sum(target.data > 0) + 1e-10)
test_loss += np.sqrt(loss.data.item()*mean_corrector)
s += 1.
print('test loss: '+str(test_loss/s))
| Change:
output[target == 0] = 0 # I get error at this line
To:
output[(target == 0).unsqueeze(0)] = 0
Reason:
The torch.Tensor returned by target == 0 is of the shape [1682].
(target == 0).unsqueeze(0) will convert it to [1, 1682]
| https://stackoverflow.com/questions/54159814/ |
How to use a numpy function as the loss function in PyTorch and avoid getting errors during run time? | For my task, I do not need to compute gradients. I am simply replacing nn.L1Loss with a numpy function (corrcoef) in my loss evaluation but I get the following error:
RuntimeError: Can’t call numpy() on Variable that requires grad. Use var.detach().numpy() instead.
I couldn’t figure out how exactly I should detach the graph (I tried torch.Tensor.detach(np.corrcoef(x, y)) but I still get the same error. I eventually wrapped everything using with torch.no_grad as follow:
with torch.no_grad():
predFeats = self.forward(x)
targetFeats = self.forward(target)
loss = torch.from_numpy(np.corrcoef(predFeats.cpu().numpy().astype(np.float32), targetFeats.cpu().numpy().astype(np.float32))[1][1])
But this time I get the following error:
TypeError: expected np.ndarray (got numpy.float64)
I wonder, what am I doing wrong?
| TL;DR
with torch.no_grad():
predFeats = self(x)
targetFeats = self(target)
loss = torch.tensor(np.corrcoef(predFeats.cpu().numpy(),
targetFeats.cpu().numpy())[1][1]).float()
You would avoid the first RuntimeError by detaching the tensors (predFeats and targetFeats) from the computational graph.
i.e. Getting a copy of the tensor data without the gradients and the gradient function (grad_fn).
So, instead of
torch.Tensor.detach(np.corrcoef(x.numpy(), y.numpy())) # Detaches a newly created tensor!
# x and y still may have gradients. Hence the first error.
which does nothing, do
# Detaches x and y properly
torch.Tensor(np.corrcoef(x.detach().numpy(), y.detach().numpy()))
But let's not bother with all the detachments.
Like you rightfully fixed, it, let's disable the gradients.
torch.no_grad()
Now, compute the features.
predFeats = self(x) # No need for the explicit .forward() call
targetFeats = self(target)
I found it helpful to break your last line up.
loss = np.corrcoef(predFeats.numpy(), targetFeats.numpy()) # We don't need to detach
# Notice that we don't need to cast the arguments to fp32
# since the `corrcoef` casts them to fp64 anyway.
print(loss.shape, loss.dtype) # A 2-dimensional fp64 matrix
loss = loss[1][1]
print(type(loss)) # Output: numpy.float64
# Loss now just a simple fp64 number
And that is the problem!
Because, when we do
loss = torch.from_numpy(loss)
we're passing in a number (numpy.float64) while it expects a numpy tensor (np.ndarray).
If you're using PyTorch 0.4 or up, there's inbuilt support for scalars.
Simply replace the from_numpy() method with the universal tensor() creation method.
loss = torch.tensor(loss)
P.S. You might also want to look at setting rowvar=False in corrcoef since the rows in PyTorch tensors usually represent the observations.
| https://stackoverflow.com/questions/54165651/ |
grad_outputs in torch.autograd.grad (CrossEntropyLoss) | I’m trying to get d(loss)/d(input). I know I have 2 options.
First option:
loss.backward()
dlossdx = x.grad.data
Second option:
# criterion = nn.CrossEntropyLoss(reduce=False)
# loss = criterion(y_hat, labels)
# No need to call backward.
dlossdx = torch.autograd.grad(outputs = loss,
inputs = x,
grad_outputs = ? )
My question is: if I use cross-entropy loss, what should I pass as grad_outputs in the second option?
Do I put d(CE)/d(y_hat)? Since pytorch crossentropy contains softmax, this will require me to pre-calculate softmax derivative using Kronecker delta.
Or do I put d(CE)/d(CE) which is torch.ones_like?
A conceptual answer is fine.
| Let's try to understand how both the options work.
We will use this setup
import torch
import torch.nn as nn
import numpy as np
x = torch.rand((64,10), requires_grad=True)
net = nn.Sequential(nn.Linear(10,10))
labels = torch.tensor(np.random.choice(10, size=64)).long()
criterion = nn.CrossEntropyLoss()
First option
loss = criterion(net(x), labels)
loss.backward(retain_graph=True)
dloss_dx = x.grad
Note that you passed no options to gradient because the loss is a scalar quantity if you compute loss as a vector, then you have to pass
Second option
dloss_dx2 = torch.autograd.grad(loss, x)
This will return a tuple and you can use the first element as the gradient of x.
Note that torch.autograd.grad return sum of dout/dx if you pass multiple outputs as tuples. But since loss is scalar, you don't need to pass grad_outputs as by default it will consider it to be one.
| https://stackoverflow.com/questions/54166206/ |
PyTorch - RuntimeError: bool value of Tensor with more than one value is ambiguous | I trained a GAN on the MNIST dataset, and I'm trying to make a very simple UI that has a button to generate and display new images. When I press a button I make a call to the generator and pass a new latent vector to the forward method and keep getting this error message.
def update_picture():
print('press')
_, img = netG.forward(create_noise(1))
img = img.detach().cpu().numpy()[0][0]
img = ((img - img.min()) * (1 / img.max() - img.min()) * 255)
photo = ImageTk.PhotoImage(image=Image.fromarray(img))
label = Label(image=photo).grid(row=0, column=0)
tk = Tk()
photo = ImageTk.PhotoImage(image=Image.fromarray(img))
label = Label(image=photo).grid(row=0, column=0)
create = Button(text="update", command=update_picture).grid(row=1, column=0)
tk.mainloop()
And when I press the button to generate a new picture I keep getting this error:
Traceback (most recent call last):
File "C:\Users\daman\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users/daman/PycharmProjects/untitled4/DCGAN_MNIST.py", line 243, in update_picture
_, img = netG.forward(create_noise(1))
File "C:/Users/daman/PycharmProjects/untitled4/DCGAN_MNIST.py", line 104, in create_noise
return Variable(torch.zeros(b, feature_space, 1, 1).normal_(0, 1))
File "C:\Users\daman\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 315, in __init__
if not master:
RuntimeError: bool value of Tensor with more than one value is ambiguous
The error traces back to my create noise function:
def create_noise(b):
return Variable(torch.zeros(b, feature_space, 1, 1).normal_(0, 1))
Any ideas why this is happening and what does that error actually mean? I can post more code if needed.
| I think I got the problem.
Variable is a name reserved in torch and tkinter. If you are doing from ... import * you may get Variable from tkinter. Since the error is comming from this line, the Variable in your code is from tkinter. However, since you are calling it with a Tensor inside, I'm guessing that you wanted the deprecated version of torch's Variable.
Simply removing Variable in create_noise should do the work.
def create_noise(b):
return torch.zeros(b, feature_space, 1, 1).normal_(0, 1)
| https://stackoverflow.com/questions/54188885/ |
Pytorch detach() function failed to be excuated on different GPU severs | Recently, our lab bought a new server with 9 GPUs and I want to run my programming on this machine. However, I do not change my right code and I got an unexpected error like the following.
THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THC/THCGeneral.cpp line=663 error=11 : invalid argument
Traceback (most recent call last):
File "main.py", line 166, in <module>
p_img.copy_(netG(p_z).detach())
File "/usr/local/anaconda3/envs/tensorflow/lib/python3.6/site-packages/torch/nn/modules/module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "/home/szhangcj/python/GBGAN/celebA_attention/sagan_models.py", line 100, in forward
out,p1 = self.attn1(out)
File "/usr/local/anaconda3/envs/tensorflow/lib/python3.6/site-packages/torch/nn/modules/module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "/home/szhangcj/python/GBGAN/celebA_attention/sagan_models.py", line 32, in forward
energy = torch.bmm(proj_query,proj_key) # transpose check
RuntimeError: cublas runtime error : the GPU program failed to execute at /opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THC/THCBlas.cu:411
However, I can run my programming successfully on the old machine with 4 GPUs. I am not sure what the problem is and it seems that the error is caused by the detach() function. My code is as the following.
z_b = torch.FloatTensor(opt.batch_size, opt.z_dim).to(device)
img_b = torch.FloatTensor(opt.batch_size, 3, 64, 64).to(device)
img_a = torch.FloatTensor(opt.batch_size, 3, 64, 64).to(device)
p_z = torch.FloatTensor(pool_size, opt.z_dim).to(device)
p_img = torch.FloatTensor(pool_size, 3, 64, 64).to(device)
## evaluation placeholder
show_z_b = torch.FloatTensor(100, opt.z_dim).to(device)
eval_z_b = torch.FloatTensor(250, opt.z_dim).to(device) # 250/batch * 120 --> 300000
optim_D = optim.Adam(netD.parameters(), lr=opt.lr_d) # other param?
optim_G = optim.Adam(netG.parameters(), lr=opt.lr_g) #?suitable
criterion_G = nn.MSELoss()
eta = 1
loss_GD = []
pre_loss = 0
cur_loss = 0
G_epoch = 1
for epoch in range(start_epoch, start_epoch + opt.num_epoch):
print('Start epoch: %d' % epoch)
## input_pool: [pool_size, opt.z_dim] -> [pool_size, 32, 32]
netD.train()
netG.eval()
p_z.normal_()
# print(netG(p_z).detach().size())
p_img.copy_(netG(p_z).detach())
for t in range(opt.period):
for _ in range(opt.dsteps):
t = time.time()
### Update D
netD.zero_grad()
## real
real_img, _ = next(iter(dataloader)) # [batch_size, 1, 32, 32]
img_b.copy_(real_img.squeeze().to(device))
real_D_err = torch.log(1 + torch.exp(-netD(img_b))).mean()
print("D real loss", netD(img_b).mean())
# real_D_err.backward()
## fake
z_b_idx = random.sample(range(pool_size), opt.batch_size)
img_a.copy_(p_img[z_b_idx])
fake_D_err = torch.log(1 + torch.exp(netD(img_a))).mean() # torch scalar[]
loss_gp = calc_gradient_penalty(netD, img_b, img_a)
total_loss = real_D_err + fake_D_err + loss_gp
print("D fake loss", netD(img_a).mean())
total_loss.backward()
optim_D.step()
## update input pool
p_img_t = p_img.clone().to(device)
p_img_t.requires_grad_(True)
if p_img_t.grad is not None:
p_img_t.grad.zero_()
fake_D_score = netD(p_img_t)
fake_D_score.backward(torch.ones(len(p_img_t)).to(device))
p_img = img_truncate(p_img + eta * p_img_t.grad)
print("The mean of gradient", torch.mean(p_img_t.grad))
| The error is caused by the version mismatching between the RTX GPU cards and the CUDA driver.
| https://stackoverflow.com/questions/54193209/ |
Torch C++: Getting the value of a int tensor by using *.data() | In the C++ version of Libtorch, I found that I can get the value of a float tensor by *tensor_name[0].data<float>(), in which instead of 0 I can use any other valid index. But, when I have defined an int tensor by adding option at::kInt into the tensor creation, I cannot use this structure to get the value of the tensor, i.e. something like *tensor_name[0].data<at::kInt>() or *tensor_name[0].data<int>() does not work and the debugger keeps saying that Couldn't find method at::Tensor::data<at::kInt> or Couldn't find method at::Tensor::data<int>.
I can get the values by auto value_array = tensor_name=accessor<int,1>(), but it was easier to use *tensor_name[0].data<int>(). Can you please let me know how I can use data<>() to get the value of an int tensor?
I also have a same problem with bool type.
| Use item<dtype>() to get a scalar out of a Tensor.
int main() {
torch::Tensor tensor = torch::randint(20, {2, 3});
std::cout << tensor << std::endl;
int a = tensor[0][0].item<int>();
std::cout << a << std::endl;
return 0;
}
~/l/build ❯❯❯ ./example-app
3 10 3
2 5 8
[ Variable[CPUFloatType]{2,3} ]
3
The following code prints 0 (tested on Linux with the stable libtorch):
#include <torch/script.h>
#include <iostream>
int main(int argc, const char* argv[])
{
auto indx = torch::zeros({20},at::dtype(at::kLong));
std::cout << indx[0].item<long>() << std::endl;
return 0;
}
| https://stackoverflow.com/questions/54200785/ |
size mismatch, m1: [3584 x 28], m2: [784 x 128] at /pytorch/aten/src/TH/generic/THTensorMath.cpp:940 | I have executed the following code and getting the error shown at extreme bottom. I would like to know how to resolve this. thanks
import torch.nn as nn
import torch.nn.functional as F
from torch import optim
from torchvision import transforms
_tasks = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
from torchvision.datasets import MNIST
mnist = MNIST("data", download=True, train=True, transform=_tasks)
from torch.utils.data import DataLoader
from torch.utils.data.sampler import SubsetRandomSampler
create training and validation split
split = int(0.8 * len(mnist))
index_list = list(range(len(mnist)))
train_idx, valid_idx = index_list[:split], index_list[split:]
create sampler objects using SubsetRandomSampler
tr_sampler = SubsetRandomSampler(train_idx)
val_sampler = SubsetRandomSampler(valid_idx)
create iterator objects for train and valid datasets
trainloader = DataLoader(mnist, batch_size=256, sampler=tr_sampler)
validloader = DataLoader(mnist, batch_size=256, sampler=val_sampler)
Creating model for execution
class Model(nn.Module):
def init(self):
super().init()
self.hidden = nn.Linear(784, 128)
self.output = nn.Linear(128, 10)
def forward(self, x):
x = self.hidden(x)
x = F.sigmoid(x)
x = self.output(x)
return x
model = Model()
loss_function = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, weight_decay= 1e-6, momentum = 0.9, nesterov = True)
for epoch in range(1, 11): ## run the model for 10 epochs
train_loss, valid_loss = [], []
#training part
model.train()
for data, target in trainloader:
optimizer.zero_grad()
#1. forward propagation
output = model(data)
#2. loss calculation
loss = loss_function(output, target)
#3. backward propagation
loss.backward()
#4. weight optimization
optimizer.step()
train_loss.append(loss.item())
# evaluation part
model.eval()
for data, target in validloader:
output = model(data)
loss = loss_function(output, target)
valid_loss.append(loss.item())
Executing this I am getting the following error :
RuntimeError Traceback (most recent call last) in ()
----> 1 output = model(data) 2 3 ## 2. loss calculation 4 loss = loss_function(output, target) 5
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in
call(self, *input, **kwargs) 487 result = self._slow_forward(*input,
**kwargs)
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in
linear(input, weight, bias) 1352 ret =
torch.addmm(torch.jit._unwrap_optional(bias), input, weight.t()) 1353
else:
-> 1354 output = input.matmul(weight.t()) 1355 if bias is not None: 1356 output += torch.jit._unwrap_optional(bias)
RuntimeError: size mismatch, m1: [3584 x 28], m2: [784 x 128] at
/pytorch/aten/src/TH/generic/THTensorMath.cpp:940
| Your input MNIST data has shape [256, 1, 28, 28] corresponding to [B, C, H, W]. You need to flatten the input images into a single 784 long vector before feeding it to the Linear layer Linear(784, 128) such that the input becomes [256, 784] corresponding to [B, N], where N is 1x28x28, your image size. This can be done as follows:
for data, target in trainloader:
# Flatten MNIST images into a 784 long vector
data = data.view(data.shape[0], -1)
optimizer.zero_grad()
...
The same is needed to be done in the validation loop.
| https://stackoverflow.com/questions/54218604/ |
How to vectorize computation of mean over specific set of indices given as matrix rows? | I have a problem vectorizing some code in pytorch.
A numpy solution would also help, but a pytorch solution would be better.
I'm going to use array and Tensor interchangeably.
The problem I am facing is this:
Given an 2D float array X of size (n, x), and a boolean 2D array A of size (n, n), compute the mean over rows in X indexed by rows in A.
The problem is that the rows in A contain a variable number of True indices.
Example (numpy):
import numpy as np
A = np.array([[0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 1, 0, 0],
[0, 1, 1, 1, 0, 0]])
X = np.arange(6 * 3, dtype=np.float32).reshape(6, 3)
# Compute the mean in numpy with a for loop
means_np = np.array([X[A.astype(np.bool)[i]].mean(axis=0) for i in np.arange(len(A)])
So this examples works, but this formulation has 3 problems:
The for loop is slow for larger A and X. I need to loop over a few 10 thousand indices.
It can happen that A[i] contains no True indices. This results in np.mean(np.array([])), which is NaN. I want this to be 0 instead.
Implementing it this way in pytorch results in SIGFPE (Floating point error) during the backwards pass of backpropagation through this function. The cause is when nothing being selected.
The workaround that I am using now is (also see code below):
Set the diagonal elements of A to True so that there is always at least one element to select
sum of all selected elements, subtract the values in X from that sum (the diagonal is guaranteed to be False in the beginning), and divide by the number of True elements - 1 clamped to at least 1 in each row.
This works, is differentiable in pytorch and does not produce NaN, but I still need a loop over all indices.
How can I get rid of this loop?
This is my current pytorch code:
import torch
A = torch.from_numpy(A).bytes()
X = torch.from_numpy(X)
A[np.diag_indices(len(A)] = 1 # Set the diagonal to 1
means = [(X[A[i]].sum(dim=0) - X[i]) / torch.clamp(A[i].sum() - 1, min=1.) # Compute the mean safely
for i in range(len(A))] # Get rid of the loop somehow
means = torch.stack(means)
I don't mind if your version looks completely different, as long as it is differentiable and produces the same result.
| We can leverage matrix-multiplication -
c = A.sum(1,keepdims=True)
means_np = np.where(c==0,0,A.dot(X)/c)
We can optimize it further by converting A to float32 dtype if it's not already so and if the loss of precision is okay there, as shown below -
In [57]: np.random.seed(0)
In [58]: A = np.random.randint(0,2,(1000,1000))
In [59]: X = np.random.rand(1000,1000).astype(np.float32)
In [60]: %timeit A.dot(X)
10 loops, best of 3: 27 ms per loop
In [61]: %timeit A.astype(np.float32).dot(X)
100 loops, best of 3: 10.2 ms per loop
In [62]: np.allclose(A.dot(X), A.astype(np.float32).dot(X))
Out[62]: True
Thus, use A.astype(np.float32).dot(X) to replace A.dot(X).
Alternatively, to solve for the case where the row-sum is zero, and that requires us to use np.where, we could assign any non-zero value, say 1 into c and then simply divide by it, like so -
c = A.sum(1,keepdims=True)
c[c==0] = 1
means_np = A.dot(X)/c
This would also avoid the warning that we would otherwise get from np.where in those zero row sum cases.
| https://stackoverflow.com/questions/54220249/ |
how to fix capsule training problem for a single class of MNIST dataset? | I am training a Capsule Network with both encoder and decoder part. It works perfectly fine with all the classes (10 classes) of the MNIST data set. But when I am extracting a single class say (class 0 or class 5) and then training the capsule network, the reconstruction of the image is very poor.
Where do I need to change the network setting, or do I have an error in my data preparation?
I tried:
I changed the total class from 10 (for ten digits to 1 for 1 digit and even for 2 for 2 digits).
When I am using the default MNIST dataset, I am getting no error or tensor size, but when I am extracting a particular class and then passing it into the network, I am facing issues like a) Dimensional Issues b) Float tensor warning.
I fixed these things but manually adding a dimension and converting the data to data.float().cuda() tensor. I did this for both the case i.e when I am using the 10 Digit Capsules and when I am using the 1 Digit Capsules for training a single class digit.
But after this, the network is running fine, but I am getting really blurred and poor reconstructions. While when I am training the whole MNIST dataset without extracting any class and passing it to the network, it doesn't throw any error and the reconstruction works really fine.
I would love to share the more detail and other parts of the code -
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.optim import Adam
from torchvision import datasets, transforms
USE_CUDA = True
### **Here we prepare the data for the complete 10 class digit training**###
class Mnist:
def __init__(self, batch_size):
dataset_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST('../data', train=True, download=True, transform=dataset_transform)
test_dataset = datasets.MNIST('../data', train=False, download=True, transform=dataset_transform)
self.train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
self.test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=True)
## **Here is my code for extracting a single class digit extraction**##
class Mnist:
def __init__(self,batch_size):
dataset_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_mnist = datasets.MNIST("../data", train=True)
test_mnist = datasets.MNIST("../data", train= False)
train_image, train_label = train_mnist.train_data, train_mnist.train_labels
test_image, test_label = test_mnist.test_data, test_mnist.test_labels
train_0, test_0 = [train_image[key] for (key, label) in enumerate(train_label) if int(label) == 5],[test_image[key] for (key, label) in enumerate(test_label) if int(label) == 5]
train_label_0, test_label_0 = zero__train = [train_label[key] for (key, label) in enumerate(train_label) if int(label) == 5],[test_label[key] for (key, label) in enumerate(test_label) if int(label) == 5]
train_dataset = tuple(zip(train_0, train_label_0))
test_dataset = tuple(zip(test_0, test_label_0))
self.train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
self.test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=True)
# Here is the main code for the capsule training.
''' The below code is used for training the 1 class but using the 10 Digit capsules
'''
class ConvLayer(nn.Module):
def __init__(self, in_channels=1, out_channels=256, kernel_size=9):
super(ConvLayer, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels,
out_channels=out_channels,
kernel_size=kernel_size,
stride=1
)
def forward(self, x):
return F.relu(self.conv(x))
class PrimaryCaps(nn.Module):
def __init__(self, num_capsules=8, in_channels=256, out_channels=32, kernel_size=9):
super(PrimaryCaps, self).__init__()
self.capsules = nn.ModuleList([
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=2, padding=0)
for _ in range(num_capsules)])
def forward(self, x):
u = [capsule(x) for capsule in self.capsules]
u = torch.stack(u, dim=1)
u = u.view(x.size(0), 32 * 6 * 6, -1)
return self.squash(u)
def squash(self, input_tensor):
squared_norm = (input_tensor ** 2).sum(-1, keepdim=True)
output_tensor = squared_norm * input_tensor / ((1. + squared_norm) * torch.sqrt(squared_norm))
return output_tensor
class DigitCaps(nn.Module):
def __init__(self, num_capsules=10, num_routes=32 * 6 * 6, in_channels=8, out_channels=16):
super(DigitCaps, self).__init__()
self.in_channels = in_channels
self.num_routes = num_routes
self.num_capsules = num_capsules
self.W = nn.Parameter(torch.randn(1, num_routes, num_capsules, out_channels, in_channels))
def forward(self, x):
batch_size = x.size(0)
x = torch.stack([x] * self.num_capsules, dim=2).unsqueeze(4)
# print(f"x at epoch {epoch} is equal to : {x}")
W = torch.cat([self.W] * batch_size, dim=0)
# print(f"W at epoch {epoch} is equal to : {W}")
u_hat = torch.matmul(W, x)
# print(f"u_hatat epoch {epoch} is equal to : {u_hat}")
b_ij = Variable(torch.zeros(1, self.num_routes, self.num_capsules, 1))
if USE_CUDA:
b_ij = b_ij.cuda()
# print(f"b_ij at epoch {epoch} is equal to : {b_ij}")
num_iterations = 3
for iteration in range(num_iterations):
c_ij = F.softmax(b_ij, dim =1)
c_ij = torch.cat([c_ij] * batch_size, dim=0).unsqueeze(4)
s_j = (c_ij * u_hat).sum(dim=1, keepdim=True)
v_j = self.squash(s_j)
# print(f"b_ij at iteration {iteration} is equal to : {b_ij}")
if iteration < num_iterations - 1:
a_ij = torch.matmul(u_hat.transpose(3, 4), torch.cat([v_j] * self.num_routes, dim=1))
b_ij = b_ij + a_ij.squeeze(4).mean(dim=0, keepdim=True)
return v_j.squeeze(1)
def squash(self, input_tensor):
squared_norm = (input_tensor ** 2).sum(-1, keepdim=True)
output_tensor = squared_norm * input_tensor / ((1. + squared_norm) * torch.sqrt(squared_norm))
return output_tensor
class Decoder(nn.Module):
def __init__(self):
super(Decoder, self).__init__()
self.reconstraction_layers = nn.Sequential(
nn.Linear(16 * 10, 512),
nn.ReLU(inplace=True),
nn.Linear(512, 1024),
nn.ReLU(inplace=True),
nn.Linear(1024, 784),
nn.Sigmoid()
)
def forward(self, x, data):
classes = torch.sqrt((x ** 2).sum(2))
classes = F.softmax(classes, dim =1)
_, max_length_indices = classes.max(dim=1)
masked = Variable(torch.sparse.torch.eye(10))
if USE_CUDA:
masked = masked.cuda()
masked = masked.index_select(dim=0, index=max_length_indices.squeeze(1).data)
reconstructions = self.reconstraction_layers((x * masked[:, :, None, None]).view(x.size(0), -1))
reconstructions = reconstructions.view(-1, 1, 28, 28)
return reconstructions, masked
class CapsNet(nn.Module):
def __init__(self):
super(CapsNet, self).__init__()
self.conv_layer = ConvLayer()
self.primary_capsules = PrimaryCaps()
self.digit_capsules = DigitCaps()
self.decoder = Decoder()
self.mse_loss = nn.MSELoss()
def forward(self, data):
output = self.digit_capsules(self.primary_capsules(self.conv_layer(data)))
reconstructions, masked = self.decoder(output, data)
return output, reconstructions, masked
def loss(self, data, x, target, reconstructions):
return self.margin_loss(x, target) + self.reconstruction_loss(data, reconstructions)
# return self.reconstruction_loss(data, reconstructions)
def margin_loss(self, x, labels, size_average=True):
batch_size = x.size(0)
v_c = torch.sqrt((x**2).sum(dim=2, keepdim=True))
left = F.relu(0.9 - v_c).view(batch_size, -1)
right = F.relu(v_c - 0.1).view(batch_size, -1)
# print(f"shape of labels, left and right respectively - {labels.size(), left.size(), right.size()}")
loss = labels * left + 0.5 * (1.0 - labels) * right
loss = loss.sum(dim=1).mean()
return loss
def reconstruction_loss(self, data, reconstructions):
loss = self.mse_loss(reconstructions.view(reconstructions.size(0), -1), data.view(reconstructions.size(0), -1))
return loss*0.0005
capsule_net = CapsNet()
if USE_CUDA:
capsule_net = capsule_net.cuda()
optimizer = Adam(capsule_net.parameters())
capsule_net
##### Here is the problem while training####
batch_size = 100
mnist = Mnist(batch_size)
n_epochs = 5
for epoch in range(n_epochs):
capsule_net.train()
train_loss = 0
for batch_id, (data, target) in enumerate(mnist.train_loader):
target = torch.eye(10).index_select(dim=0, index=target)
data, target = Variable(data), Variable(target)
if USE_CUDA:
data, target = data.cuda(), target.cuda()
data, target = data.float().cuda(), target.float().cuda() # Here I changed the data to float and it's required only when I am using my extracted dataset for a single class
data = data[:,:,:] # Use this when 1st MNist data is used
# data = data[:,None,:,:] # Use this when I am using my extracted single class digits
optimizer.zero_grad()
output, reconstructions, masked = capsule_net(data)
loss = capsule_net.loss(data, output, target, reconstructions)
loss.backward()
optimizer.step()
train_loss += loss.item()
# if batch_id % 100 == 0:
# print ("train accuracy:", sum(np.argmax(masked.data.cpu().numpy(), 1) ==
# np.argmax(target.data.cpu().numpy(), 1)) / float(batch_size))
print (train_loss / len(mnist.train_loader))
I used this to see the main data as image and the reconstructed image
import matplotlib
import matplotlib.pyplot as plt
def plot_images_separately(images):
"Plot the six MNIST images separately."
fig = plt.figure()
for j in range(1, 10):
ax = fig.add_subplot(1, 10, j)
ax.matshow(images[j-1], cmap = matplotlib.cm.binary)
plt.xticks(np.array([]))
plt.yticks(np.array([]))
plt.show()
plot_images_separately(data[:10,0].data.cpu().numpy())
plot_images_separately(reconstructions[:10,0].data.cpu().numpy())
| I checked the normal performing code and then the problematic one, I found that the dataset passed into the network was of not same nature. The problems were -
The MNIST data extracted for a single class was not transformed into tensor and no normalization was applied, although I tried passing it through the transformation.
This is what I did to fix it -
I created transformation objections and tensor objection and then passed by list comprehension elements to it. Below are the codes and the final output of my network -
Preparing class 0 dataset (dataset for the digit 5)
class Mnist:
trans = transforms.ToTensor()
normalize = transforms.Normalize((0.1307,), (0.3081,))
def init(self,batch_size):
dataset_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
trans = transforms.ToTensor()
normalize = transforms.Normalize((0.1307,), (0.3081,))
train_mnist = datasets.MNIST("../data", train=True, transform=dataset_transform)
test_mnist = datasets.MNIST("../data", train= False, transform=dataset_transform)
train_image, train_label = train_mnist.train_data, train_mnist.train_labels
test_image, test_label = test_mnist.test_data, test_mnist.test_labels
train_0, test_0 = [normalize(trans(train_image[key].unsqueeze(2).numpy())) for (key, label) in enumerate(train_label) if int(label) == 5],[test_image[key] for (key, label) in enumerate(test_label) if int(label) == 5]
train_label_0, test_label_0 = zero__train = [train_label[key] for (key, label) in enumerate(train_label) if int(label) == 5],[test_label[key] for (key, label) in enumerate(test_label) if int(label) == 5]
train_dataset = tuple(zip(train_0, train_label_0))
test_dataset = tuple(zip(test_0, test_label_0))
self.train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
self.test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=True)
enter image description here
| https://stackoverflow.com/questions/54221434/ |
pytorch : unable to understand model.forward function | I am learning deep learning and am trying to understand the pytorch code given below. I'm struggling to understand how the probability calculation works. Can somehow break it down in lay-man terms. Thanks a ton.
ps = model.forward(images[0,:])
# Hyperparameters for our network
input_size = 784
hidden_sizes = [128, 64]
output_size = 10
# Build a feed-forward network
model = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),
nn.ReLU(),
nn.Linear(hidden_sizes[0], hidden_sizes[1]),
nn.ReLU(),
nn.Linear(hidden_sizes[1], output_size),
nn.Softmax(dim=1))
print(model)
# Forward pass through the network and display output
images, labels = next(iter(trainloader))
images.resize_(images.shape[0], 1, 784)
print(images.shape)
ps = model.forward(images[0,:])
| I'm a layman so I'll help you with the layman's terms :)
input_size = 784
hidden_sizes = [128, 64]
output_size = 10
These are parameters for the layers in your network. Each neural network consists of layers, and each layer has an input and an output shape.
Specifically input_size deals with the input shape of the first layer. This is the input_size of the entire network. Each sample that is input into the network will be a 1 dimension vector that is length 784 (array that is 784 long).
hidden_size deals with the shapes inside the network. We will cover this a little later.
output_size deals with the output shape of the last layer. This means that our network will output a 1 dimensional vector that is length 10 for each sample.
Now to break up model definition line by line:
model = nn.Sequential(nn.Linear(input_size, hidden_sizes[0]),
The nn.Sequential part simply defines a network, each argument that is input defines a new layer in that network in that order.
nn.Linear(input_size, hidden_sizes[0]) is an example of such a layer. It is the first layer of our network takes in an input of size input_size, and outputs a vector of size hidden_sizes[0]. The size of the output is considered "hidden" in that it is not the input or the output of the whole network. It "hidden" because it's located inside of the network far from the input and output ends of the network that you interact with when you actually use it.
This is called Linear because it applies a linear transformation by multiplying the input by its weights matrix and adding its bias matrix to the result. (Y = Ax + b, Y = output, x = input, A = weights, b = bias).
nn.ReLU(),
ReLU is an example of an activation function. What this function does is apply some sort of transformation to the output of the last layer (the layer discussed above), and outputs the result of that transformation. In this case the function being used is the ReLU function, which is defined as ReLU(x) = max(x, 0). Activation functions are used in neural networks because they create non-linearities. This allows your model to model non-linear relationships.
nn.Linear(hidden_sizes[0], hidden_sizes[1]),
From what we discussed above, this is a another example of a layer. It takes an input of hidden_sizes[0] (same shape as the output of the last layer) and outputs a 1D vector of length hidden_sizes[1].
nn.ReLU(),
Apples the ReLU function again.
nn.Linear(hidden_sizes[1], output_size)
Same as the above two layers, but our output shape is the output_size this time.
nn.Softmax(dim=1))
Another activation function. This activation function turns the logits outputted by nn.Linear into an actual probability distribution. This lets the model output the probability for each class. At this point our model is built.
# Forward pass through the network and display output
images, labels = next(iter(trainloader))
images.resize_(images.shape[0], 1, 784)
print(images.shape)
These are simply just preprocessing training data and putting it into the correct format
ps = model.forward(images[0,:])
This passes the images through the model (forward pass) and applies the operations previously discussed in layer. You get the resultant output.
| https://stackoverflow.com/questions/54239125/ |
What is the difference between MLP implementation from scratch and in PyTorch? | Following up the question from How to update the learning rate in a two layered multi-layered perceptron?
Given the XOR problem:
X = xor_input = np.array([[0,0], [0,1], [1,0], [1,1]])
Y = xor_output = np.array([[0,1,1,0]]).T
And a simple
two layered Multi-Layered Perceptron (MLP) with
sigmoid activations between them and
Mean Square Error (MSE) as the loss function/optimization criterion
If we train the model from scratch as such:
from itertools import chain
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(0)
def sigmoid(x): # Returns values that sums to one.
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(sx):
# See https://math.stackexchange.com/a/1225116
return sx * (1 - sx)
# Cost functions.
def mse(predicted, truth):
return 0.5 * np.mean(np.square(predicted - truth))
def mse_derivative(predicted, truth):
return predicted - truth
X = xor_input = np.array([[0,0], [0,1], [1,0], [1,1]])
Y = xor_output = np.array([[0,1,1,0]]).T
# Define the shape of the weight vector.
num_data, input_dim = X.shape
# Lets set the dimensions for the intermediate layer.
hidden_dim = 5
# Initialize weights between the input layers and the hidden layer.
W1 = np.random.random((input_dim, hidden_dim))
# Define the shape of the output vector.
output_dim = len(Y.T)
# Initialize weights between the hidden layers and the output layer.
W2 = np.random.random((hidden_dim, output_dim))
# Initialize weigh
num_epochs = 5000
learning_rate = 0.3
losses = []
for epoch_n in range(num_epochs):
layer0 = X
# Forward propagation.
# Inside the perceptron, Step 2.
layer1 = sigmoid(np.dot(layer0, W1))
layer2 = sigmoid(np.dot(layer1, W2))
# Back propagation (Y -> layer2)
# How much did we miss in the predictions?
cost_error = mse(layer2, Y)
cost_delta = mse_derivative(layer2, Y)
#print(layer2_error)
# In what direction is the target value?
# Were we really close? If so, don't change too much.
layer2_error = np.dot(cost_delta, cost_error)
layer2_delta = cost_delta * sigmoid_derivative(layer2)
# Back propagation (layer2 -> layer1)
# How much did each layer1 value contribute to the layer2 error (according to the weights)?
layer1_error = np.dot(layer2_delta, W2.T)
layer1_delta = layer1_error * sigmoid_derivative(layer1)
# update weights
W2 += - learning_rate * np.dot(layer1.T, layer2_delta)
W1 += - learning_rate * np.dot(layer0.T, layer1_delta)
#print(np.dot(layer0.T, layer1_delta))
#print(epoch_n, list((layer2)))
# Log the loss value as we proceed through the epochs.
losses.append(layer2_error.mean())
#print(cost_delta)
# Visualize the losses
plt.plot(losses)
plt.show()
We get a sharp dive in the loss from epoch 0 and then saturates quickly:
But if we train a similar model with pytorch, the training curve has a gradual drop in losses before saturating:
What is the difference between the MLP from scratch and the PyTorch code?
Why is it achieving convergence at different point?
Other than the weights initialization, np.random.rand() in the code from scratch and the default torch initialization, I can't seem to see a difference in the model.
Code for PyTorch:
from tqdm import tqdm
import numpy as np
import torch
from torch import nn
from torch import tensor
from torch import optim
import matplotlib.pyplot as plt
torch.manual_seed(0)
device = 'gpu' if torch.cuda.is_available() else 'cpu'
# XOR gate inputs and outputs.
X = xor_input = tensor([[0,0], [0,1], [1,0], [1,1]]).float().to(device)
Y = xor_output = tensor([[0],[1],[1],[0]]).float().to(device)
# Use tensor.shape to get the shape of the matrix/tensor.
num_data, input_dim = X.shape
print('Inputs Dim:', input_dim) # i.e. n=2
num_data, output_dim = Y.shape
print('Output Dim:', output_dim)
print('No. of Data:', num_data) # i.e. n=4
# Step 1: Initialization.
# Initialize the model.
# Set the hidden dimension size.
hidden_dim = 5
# Use Sequential to define a simple feed-forward network.
model = nn.Sequential(
# Use nn.Linear to get our simple perceptron.
nn.Linear(input_dim, hidden_dim),
# Use nn.Sigmoid to get our sigmoid non-linearity.
nn.Sigmoid(),
# Second layer neurons.
nn.Linear(hidden_dim, output_dim),
nn.Sigmoid()
)
model
# Initialize the optimizer
learning_rate = 0.3
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
# Initialize the loss function.
criterion = nn.MSELoss()
# Initialize the stopping criteria
# For simplicity, just stop training after certain no. of epochs.
num_epochs = 5000
losses = [] # Keeps track of the loses.
# Step 2-4 of training routine.
for _e in tqdm(range(num_epochs)):
# Reset the gradient after every epoch.
optimizer.zero_grad()
# Step 2: Foward Propagation
predictions = model(X)
# Step 3: Back Propagation
# Calculate the cost between the predictions and the truth.
loss = criterion(predictions, Y)
# Remember to back propagate the loss you've computed above.
loss.backward()
# Step 4: Optimizer take a step and update the weights.
optimizer.step()
# Log the loss value as we proceed through the epochs.
losses.append(loss.data.item())
plt.plot(losses)
| List of differences between hand-rolled code and PyTorch code
Turns out there are a lot of differences between what your hand-rolled code and the PyTorch code are doing. Here's what I uncovered, listed roughly in order of most to least impact on the output:
Your code and the PyTorch code use two different functions to report the loss.
Your code and the PyTorch code set up the initial weights very differently. You mention this in your question, but it turns out to have a pretty significant impact on the results.
By default, the torch.nn.Linear layers add an extra bunch of "bias" weights to the model. Thus, the 1st layer of the Pytorch model effectively has 3x5 weights and the second layer has 6x1 weights. The layers in the hand-rolled code have 2x5 and 5x1 weights, respectively.
The bias seems to help the model to learn and adapt somewhat faster. If you turn the bias off, it takes roughly twice as many training epochs for the Pytorch model to reach near 0 loss.
Curiously, it seems like the Pytorch model is using a learning rate that is effectively half of what you specify. Alternatively, it may be that there's a stray factor of 2 that's found its way into your hand-rolled math/code somewhere.
How to get identical results from the hand-rolled and Pytorch code
By carefully accounting for the above 4 factors, it is possible to achieve complete parity between the hand-rolled and the Pytorch code. With the correct tweaks and settings, the two snippets will produce identical results:
The most important tweak - make the loss reporting functions match
The critical difference is that you end up using two completely different functions to measure the loss in the two code snippets:
In the hand rolled code, you measure the loss as layer2_error.mean(). If you unpack the variable, you can see that layer2_error.mean() is a somewhat screwy and meaningless value:
layer2_error.mean()
== np.dot(cost_delta, cost_error).mean()
== np.dot(mse_derivative(layer2, Y), mse(layer2, Y)).mean()
== np.sum(.5 * (layer2 - Y) * ((layer2 - Y)**2).mean()).mean()
On the other hand, in the PyTorch code the loss is measured in terms of the traditional definition of the mse, ie as the equivalent of np.mean((layer2 - Y)**2). You can prove this to yourself by modifying your PyTorch loop like so:
def mse(x, y):
return np.mean((x - y)**2)
torch_losses = [] # Keeps track of the loses.
torch_losses_manual = [] # for comparison
# Step 2-4 of training routine.
for _e in tqdm(range(num_epochs)):
# Reset the gradient after every epoch.
optimizer.zero_grad()
# Step 2: Foward Propagation
predictions = model(X)
# Step 3: Back Propagation
# Calculate the cost between the predictions and the truth.
loss = criterion(predictions, Y)
# Remember to back propagate the loss you've computed above.
loss.backward()
# Step 4: Optimizer take a step and update the weights.
optimizer.step()
# Log the loss value as we proceed through the epochs.
torch_losses.append(loss.data.item())
torch_losses_manual.append(mse(predictions.detach().numpy(), Y.detach().numpy()))
plt.plot(torch_losses, lw=5, label='torch_losses')
plt.plot(torch_losses_manual, lw=2, label='torch_losses_manual')
plt.legend()
Output:
Also important - use the same initial weights
PyTorch uses it's own special routine for setting the initial weights which produces very different results from np.random.rand. I haven't been able to exactly replicate it yet, but for the next best thing we can just hijack Pytorch. Here's a function that will get the same initial weights that the Pytorch model uses:
import torch
from torch import nn
torch.manual_seed(0)
def torch_weights(nodes_in, nodes_hidden, nodes_out, bias=None):
model = nn.Sequential(
nn.Linear(nodes_in, nodes_hidden, bias=bias),
nn.Sigmoid(),
nn.Linear(nodes_hidden, nodes_out, bias=bias),
nn.Sigmoid()
)
return [t.detach().numpy() for t in model.parameters()]
Finally - in Pytorch, turn off all bias weights and double the learning rate
Eventually you may want to implement the bias weights in your own code. For now, we'll just turn the bias off in the Pytorch model and compare the results of the hand-rolled model to those of the unbiased Pytorch model.
Also, in order to make the results match you need to double the Pytorch model's learning rate. This effectively scales the results along the x axis (ie doubling the rate means that it takes half as many epochs to reach some particular feature on the loss curve).
Putting it together
In order to reproduce the hand_rolled_losses data from the plot at the start of my post, all you need to do is take your hand-rolled code and replace the mse function with:
def mse(predicted, truth):
return np.mean(np.square(predicted - truth))
the lines that initialize the weights with:
W1,W2 = [w.T for w in torch_weights(input_dim, hidden_dim, output_dim)]
and the line that tracks the losses with:
losses.append(cost_error)
and you should be good to go.
In order to reproduce the torch_losses data from the plot we'll also need to turn the bias weights off in the Pytorch model. To do that, you just need to change the lines defining the Pytorch model like so:
model = nn.Sequential(
# Use nn.Linear to get our simple perceptron.
nn.Linear(input_dim, hidden_dim, bias=None),
# Use nn.Sigmoid to get our sigmoid non-linearity.
nn.Sigmoid(),
# Second layer neurons.
nn.Linear(hidden_dim, output_dim, bias=None),
nn.Sigmoid()
)
You also need to change the line defining the learning_rate:
learning_rate = 0.3 * 2
Complete code listing
The hand-rolled code
Here's a complete listing of my version of the hand-rolled neural net code, to help with reproducing my results:
from itertools import chain
import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import scipy.stats
import torch
from torch import nn
np.random.seed(0)
torch.manual_seed(0)
def torch_weights(nodes_in, nodes_hidden, nodes_out, bias=None):
model = nn.Sequential(
nn.Linear(nodes_in, nodes_hidden, bias=bias),
nn.Sigmoid(),
nn.Linear(nodes_hidden, nodes_out, bias=bias),
nn.Sigmoid()
)
return [t.detach().numpy() for t in model.parameters()]
def sigmoid(x): # Returns values that sums to one.
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(sx):
# See https://math.stackexchange.com/a/1225116
return sx * (1 - sx)
# Cost functions.
def mse(predicted, truth):
return np.mean(np.square(predicted - truth))
def mse_derivative(predicted, truth):
return predicted - truth
X = xor_input = np.array([[0,0], [0,1], [1,0], [1,1]])
Y = xor_output = np.array([[0,1,1,0]]).T
# Define the shape of the weight vector.
num_data, input_dim = X.shape
# Lets set the dimensions for the intermediate layer.
hidden_dim = 5
# Define the shape of the output vector.
output_dim = len(Y.T)
W1,W2 = [w.T for w in torch_weights(input_dim, hidden_dim, output_dim)]
num_epochs = 5000
learning_rate = 0.3
losses = []
for epoch_n in range(num_epochs):
layer0 = X
# Forward propagation.
# Inside the perceptron, Step 2.
layer1 = sigmoid(np.dot(layer0, W1))
layer2 = sigmoid(np.dot(layer1, W2))
# Back propagation (Y -> layer2)
# In what direction is the target value?
# Were we really close? If so, don't change too much.
cost_delta = mse_derivative(layer2, Y)
layer2_delta = cost_delta * sigmoid_derivative(layer2)
# Back propagation (layer2 -> layer1)
# How much did each layer1 value contribute to the layer2 error (according to the weights)?
layer1_error = np.dot(layer2_delta, W2.T)
layer1_delta = layer1_error * sigmoid_derivative(layer1)
# update weights
W2 += - learning_rate * np.dot(layer1.T, layer2_delta)
W1 += - learning_rate * np.dot(layer0.T, layer1_delta)
# Log the loss value as we proceed through the epochs.
losses.append(mse(layer2, Y))
# Visualize the losses
plt.plot(losses)
plt.show()
The Pytorch code
import matplotlib.pyplot as plt
from tqdm import tqdm
import numpy as np
import torch
from torch import nn
from torch import tensor
from torch import optim
torch.manual_seed(0)
device = 'gpu' if torch.cuda.is_available() else 'cpu'
num_epochs = 5000
learning_rate = 0.3 * 2
# XOR gate inputs and outputs.
X = tensor([[0,0], [0,1], [1,0], [1,1]]).float().to(device)
Y = tensor([[0],[1],[1],[0]]).float().to(device)
# Use tensor.shape to get the shape of the matrix/tensor.
num_data, input_dim = X.shape
num_data, output_dim = Y.shape
# Step 1: Initialization.
# Initialize the model.
# Set the hidden dimension size.
hidden_dim = 5
# Use Sequential to define a simple feed-forward network.
model = nn.Sequential(
# Use nn.Linear to get our simple perceptron.
nn.Linear(input_dim, hidden_dim, bias=None),
# Use nn.Sigmoid to get our sigmoid non-linearity.
nn.Sigmoid(),
# Second layer neurons.
nn.Linear(hidden_dim, output_dim, bias=None),
nn.Sigmoid()
)
# Initialize the optimizer
optimizer = optim.SGD(model.parameters(), lr=learning_rate)
# Initialize the loss function.
criterion = nn.MSELoss()
def mse(x, y):
return np.mean((x - y)**2)
torch_losses = [] # Keeps track of the loses.
torch_losses_manual = [] # for comparison
# Step 2-4 of training routine.
for _e in tqdm(range(num_epochs)):
# Reset the gradient after every epoch.
optimizer.zero_grad()
# Step 2: Foward Propagation
predictions = model(X)
# Step 3: Back Propagation
# Calculate the cost between the predictions and the truth.
loss = criterion(predictions, Y)
# Remember to back propagate the loss you've computed above.
loss.backward()
# Step 4: Optimizer take a step and update the weights.
optimizer.step()
# Log the loss value as we proceed through the epochs.
torch_losses.append(loss.data.item())
torch_losses_manual.append(mse(predictions.detach().numpy(), Y.detach().numpy()))
plt.plot(torch_losses, lw=5, c='C1', label='torch_losses')
plt.plot(torch_losses_manual, lw=2, c='C2', label='torch_losses_manual')
plt.legend()
Notes
Bias weights
You can find some very instructive examples that show what the bias weights are and how to implement them in this tutorial. They list a bunch of pure-Python implementations of neural nets very similar to your hand-rolled one, so it's likely you could adapt some of their code to make your own implementation of the bias.
Functions to produce an initial guess of the weights
Here's a function I adapted from that same tutorial that can produce reasonable initial values for the weights. I think the algorithm Pytorch uses internally is somewhat different, but this produces similar results:
import scipy as sp
import scipy.stats
def tnorm_weights(nodes_in, nodes_out, bias_node=0):
# see https://www.python-course.eu/neural_network_mnist.php
wshape = (nodes_out, nodes_in + bias_node)
bound = 1 / np.sqrt(nodes_in)
X = sp.stats.truncnorm(-bound, bound)
return X.rvs(np.prod(wshape)).reshape(wshape)
| https://stackoverflow.com/questions/54247143/ |
Model parameter initialization | I am new to PyTorch. I am writing a simple program for linear regression and i want to compare the results by using different methods (SGD,momentum,ADAM,etc). The problem I have is that I want every time a loop ends for the model parameters to be reinitialized to the same value that the previous model started with so the comparison is valid.
This is what i have so far, this is my training data:
x1=np.arange(0,10,1).reshape(10,1)
y1=2*x1+1+np.random.normal(0,1,(10,1))
x=torch.from_numpy(x1)
y=torch.from_numpy(y1)
Here i train the data
from torch.utils.data import TensorDataset,DataLoader
train=TensorDataset(xdata,ydata)
size_batch=10
dl=DataLoader(train,size_batch,shuffle=True)
Define the model and opt
model=nn.Linear(1,1)
opt=torch.optim.SGD(model.parameters(), lr=1e-4)
import torch.nn.functional as F
loss1=F.mse_loss
loss=loss1(model(x),y)
Function
def fitmodel(nepochs, model, loss1, opt):
for epoch in range(nepochs):
for xm,ym in dl:
predict = model(xm)
loss = loss1(predict, ym)
loss.backward()
opt.step()
opt.zero_grad()
Call the function
fitmodel(1000,model,loss1,opt)
Now i want to rerun the above but for different optimization algorithms. If I just rerun fitmodel it will use some of the parameters it already has calculated. I want to start from the same 'initial conditions' as i started the previous run. Anyone has any ideas how to do that?
Edit
Before i run the fitmodel I copy the initial bias and weight
w1=model.weight
b1=model.bias
fitmodel(1000,model,loss1,opt)
model.weight=w1
model.bias=b1
loss=[]
But i get this error:
TypeError: cannot assign 'list' as parameter 'bias' (torch.nn.Parameter or None expected)
| The parameters of a linear layer are stored in model.weight and model.bias. You need to copy those before training, and then restore afterwards. This is a bit more involved than what you're doing in your code. Example below
# clone and detach so that we have an actual backup copy,
# not merely a reference to the parameters
w1=model.weight.clone().detach()
b1=model.bias.clone().detach()
for i in range(3): # as many experiments as you wish to run
# since we have detached, w1 and b1 are no longer nn.Parameter -
# we have to rewrap them. We keep copying so that the tensors used
# in the computation are separate from the backup copies
model.weight=nn.Parameter(w1.clone())
model.bias=nn.Parameter(b1.clone())
# we reinitialize the optimizer because it looks at model.parameters()
# if not for this line, it would try to optimize the values from
# the previous experiment!
opt=torch.optim.SGD(model.parameters(), lr=1e-4)
fitmodel(1000,model,loss1,opt)
| https://stackoverflow.com/questions/54248646/ |
how to multiply all rows by column of single matrix in pytorch in a vectorized way | I need to multiply all rows of a matrix by column, i think with an example it will be clearer:
matrix is:
1,2,3
4,5,6
7,8,9
An i need an operation that returns:
28,80,162
But i can't find anything in the documentation and blogs and other SO question only are related to matrix multiplication and dot product, which is not what i need in this case,how can it be achieved in a vectorized fashion(instead of for loop based) ?
For example this is easy to achieve for the case of sum like:
the_matrix.sum(dim=0)
But there's not something like:
the_matrix.mul(dim=0)
| I found the solution, there's no :
the_matrix.mul(dim=0)
But there's:
he_matrix.prod(dim=0)
Which does exactly what is needed.
| https://stackoverflow.com/questions/54249399/ |
Pytorch mask missing values when calculating rmse | I'm trying to calculate the rmse error of two torch tensors. I would like to ignore/mask the rows where the labels are 0 (missing values). How could I modify this line to take that restriction into account?
torch.sqrt(((preds.detach() - labels) ** 2).mean()).item()
Thank you in advance.
| This can be solved by defining a custom MSE loss function* that masks out the missing values, 0 in your case, from both the input and target tensors:
def mse_loss_with_nans(input, target):
# Missing data are nan's
# mask = torch.isnan(target)
# Missing data are 0's
mask = target == 0
out = (input[~mask]-target[~mask])**2
loss = out.mean()
return loss
(*) Computing MSE is equivalent to RMSE from an optimisation point of view -- with the advantage of being computationally faster.
| https://stackoverflow.com/questions/54249737/ |
How Weight update in Dynamic Computation Graph of pytorch works? | How does the Weight Update works in Pytorch code of Dynamic Computation Graph when Weights are shard (=reused multiple times)
https://pytorch.org/tutorials/beginner/examples_nn/dynamic_net.html#sphx-glr-beginner-examples-nn-dynamic-net-py
import random
import torch
class DynamicNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
"""
In the constructor we construct three nn.Linear instances that we will use
in the forward pass.
"""
super(DynamicNet, self).__init__()
self.input_linear = torch.nn.Linear(D_in, H)
self.middle_linear = torch.nn.Linear(H, H)
self.output_linear = torch.nn.Linear(H, D_out)
def forward(self, x):
"""
For the forward pass of the model, we randomly choose either 0, 1, 2, or 3
and reuse the middle_linear Module that many times to compute hidden layer
representations.
Since each forward pass builds a dynamic computation graph, we can use normal
Python control-flow operators like loops or conditional statements when
defining the forward pass of the model.
Here we also see that it is perfectly safe to reuse the same Module many
times when defining a computational graph. This is a big improvement from Lua
Torch, where each Module could be used only once.
"""
h_relu = self.input_linear(x).clamp(min=0)
for _ in range(random.randint(0, 3)):
h_relu = self.middle_linear(h_relu).clamp(min=0)
y_pred = self.output_linear(h_relu)
return y_pred
I want to know what happens to middle_linear weight at each backward which is used multiple times at a step
| When you call backward (either as the function or a method on a tensor) the gradients of operands with requires_grad == True are calculated with respect to the tensor you called backward on. These gradients are accumulated in the .grad property of these operands. If the same operand A appears multiple times in the expression, you can conceptually treat them as separate entities A1, A2... for the backpropagation algorithm and just at the end sum their gradients so that A.grad = A1.grad + A2.grad + ....
Now, strictly speaking, the answer to your question
I want to know what happens to middle_linear weight at each backward
is: nothing. backward does not change weights, only calculates the gradient. To change the weights you have to do an optimization step, perhaps using one of the optimizers in torch.optim. The weights are then updated according to their .grad property, so if your operand was used multiple times, it will be updated accordingly to the sum of the gradients in each of its uses.
In other words, if your matrix element x has positive gradient when first applied and negative when used the second time, it may be that the net effects will cancel out and it will stay as it is (or change just a bit). If both applications call for x to be higher, it will raise more than if it was used just once, etc.
| https://stackoverflow.com/questions/54250651/ |
Pytorch errors: "received an invalid combination of arguments" in Jupyter Notebook | I'm trying to learn Pytorch, but whenever I seem to try any online tutorial (https://pytorch.org/tutorials/beginner/blitz/tensor_tutorial.html#sphx-glr-beginner-blitz-tensor-tutorial-py), I get errors when trying to run certain functions, but only in Jupyter Notebook.
When running
x = torch.empty(5, 3)
I get an error:
module 'torch' has no attribute 'empty'
Furthermore, when running
x = torch.zeros(5, 3, dtype=torch.long)
I get the error:
module 'torch' has no attribute 'long'
Some other functions work fine like:
x = torch.rand(5, 3)
But generally, most code I try to run seems to run into an error really quickly. I couldn't find any resolution online.
When I go into my docker container and simply run python in the shell, I can run these lines just fine with no errors.
I'm running pytorch in a Docker image that I extended from a fastai image, as it already included things like jupyter notebook and pytorch. I used anaconda to update everything, and committed it to a new image for myself.
I have absolutely no idea what the issue could be. I've tried updating packages through anaconda, pip, aptitude in my docker container, and making sure to commit my changes, but nothing seems to work. I also tried creating a new kernel with python 3.7 as I noticed that my Jupyter Notebook only runs in 3.6.4, and when I run python in the shell it is at 3.7.
I've also tried getting different docker images and extending them with what I need, but all images that I've tried have had errors with anaconda where it gets stuck on "Solving environment" step.
| Ok, so the fix for me was to either update pytorch through conda using the following command
conda update pytorch
If it's not installed yet, I've gotten it to work in other environments by simply installing it through conda
conda install pytorch
Kind of stupid that I didn't try this earlier, but I was confused on the difference between conda and pip.
| https://stackoverflow.com/questions/54257695/ |
How to look at the parameters of a pytorch model? | I have a simple pytorch neural net that I copied from openai, and I modified it to some extent (mostly the input).
When I run my code, the output of the network remains the same on every episode, as if no training occurs.
I want to see if any training happens, or if some other reason causes the results to be the same.
How can I make sure any movement happens to the weights?
Thanks
| Depends on what you are doing, but the easiest would be to check the weights of your model.
You can do this (and compare with the ones from previous iteration) using the following code:
for parameter in model.parameters():
print(parameter.data)
If the weights are changing, the neural network is being optimized (which doesn't necessarily mean it learns anything useful in particular).
| https://stackoverflow.com/questions/54259943/ |
How does the parameter 'dim' in torch.unique() work? | I am trying to extract the unique values in each row of a matrix and returning them into the same matrix (with repeated values set to say, 0) For example, I would like to transform
torch.Tensor(([1, 2, 3, 4, 3, 3, 4],
[1, 6, 3, 5, 3, 5, 4]])
to
torch.Tensor(([1, 2, 3, 4, 0, 0, 0],
[1, 6, 3, 5, 0, 0, 4]])
or
torch.Tensor(([1, 2, 3, 4, 0, 0, 0],
[1, 6, 3, 5, 4, 0, 0]])
I.e. the order does not matter in the rows. I have tried using pytorch.unique() and in the documentation it is mentioned that the dimension to take the unique values can be specified with the parameter dim. However, It doesn't seem to work for this case.
I've tried:
output= torch.unique(torch.Tensor([[4,2,52,2,2],[5,2,6,6,5]]), dim = 1)
output
Which gives
tensor([[ 2., 2., 2., 4., 52.],
[ 2., 5., 6., 5., 6.]])
Does anyone have a particular fix for this? If possible, I'm trying to avoid for loops.
| One must admit the unique function can sometimes be very confusing without given proper examples and explanations.
The dim parameter specifies which dimension on the matrix tensor you want to apply on.
For instance, in a 2D matrix, dim=0 will let operation perform vertically where dim=1 means horizontally.
Example, let's consider a 4x4 matrix with dim=1. As you can see from my code below, the unique operation is applied row by row.
You notice the double occurrence of the number 11 in the first and last row. Numpy and Torch does this to preserve the shape of the final matrix.
However, if you do not specify any dimension, torch will automatically flatten your matrix and then apply unique to it and you will get a 1D array that contains unique data.
import torch
m = torch.Tensor([
[11, 11, 12,11],
[13, 11, 12,11],
[16, 11, 12, 11],
[11, 11, 12, 11]
])
output, indices = torch.unique(m, sorted=True, return_inverse=True, dim=1)
print("Ori \n{}".format(m.numpy()))
print("Sorted \n{}".format(output.numpy()))
print("Indices \n{}".format(indices.numpy()))
# without specifying dimension
output, indices = torch.unique(m, sorted=True, return_inverse=True)
print("Sorted (no dim) \n{}".format(output.numpy()))
Result (dim=1)
Ori
[[11. 11. 12. 11.]
[13. 11. 12. 11.]
[16. 11. 12. 11.]
[11. 11. 12. 11.]]
Sorted
[[11. 11. 12.]
[11. 13. 12.]
[11. 16. 12.]
[11. 11. 12.]]
Indices
[1 0 2 0]
Result (no dimension)
Sorted (no dim)
[11. 12. 13. 16.]
| https://stackoverflow.com/questions/54262689/ |
How to convert a pytorch tensor into a numpy array? | How do I convert a torch tensor to numpy?
| copied from pytorch doc:
a = torch.ones(5)
print(a)
tensor([1., 1., 1., 1., 1.])
b = a.numpy()
print(b)
[1. 1. 1. 1. 1.]
Following from the below discussion with @John:
In case the tensor is (or can be) on GPU, or in case it (or it can) require grad, one can use
t.detach().cpu().numpy()
I recommend to uglify your code only as much as required.
| https://stackoverflow.com/questions/54268029/ |
Strange behavior of linear regression in PyTorch | I am facing a peculiar problem and I was wondering if there is an explanation. I am trying to run a linear regression problem and test different optimization methods and two of them have a strange outcome when comparing to each other. I build a data set that satisfies y=2x+5 and I add a random noise to that.
xtrain=np.range(0,50,1).reshape(50,1)
ytrain=2*train+5+np.random.normal(0,2,(50,1))
opt1=torch.optim.SGD(model.parameters(),lr=1e-5,momentum=0.8))
opt2=torch.optim.Rprop(model.parameters(),lr=1e-5)
F_loss=F.mse_loss
from torch.utils.data import TensorDataset,DataLoader
train_d=TensorDataset(xtrain,ytrain)
train=DataLoader(train_d,50,shuffle=True)
model1=nn.Linear(1,1)
loss=F_loss(model1(xtrain),ytrain)
def fit(nepoch, model1, F_loss, opt):
for epoch in range(nepoch):
for i,j in train:
predict = model1(i)
loss = F_loss(predict, j)
loss.backward()
opt.step()
opt.zero_grad()
When i compare the results of the following commands:
fit(500000, model1, F_loss, opt1)
fit(500000, model1, F_loss, opt2)
In the last epoch for opt1:loss=2.86,weight=2.02,bias=4.46
In the last epoch for opt2:loss=3.47,weight=2.02,bias=4.68
These results do not make sense to me, shouldn't opt2 have a smaller loss than opt1 since the weight and bias it finds is closer to the real value? opt2's method finds weights and biases to be closer to the real value (they are respectively 2 and 5). Am i doing something wrong?
| This has to do with the fact that you are drawing the training samples themselves from a random distribution.
By doing so, you inherently randomized the ground truth to some extent. Sure, you will get values that are inherently distributed around 2x+5, but you do not guarantee that 2x+5 will also be the best fit to this data distribution.
It could thus happen that you accidentally end up with values that deviate quite significantly from the original function, and, since you use a mean squared error, these values get weighted quite significantly.
In expectation (i.e., for the number of samples going towards infinity), you will likely get closer and closer to the expected parameters.
A way to verify this would be to plot your training samples against the parameter set, as well as the (ideal) underlying function.
Also note that Linear Regression does have a direct solution - something that is very uncommon in Machine Learning - meaning you can directly calculate an optimal solution, e.g., with sklearn's function
| https://stackoverflow.com/questions/54273680/ |
RuntimeError: PyTorch does not currently provide packages for PyPI | I'm trying to run this https://github.com/shariqiqbal2810/MAAC repository and it has a module called torch
import torch as McLawrence
from torch.autograd import Variable
I'm using python version 3.7.1 and I downgraded to 3.6.5 on win10
I tried to use
pip install torch
pip install pytorch
pip install torchvision
I change torch to pytorch
I enter their website https://pytorch.org/ and I tried all suggestion that uses pip such as
pip3 install https://download.pytorch.org/whl/cu80/torch-1.0.0-cp36-cp36m-win_amd64.whl
pip3 install torchvision
I read every comment relate to this issue in
https://github.com/pytorch/pytorch/issues/566
I read most of the answer here
https://stackoverflow.com/search?q=module+named+torch
But I still get the same message:
Collecting torch
Using cached https://files.pythonhosted.org/packages/5f/e9/bac4204fe9cb1a002ec6140b47f51affda1655379fe302a1caef421f9846/torch-0.1.2.post1.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\iibra\AppData\Local\Temp\pip-install-yupbt_qk\torch\setup.py", line 11, in <module>
raise RuntimeError(README)
RuntimeError: PyTorch does not currently provide packages for PyPI (see status at https://github.com/pytorch/pytorch/issues/566).
Please follow the instructions at http://pytorch.org/ to install with miniconda instead.
pip install pytorch
Collecting pytorch
Using cached https://files.pythonhosted.org/packages/a9/41/4487bc23e3ac4d674943176f5aa309427b011e00607eb98899e9d951f67b/pytorch-0.1.2.tar.gz
Building wheels for collected packages: pytorch
Running setup.py bdist_wheel for pytorch ... error
Complete output from command c:\users\iibra\appdata\local\programs\python\python36\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\iibra\\AppData\\Local\\Temp\\pip-install-7qwe1571\\pytorch\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\iibra\AppData\Local\Temp\pip-wheel-_mjh_olk --python-tag cp36:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\iibra\AppData\Local\Temp\pip-install-7qwe1571\pytorch\setup.py", line 17, in <module>
raise Exception(message)
Exception: You should install pytorch from http://pytorch.org
pip install torchvision
Collecting torchvision
Using cached https://files.pythonhosted.org/packages/ca/0d/f00b2885711e08bd71242ebe7b96561e6f6d01fdb4b9dcf4d37e2e13c5e1/torchvision-0.2.1-py2.py3-none-any.whl
Requirement already satisfied: six in c:\users\iibra\appdata\local\programs\python\python36\lib\site-packages (from torchvision) (1.11.0)
Requirement already satisfied: pillow>=4.1.1 in c:\users\iibra\appdata\local\programs\python\python36\lib\site-packages (from torchvision) (5.1.0)
Collecting torch (from torchvision)
Using cached https://files.pythonhosted.org/packages/5f/e9/bac4204fe9cb1a002ec6140b47f51affda1655379fe302a1caef421f9846/torch-0.1.2.post1.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\iibra\AppData\Local\Temp\pip-install-k8dl2vhz\torch\setup.py", line 11, in <module>
raise RuntimeError(README)
RuntimeError: PyTorch does not currently provide packages for PyPI (see status at https://github.com/pytorch/pytorch/issues/566).
Please follow the instructions at http://pytorch.org/ to install with miniconda instead.
| Installing from the PyTorch wheel should have worked. But, the problem turns out to be that pip is using the cached pytorch to install it as mentioned on GitHub here.
Collecting pytorch
Using cached https://files.pythonhosted.org/packages...
Either removing the pip's cache from %LocalAppData%\pip\Cache on Windows or disabling it by using --no-cache-dir would solve the issue as follows:
pip3 --no-cache-dir install https://download.pytorch.org/whl/cu80/torch-1.0.0-cp36-cp36m-win_amd64.whl
| https://stackoverflow.com/questions/54274089/ |
Applying any optimization causes values to be NaN | I am working on a classifier model for this data set:
https://archive.ics.uci.edu/ml/datasets/ILPD+%28Indian+Liver+Patient+Dataset%29
and I have come up with this code in pytorch:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
ILPDataset = pd.read_csv('preprocessed-ilpd.csv')
ILPDataset["Age"] = pd.to_numeric(ILPDataset["Age"])
LabelEncoder = preprocessing.LabelEncoder()
LabelEncoder.fit(ILPDataset["Gender"])
ILPDataset["Gender"] = LabelEncoder.transform(ILPDataset["Gender"])
print(ILPDataset["Gender"].describe())
ILPDataset["AAP"] = preprocessing.scale(ILPDataset["AAP"])
ILPDataset["SgAlAm"] = preprocessing.scale(ILPDataset["SgAlAm"])
ILPDataset["SgApAm"] = preprocessing.scale(ILPDataset["SgApAm"])
Features = ["Age","Gender","TB","DB","AAP","SgAlAm","SgApAm","TP","ALB","A/G"]
ILPDFeatures = ILPDataset[Features]
ILPDTarget = ILPDataset["Selector"]
X_Train, X_Test, Y_Train, Y_Test = train_test_split(ILPDFeatures,ILPDTarget,test_size=0.2,random_state=0)
print(X_Train.shape)
print(Y_Train.shape)
print(X_Test.shape)
print(Y_Test.shape)
torch.set_default_tensor_type(torch.DoubleTensor)
TrainX = torch.from_numpy(X_Train.values).double()
TestX = torch.from_numpy(X_Test.values).double()
TrainY = torch.from_numpy(Y_Train.values).long().view(1,-1)[0]
TestY = torch.from_numpy(Y_Test.values).long().view(1,-1)[0]
TrainY.reshape(TrainY.shape[0],1)
TestY.reshape(TestY.shape[0],1)
print(X_Train.shape[1])
input_layers = X_Train.shape[1]
output_layers = 2
hidden = 100
class Net(nn.Module):
def __init__(self):
super(Net,self).__init__()
self.fc1 = nn.Linear(input_layers,hidden)
self.fc2 = nn.Linear(hidden,hidden)
self.fc3 = nn.Linear(hidden,output_layers)
def forward(self,x):
x = torch.sigmoid(self.fc1(x))
x = torch.sigmoid(self.fc2(x))
x = self.fc3(x)
return F.softmax(x,dim=-1)
model = Net()
optimizer = torch.optim.SGD(model.parameters(),lr = 0.0001,momentum = 0.9)
loss_fn = nn.NLLLoss()
epochs_data = []
epochs = 601
print(TrainX.shape)
print(TestY.shape)
for epoch in range(1,3):
optimizer.zero_grad()
Ypred = model(TrainX)
loss = loss_fn(Ypred,TrainY)
loss.backward()
optimizer.step()
print(Ypred)
if epoch%100==0:
print("Epoch - %d, (%d%%) "%(epoch,epoch/epochs*100))
YPred_Test = model(TestX)
Loss_Test = loss_fn(YPred_Test,TestY)
print(Loss_Test.item())
print(YPred_Test)
print(YPred_Test)
print(TestY)
I have used different optimizers with different LRs and Momentum but on applying each one of them after loss.backward(), it turns the values in the tensor to NaN. I looked up the different answers on SO but even after trying them out I couldn't solve the bug.
| The problem is caused by not normalizing every column in the dataset. I have no idea why but normalizing column will solve the problem.
| https://stackoverflow.com/questions/54275436/ |
What's the difference between torch.stack() and torch.cat() functions? | OpenAI's REINFORCE and actor-critic example for reinforcement learning has the following code:
REINFORCE:
policy_loss = torch.cat(policy_loss).sum()
actor-critic:
loss = torch.stack(policy_losses).sum() + torch.stack(value_losses).sum()
One is using torch.cat, the other uses torch.stack, for similar use cases.
As far as my understanding goes, the doc doesn't give any clear distinction between them.
I would be happy to know the differences between the functions.
| stack
Concatenates sequence of tensors along a new dimension.
cat
Concatenates the given sequence of seq tensors in the given dimension.
So if A and B are of shape (3, 4):
torch.cat([A, B], dim=0) will be of shape (6, 4)
torch.stack([A, B], dim=0) will be of shape (2, 3, 4)
| https://stackoverflow.com/questions/54307225/ |
Pytorch median - is it bug or am I using it wrong | I am trying to get median of each row of 2D torch.tensor. But the result is not what I expect when compared to working with standard array or numpy
import torch
import numpy as np
from statistics import median
print(torch.__version__)
>>> 0.4.1
y = [[1, 2, 3, 5, 9, 1],[1, 2, 3, 5, 9, 1]]
median(y[0])
>>> 2.5
np.median(y,axis=1)
>>> array([2.5, 2.5])
yt = torch.tensor(y,dtype=torch.float32)
yt.median(1)[0]
>>> tensor([2., 2.])
| Looks like this is the intended behaviour of Torch as mentioned in this issue
https://github.com/pytorch/pytorch/issues/1837
https://github.com/torch/torch7/pull/182
The reasoning as mentioned in the link above
Median returns 'middle' element in case of odd-many elements, otherwise one-before-middle element (could also do the other convention to take mean of the two around-the-middle elements, but that would be twice more expensive, so I decided for this one).
| https://stackoverflow.com/questions/54310861/ |
Update step in PyTorch implementation of Newton's method | I'm trying to get some insight into how PyTorch works by implementing Newton's method for solving x = cos(x). Here's a version that works:
x = Variable(DoubleTensor([1]), requires_grad=True)
for i in range(5):
y = x - torch.cos(x)
y.backward()
x = Variable(x.data - y.data/x.grad.data, requires_grad=True)
print(x.data) # tensor([0.7390851332151607], dtype=torch.float64) (correct)
This code seems inelegant (inefficient?) to me since it's recreating the entire computational graph during each step of the for loop (right?). I tried to avoid this by simply updating the data held by each of the variables instead of recreating them:
x = Variable(DoubleTensor([1]), requires_grad=True)
y = x - torch.cos(x)
y.backward(retain_graph=True)
for i in range(5):
x.data = x.data - y.data/x.grad.data
y.data = x.data - torch.cos(x.data)
y.backward(retain_graph=True)
print(x.data) # tensor([0.7417889255761136], dtype=torch.float64) (wrong)
Seems like, with DoubleTensors, I'm carrying enough digits of precision to rule out round-off error. So where's the error coming from?
Possibly related: The above snippet breaks without the retain_graph=True flag set at every step if the for loop. The error message I get if I omit it within the loop --- but retain it on line 3 --- is:
RuntimeError: Trying to backward through the graph a second time, but the buffers have already been freed. Specify retain_graph=True when calling backward the first time. This seems like evidence that I'm misunderstanding something...
| I think your first version of code is optimal, meaning that it is not creating a computation graph on every run.
# initial guess
guess = torch.tensor([1], dtype=torch.float64, requires_grad = True)
# function to optimize
def my_func(x):
return x - torch.cos(x)
def newton(func, guess, runs=5):
for _ in range(runs):
# evaluate our function with current value of `guess`
value = my_func(guess)
value.backward()
# update our `guess` based on the gradient
guess.data -= (value / guess.grad).data
# zero out current gradient to hold new gradients in next iteration
guess.grad.data.zero_()
return guess.data # return our final `guess` after 5 updates
# call starts
result = newton(my_func, guess)
# output of `result`
tensor([0.7391], dtype=torch.float64)
In each run, our function my_func(), which defines the computation graph, is evaluated with the current guess value. Once that returns the result, we compute the gradient (with value.backward() call). With this gradient, we now update our guess and zero-out our gradients so that it will be afresh for holding the gradients the next time we call value.backward() (i.e. it stops accumulating the gradient; without zeroing out the gradient, it would by default starts accumulating the gradients. But, we want to avoid that behaviour here).
| https://stackoverflow.com/questions/54316053/ |
Size mismatch error with PyTorch toturial | I am learning the tutorial called Deep Learning with PyTorch: A 60 Minute Blitz on PyTorch website. My codes are the same as those of it, but there is a size mismatch error as shown below. Could anyone tell me why and how to solve it? Thank you:)
RuntimeError: size mismatch, m1: [80 x 5], m2: [400 x 120] at
c:\a\w\1\s\tmp_conda_3.7_110509\conda\conda-bld\pytorch_1544094576194\work\aten\src\th\generic/THTensorMath.cpp:940
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net,self).__init__()
self.conv1=nn.Conv2d(1,6,5)
self.conv2=nn.Conv2d(6,16,5)
self.fc1=nn.Linear(16*5*5,120)
self.fc2=nn.Linear(120,84)
self.fc3=nn.Linear(84,10)
def forward(self,x):
x=F.max_pool2d(F.relu(self.conv1(x)),(2,2))
x=F.max_pool2d(F.relu(self.conv2(x)),2)
x.view(-1,self.num_flat_features(x))
x=F.relu(self.fc1(x))
x=F.relu(self.fc2(x))
x=self.fc3(x)
return x
def num_flat_features(self,x):
size=x.size()[1:]
num_features=1
for s in size:
num_features*=s
return num_features
net=Net()
input=torch.randn(1,1,32,32)
out=net(input)
print(out)
| Sorry for disturbance, I find the mistake. I missed x= in x=x.view(-1,self.num_flat_features(x))...
| https://stackoverflow.com/questions/54319419/ |
PIL image resize change the value of pixel? | I want to resize an PIL image without changing the pixel value range.
I have tried the Image.resize() but it changes my pixel value range from [0,255] to [79,179]
I'm using Python and PyTorch, in PyTorch, the transforms.resize() will implement Image.resize()
Here is the test code I used
a = torch.randint(0,255,(500,500), dtype=torch.uint8)
print(a.size())
print(torch.max(a))
a = torch.unsqueeze(a, dim =0)
print(a.size())
compose = transforms.Compose([transforms.ToPILImage(),transforms.Resize((128,128))])
a_trans = compose(a)
print(a_trans.size)
print(a_trans.getextrema())
The output of the code is:
torch.Size([500, 500])
tensor(254, dtype=torch.uint8)
torch.Size([1, 500, 500])
(128, 128)
(79, 179)
So someone could explain why the output range is [79,179]?
If I want to do the resize without changing the value range, what should I do?
Thank you in advance
| Try resize with Nearest neighbor algorithm implemented in pil. It doesn't change pixels
| https://stackoverflow.com/questions/54321678/ |
How to fill in the blank using bidirectional RNN and pytorch? | I am trying to fill in the blank using a bidirectional RNN and pytorch.
The input will be like: The dog is _____, but we are happy he is okay.
The output will be like:
1. hyper (Perplexity score here)
2. sad (Perplexity score here)
3. scared (Perplexity score here)
I discovered this idea here: https://medium.com/@plusepsilon/the-bidirectional-language-model-1f3961d1fb27
import torch, torch.nn as nn
from torch.autograd import Variable
text = ['BOS', 'How', 'are', 'you', 'EOS']
seq_len = len(text)
batch_size = 1
embedding_size = 1
hidden_size = 1
output_size = 1
random_input = Variable(
torch.FloatTensor(seq_len, batch_size, embedding_size).normal_(), requires_grad=False)
bi_rnn = torch.nn.RNN(
input_size=embedding_size, hidden_size=hidden_size, num_layers=1, batch_first=False, bidirectional=True)
bi_output, bi_hidden = bi_rnn(random_input)
# stagger
forward_output, backward_output = bi_output[:-2, :, :hidden_size], bi_output[2:, :, hidden_size:]
staggered_output = torch.cat((forward_output, backward_output), dim=-1)
linear = nn.Linear(hidden_size * 2, output_size)
# only predict on words
labels = random_input[1:-1]
# for language models, use cross-entropy :)
loss = nn.MSELoss()
output = loss(linear(staggered_output), labels)
I am trying to reimplement the code above found at the bottom of the blog post. I am new to pytorch and nlp, and can't understand what the input and output to the code is.
Question about the input: I am guessing the input are the few words that are given. Why does one need beginning of sentence and end of sentence tags in this case? Why don't I see the input being a corpus on which the model is trained like other classic NLP problems? I would like to use the Enron email corpus to train the RNN.
Question about the output: I see the output is a tensor. My understanding is the tensor is a vector, so maybe a word vector in this case. How can you use the tensor to output the words themselves?
| As this question is rather open-ended I will start from the last parts, moving towards the more general answer to the main question posed in the title.
Quick note: as pointed in the comments by @Qusai Alothman, you should find a better resource on the topic, this one is rather sparse when it comes to necessary informations.
Additional note: full code for the process described in the last section would take way too much space to provide as an exact answer, it would be more of a blog post. I will highlight possible steps one should take to create such a network with helpful links as we go along.
Final note: If there is anything dumb down there below (or you would like to expand the answer in any way or form, please do correct me/add info by posting a comment below).
Question about the input
Input here is generated from the random normal distribution and has no connection to the actual words. It is supposed to represent word embeddings, e.g. representation of words as numbers carrying semantic (this is important!) meaning (sometimes depending on the context as well (see one of the current State Of The Art approaches, e.g. BERT)).
Shape of the input
In your example it is provided as:
seq_len, batch_size, embedding_size,
where
seq_len - means length of a single sentence (varies across your
dataset), we will get to it later.
batch_size - how many sentences
should be processed in one step of forward pass (in case of
PyTorch it is the forward method of class inheriting from
torch.nn.Module)
embedding_size - vector with which one word is represented (it
might range from the usual 100/300 using word2vec up to 4096 or
so using the more recent approaches like the BERT mentioned
above)
In this case it's all hard-coded of size one, which is not really useful for a newcomer, it only outlines the idea that way.
Why does one need beginning of sentence and end of sentence tags in this case?
Correct me if I'm wrong, but you don't need it if your input is separated into sentences. It is used if you provide multiple sentences to the model, and want to indicate unambiguously the beginning and end of each (used with models which depend on the previous/next sentences, it seems to not be the case here). Those are encoded by special tokens (the ones which are not present in the entire corpus), so neural network "could learn" they represent end and beginning of sentence (one special token for this approach would be enough).
If you were to use serious dataset, I would advise to split your text using libraries like spaCy or nltk (the first one is a pleasure to use IMO), they do a really good job for this task.
You dataset might be already splitted into sentences, in those cases you are kind of ready to go.
Why don't I see the input being a corpus on which the model is trained like other classic NLP problems?
I don't recall models being trained on the corpuses as is, e.g. using strings. Usually those are represented by floating-points numbers using:
Simple approaches, e.g. Bag Of
Words or
TF-IDF
More sophisticated ones, which provide some information about word
relationships (e.g. king is more semantically related to queen
than to a, say, banana). Those were already linked above, some
other noticeable might be
GloVe or
ELMo and tons of other creative
approaches.
Question about the output
One should output indices into embeddings, which in turn correspond to words represented by a vector (more sophisticated approach mentioned above).
Each row in such embedding represents a unique word and it's respective columns are their unique representations (in PyTorch, first index might be reserved for the words for which a representation is unknown [if using pretrained embeddings], you may also delete those words, or represent them as aj average of sentence/document, there are some other viable approaches as well).
Loss provided in the example
# for language models, use cross-entropy :)
loss = nn.MSELoss()
For this task it makes no sense, as Mean Squared Error is a regression metric, not a classification one.
We want to use one for classification, so softmax should be used for multiclass case (we should be outputting numbers spanning [0, N], where N is the number of unique words in our corpus).
PyTorch's CrossEntropyLoss already takes logits (output of last layer without activation like softmax) and returns loss value for each example. I would advise this approach as it's numerically stable (and I like it as the most minimal one).
I am trying to fill in the blank using a bidirectional RNN and pytorch
This is a long one, I will only highlight steps I would undertake in order to create a model whose idea represents the one outlined in the post.
Basic preparation of dataset
You may use the one you mentioned above or start with something easier like 20 newsgroups from scikit-learn.
First steps should be roughly this:
scrape the metadata (if any) from your dataset (those might be HTML tags, some headers etc.)
split your text into sentences using a pre-made library (mentioned above)
Next, you would like to create your target (e.g. words to be filled) in each sentence.
Each word should be replaced by a special token (say <target-token>) and moved to target.
Example:
sentence: Neural networks can do some stuff.
would give us the following sentences and it's respective targets:
sentence: <target-token> networks can do some stuff. target: Neural
sentence: Neural <target-token> can do some stuff. target: networks
sentence: Neural networks <target-token> do some stuff. target: can
sentence: Neural networks can <target-token> some stuff. target: do
sentence: Neural networks can do <target-token> stuff. target: some
sentence: Neural networks can do some <target-token>. target: some
sentence: Neural networks can do some stuff <target-token> target: .
You should adjust this approach to the problem at hand by correcting typos if there are any, tokenizing, lemmatizing and others, experiment!
Embeddings
Each word in each sentence should be replaced by an integer, which in turn points to it embedding.
I would advise you to use a pre-trained one. spaCy provides word vectors, but another interesting approach I would highly recommend is in the open source library flair.
You may train your own, but it would take a lot of time + a lot of data for unsupervised training, and I think it is way beyond the scope of this question.
Data batching
One should use PyTorch's torch.utils.data.Dataset and torch.utils.data.DataLoader.
In my case, a good idea is was to provide custom collate_fn to DataLoader, which is responsible for creating padded batches of data (or represented as torch.nn.utils.rnn.PackedSequence already).
Important: currently, you have to sort the batch by length (word-wise) and keep the indices able to "unsort" the batch into it's original form, you should remember that during implementation. You may use torch.sort for that task. In future versions of PyTorch, there is a chance, one might not have to do that, see this issue.
Oh, and remember to shuffle your dataset using DataLoader, while we're at it.
Model
You should create a proper model by inheriting from torch.nn.Module. I would advise you to create a more general model, where you can provide PyTorch's cells (like GRU, LSTM or RNN), multilayered and bidirectional (as is described in the post).
Something along those lines when it comes to model construction:
import torch
class Filler(torch.nn.Module):
def __init__(self, cell, embedding_words_count: int):
self.cell = cell
# We want to output vector of N
self.linear = torch.nn.Linear(self.cell.hidden_size, embedding_words_count)
def forward(self, batch):
# Assuming batch was properly prepared before passing into the network
output, _ = self.cell(batch)
# Batch shape[0] is the length of longest already padded sequence
# Batch shape[1] is the length of batch, e.g. 32
# Here we create a view, which allows us to concatenate bidirectional layers in general manner
output = output.view(
batch.shape[0],
batch.shape[1],
2 if self.cell.bidirectional else 1,
self.cell.hidden_size,
)
# Here outputs of bidirectional RNNs are summed, you may concatenate it
# It makes up for an easier implementation, and is another often used approach
summed_bidirectional_output = output.sum(dim=2)
# Linear layer needs batch first, we have to permute it.
# You may also try with batch_first=True in self.cell and prepare your batch that way
# In such case no need to permute dimensions
linear_input = summed_bidirectional_output.permute(1, 0, 2)
return self.linear(embedding_words_count)
As you can see, information about shapes can be obtained in a general fashion. Such approach will allow you to create a model with how many layers you want, bidirectional or not (batch_first argument is problematic, but you can get around it too in a general way, left it out for improved clarity), see below:
model = Filler(
torch.nn.GRU(
# Size of your embeddings, for BERT it could be 4096, for spaCy's word2vec 300
input_size=300,
hidden_size=100,
num_layers=3,
batch_first=False,
dropout=0.4,
bidirectional=True,
),
# How many unique words are there in your dataset
embedding_words_count=10000,
)
You may pass torch.nn.Embedding into your model (if pretrained and already filled), create it from numpy matrix or plethora of other approaches, it's highly dependent how your structure your code exactly. Still, please, make your code more general, do not hardcode shapes unless it's totally necessary (usually it's not).
Remember it's only a showcase, you will have to tune and fix it on your own.
This implementation returns logits and no softmax layer is used. If you wish to calculate perplexity, you may have to add it in order to obtain a correct probability distribution across all possible vectors.
BTW: Here is some info on concatenation of bidirectional output of RNN.
Model training
I would highly recommend PyTorch ignite as it's quite customizable, you can log a lot of info using it, perform validation and abstract cluttering parts like for loops in training.
Oh, and split your model, training and others into separate modules, don't put everything into one unreadable file.
Final notes
This is the outline of how I would approach this problem, you may have more fun using attention networks instead of merely using the last output layer as in this example, though you shouldn't start with that.
And please check PyTorch's 1.0 documentation and do not follow blindly tutorials or blog posts you see online as they might be out of date really fast and quality of the code varies enormously. For example torch.autograd.Variable is deprecated as can be seen in the link.
| https://stackoverflow.com/questions/54323427/ |
Test set accuracy is very high after very few epochs on mnist dataset | With very few epochs this model learns to classify beween 1 and 0 extremely quickly which leads me to consider something is wrong.
Below code downloads mnist dataset, extracts the mnist images that contain 1 or 0 only. A random sample of size 200 is selected from this subset of mnist images. This random sample is the dataset the model is trained on. With just 2 epochs the model achieves 90%+ test set accuracy, is this expected behaviour ? I expected many more epochs would be required in order to train the model to achieve this level of test set accuracy.
Model code :
%reset -f
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torch.utils.data as data_utils
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_moons
from matplotlib import pyplot
from pandas import DataFrame
import torchvision.datasets as dset
import os
import torch.nn.functional as F
import time
import random
import pickle
from sklearn.metrics import confusion_matrix
import pandas as pd
import sklearn
trans = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (1.0,))])
root = './data'
if not os.path.exists(root):
os.mkdir(root)
train_set = dset.MNIST(root=root, train=True, transform=trans, download=True)
test_set = dset.MNIST(root=root, train=False, transform=trans, download=True)
batch_size = 64
train_loader = torch.utils.data.DataLoader(
dataset=train_set,
batch_size=batch_size,
shuffle=True)
test_loader = torch.utils.data.DataLoader(
dataset=test_set,
batch_size=batch_size,
shuffle=True)
class NeuralNet(nn.Module):
def __init__(self):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(28*28, 500)
self.fc2 = nn.Linear(500, 256)
self.fc3 = nn.Linear(256, 2)
def forward(self, x):
x = x.view(-1, 28*28)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
num_epochs = 2
random_sample_size = 200
values_0_or_1 = [t for t in train_set if (int(t[1]) == 0 or int(t[1]) == 1)]
values_0_or_1_testset = [t for t in test_set if (int(t[1]) == 0 or int(t[1]) == 1)]
print(len(values_0_or_1))
print(len(values_0_or_1_testset))
train_loader_subset = torch.utils.data.DataLoader(
dataset=values_0_or_1,
batch_size=batch_size,
shuffle=True)
test_loader_subset = torch.utils.data.DataLoader(
dataset=values_0_or_1_testset,
batch_size=batch_size,
shuffle=False)
train_loader = train_loader_subset
# Hyper-parameters
input_size = 100
hidden_size = 100
num_classes = 2
# learning_rate = 0.00001
learning_rate = .0001
# Device configuration
device = 'cpu'
print_progress_every_n_epochs = 1
model = NeuralNet().to(device)
# Loss and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
N = len(train_loader)
# Train the model
total_step = len(train_loader)
most_recent_prediction = []
test_actual_predicted_dict = {}
rm = random.sample(list(values_0_or_1), random_sample_size)
train_loader_subset = data_utils.DataLoader(rm, batch_size=4)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader_subset):
# Move tensors to the configured device
images = images.reshape(-1, 2).to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (epoch) % print_progress_every_n_epochs == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
predicted_test = []
model.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch mean/variance)
probs_l = []
predicted_values = []
actual_values = []
labels_l = []
with torch.no_grad():
for images, labels in test_loader_subset:
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
predicted_test.append(predicted.cpu().numpy())
sm = torch.nn.Softmax()
probabilities = sm(outputs)
probs_l.append(probabilities)
labels_l.append(labels.cpu().numpy())
predicted_values.append(np.concatenate(predicted_test).ravel())
actual_values.append(np.concatenate(labels_l).ravel())
if (epoch) % 1 == 0:
print('test accuracy : ', 100 * len((np.where(np.array(predicted_values[0])==(np.array(actual_values[0])))[0])) / len(actual_values[0]))
Output of model (12665 & 2115 represents the training and test set sizes) :
12665
2115
Epoch [1/2], Step [50/198], Loss: 0.1256
Epoch [2/2], Step [50/198], Loss: 0.0151
test accuracy : 99.76359338061465
/anaconda3/envs/pytorch/lib/python3.7/site-packages/ipykernel_launcher.py:143: UserWarning: Implicit dimension choice for softmax has been deprecated. Change the call to include dim=X as an argument.
| Here's my 2 cents on your binary experiment.
It would seem like you have severely reduce the complexity of your dataset and with the high number of neurons in your intermediate layers, your model is expected to converge very quickly.
Note that MNIST dataset has channel of 1 and this makes the task very simple.
You may try to play with CIFAR10 and see if you are still getting high accuracy in just 2 epochs.
| https://stackoverflow.com/questions/54334829/ |
Impact of using data shuffling in Pytorch dataloader | I implemented an image classification network to classify a dataset of 100 classes by using Alexnet as a pretrained model and changing the final output layers.
I noticed when I was loading my data like
trainloader = torch.utils.data.DataLoader(train_data, batch_size=32, shuffle=False)
, I was getting accuracy on validation dataset around 2-3 % for around 10 epochs but when I just changed shuffle=True and retrained the network, the accuracy jumped to 70% in the first epoch itself.
I was wondering if it happened because in the first case the network was being shown one example after the other continuously for just one class for few instances resulting in network making poor generalizations during training or is there some other reason behind it?
But, I did not expect that to have such a drastic impact.
P.S: All the code and parameters were exactly the same for both the cases except changing the shuffle option.
| Yes it totally can affect the result! Shuffling the order of the data that we use to fit the classifier is so important, as the batches between epochs do not look alike.
Checking the Data Loader Documentation it says:
"shuffle (bool, optional) – set to True to have the data reshuffled at every epoch"
In any case, it will make the model more robust and avoid over/underfitting.
In your case this heavy increase of accuracy (from the lack of awareness of the dataset) probably is due to how the dataset is "organised" as maybe, as an example, each category goes to a different batch, and in every epoch, a batch contains the same category, which derives to a very bad accuracy when you are testing.
| https://stackoverflow.com/questions/54354465/ |
Unable to get an image in the output when using MNIST Database using Pytorch | iter_test = 0
for images, labels in test_loader:
iter_test += 1
images = images.view(-1, 28*28)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
if iter_test == 1:
print('PREDICTION')
print(predicted[0])
print('LABEL SIZE')
print(labels.size())
print('LABEL FOR IMAGE 0')
print(labels[0])
I get the output of this code as follows:
PREDICTION
tensor(7)
LABEL SIZE
torch.Size([100])
LABEL FOR IMAGE 0
tensor(7)
The code works perfectly. I was wondering if i could get the "MNIST" like image as output along with prediction?
| Yes :).
You can use pyplot and show the image loaded by test_loader.
Check https://www.oreilly.com/learning/not-another-mnist-tutorial-with-tensorflow .
Hope this helps!
| https://stackoverflow.com/questions/54355067/ |
Is there any other reason why we make sequence length the same using padding? | Is there any other reason why we make sequence length the same length using padding? Other than in order to do matrix multiplication (therefore doing parallel computation).
| It may depend on the specific situation you are dealing with. But in general, the only reason I would do zero padding or any kind of padding to RNN would be to make batch-wise computations work. Also, padding should be done in a way that it doesn't affect the results. So, it should not contribute to computing hidden state computation that you would be using for downstream tasks. For example, you may pad the end of the particular sequences from {t+1:T}, but then for further task or processing we should use only h{0:t}
However, if you are doing anything different than simple RNN (for eg. bidirectional-RNN), it can be complicated to do padding. For example: for the forward direction you would pad in the end and for the reverse direction, you would want to pad the front part of sequences.
Even for batching or doing parallel computations pytorch has packed sequences which should be faster than padding IMO.
| https://stackoverflow.com/questions/54355310/ |
Pytorch: Why is the memory occupied by the `tensor` variable so small? | In Pytorch 1.0.0, I found that a tensor variable occupies very small memory. I wonder how it stores so much data.
Here's the code.
a = np.random.randn(1, 1, 128, 256)
b = torch.tensor(a, device=torch.device('cpu'))
a_size = sys.getsizeof(a)
b_size = sys.getsizeof(b)
a_size is 262288. b_size is 72.
| The answer is in two parts. From the documentation of sys.getsizeof, firstly
All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.
so it could be that for tensors __sizeof__ is undefined or defined differently than you would expect - this function is not something you can rely on. Secondly
Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.
which means that if the torch.Tensor object merely holds a reference to the actual memory, this won't show in sys.getsizeof. This is indeed the case, if you check the size of the underlying storage instead, you will see the expected number
import torch, sys
b = torch.randn(1, 1, 128, 256, dtype=torch.float64)
sys.getsizeof(b)
>> 72
sys.getsizeof(b.storage())
>> 262208
Note: I am setting dtype to float64 explicitly, because that is the default dtype in numpy, whereas torch uses float32 by default.
| https://stackoverflow.com/questions/54361763/ |
os.mknod returns [error38] function not implemented in google colab | I am trying to run the following piece of code on google colab.
dir_path = '/content/drive/My Drive/Colab Notebooks'
log_loss_path =os.path.join(dir_path, 'log_loss.txt')
if not os.path.isfile(log_loss_path):
os.mknod(log_loss_path)
but i get the error [Errno 38] Function not implemented
OSError Traceback (most recent call last)
<ipython-input-15-bd3880e6bb8b> in <module>()
2 log_loss_path = os.path.join(dir_path, 'log_loss.txt')
3 if not os.path.isfile(log_loss_path):
----> 4 os.mknod(log_loss_path)
OSError: [Errno 38] Function not implemented
can anyone help to solve it?
| /content/drive is a FUSE filesystem which doesn't support this operation.
If you are just trying to create a file, use instead open(log_loss_path, 'w').
| https://stackoverflow.com/questions/54364457/ |
By picture that is displayed in Jupyter notebook isn't shown when running the same code in IDE? | I was trying to run code from an online tutorial on my local machine by copying code from Jupiter notebook to my IDE (pycharm).
This part
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
pig_img = Image.open("pig.jpg")
preprocess = transforms.Compose([
transforms.Resize(224),
transforms.ToTensor(),
])
pig_tensor = preprocess(pig_img)[None,:,:,:]
plt.imshow(pig_tensor[0].numpy().transpose(1,2,0))
While Jupiter notebook shows the imagine - I cannot get it displayed when running in terminal or IDE.
Any ideas why?
Thank you
| You need to call .show() explicitly to show the image in terminal i.e.
Add this to the end of the code
plt.show()
From the documentation:
Display a figure. When running in ipython with its pylab mode, display all figures and return to the ipython prompt.
In non-interactive mode, display all figures and block until the figures have been closed; in interactive mode it has no effect unless figures were created prior to a change from non-interactive to interactive mode (not recommended). In that case it displays the figures but does not block.
| https://stackoverflow.com/questions/54370810/ |
What kinds of optimization are used in PyTorch methods? | I'm using PyTorch to implement an intense sequence of matrix operations, using methods such as torch.mm or torch.dot. I was wondering if PyTorch uses multithreading or other optimization mechanisms to speed up the process. I am not utilizing a GPU. I appreciate if you could inform me of how fast these methods are and whether I need to take any actions to help the process.
| PyTorch uses an efficient BLAS implementation and multithreading (openMP, if I'm not wrong) to parallelize such operations with multiple cores. Some performance loss comes from the Python itself - since this is an interpreted language, no significant compiler-like optimization can be done. You can use the jit module to speed up the "wrapper" code around the matrix multiplies, but for anything more than very small matrices this cost is probably negligible.
One big improvement you may be able to get manually, but which PyTorch doesn't apply automatically, is to properly order the matrix multiplies. As you probably know, depending on matrix shapes, a multiplication ABCD may have different performance computed as A(B(CD)) than if computed as (AB)(CD), etc.
| https://stackoverflow.com/questions/54379214/ |
Pytorch RuntimeError: Invalid index in gather | I'm new to Pytorch and I encounter this error:
x.gather(1, c)
RuntimeError: Invalid index in gather at
/pytorch/aten/src/TH/generic/THTensorEvenMoreMath.cpp:457
Here is some informations about the tensors:
print(x.size())
print(c.size())
print(type(x))
print(type(c))
torch.Size([128, 2])
torch.Size([128, 1])
<class 'torch.Tensor'>
<class 'torch.Tensor'>
x is filled with float values and c with integers, could it be the problem?
| This simply means your index tensor c has invalid indices.
For example, the following index tensor is valid:
x = torch.tensor([
[5, 9, 1],
[3, 2, 8],
[7, 4, 0]
])
c = torch.tensor([
[0, 0, 0],
[1, 2, 0],
[2, 2, 1]
])
x.gather(1, c)
>>>tensor([[5, 5, 5],
[2, 8, 3],
[0, 0, 4]])
However, the following index tensor is invalid:
c = torch.tensor([
[0, 0, 0],
[1, 2, 0],
[2, 2, 3]
])
And it gives the exception you mention
RuntimeError: Invalid index in gather
| https://stackoverflow.com/questions/54380830/ |
Forward Jacobian Of Neural Network in Pytorch is Slow | I am computing the forward jacobian (derivative of outputs with respect to inputs) of a 2 layer feedforward neural network in pytorch, and my results are correct but relatively slow. Given the nature of the calculation I would expect it to be approximately as fast as a forward pass through the network (or maybe 2-3x as long), but it takes ~12x as long to run an optimization step on this routine (in my test example I just want the jacobian=1 at all points) vs the standard mean squared error so I assume I am doing something in an un-optimal manner. I'm just wondering if anyone knew a faster way to code this. My test network has 2 input nodes, followed by 2 hidden layers of 5 nodes each and an output layer of 2 nodes, and uses tanh activation functions on the hidden layers, with a linear output layer.
The Jacobian calculations are based on the paper The Limitations of Deep Learning in Adversarial Settings which gives a basic recursive definition of the forward derivative (basically you end up multiplying the derivative of your activation functions with the weights and previous partial derivatives of each layer). This is very similar to forward propagation, which is why I would expect it to be faster than it is. Then the determinant of the 2x2 jacobian at the end is pretty straightforward.
Below is the code for the network and the jacobian
class Network(torch.nn.Module):
def __init__(self):
super(Network, self).__init__()
self.h_1_1 = torch.nn.Linear(input_1, hidden_1)
self.h_1_2 = torch.nn.Linear(hidden_1, hidden_2)
self.out = torch.nn.Linear(hidden_2, out_1)
def forward(self, x):
x = F.tanh(self.h_1_1(x))
x = F.tanh(self.h_1_2(x))
x = (self.out(x))
return x
def jacobian(self, x):
a = self.h_1_1.weight
x = F.tanh(self.h_1_1(x))
tanh_deriv_tensor = 1 - (x ** 2)
expanded_deriv = tanh_deriv_tensor.unsqueeze(-1).expand(-1, -1, input_1)
partials = expanded_deriv * a.expand_as(expanded_deriv)
a = torch.matmul(self.h_1_2.weight, partials)
x = F.tanh(self.h_1_2(x))
tanh_deriv_tensor = 1 - (x ** 2)
expanded_deriv = tanh_deriv_tensor.unsqueeze(-1).expand(-1, -1, out_1)
partials = expanded_deriv*a
partials = torch.matmul(self.out.weight, partials)
determinant = partials[:, 0, 0] * partials[:, 1, 1] - partials[:, 0, 1] * partials[:, 1, 0]
return determinant
and here are the two error functions being compared. Note that the first one requires an extra forward call through the network, to get the output values (labeled action) while the second function does not since it works on the input values.
def actor_loss_fcn1(action, target):
loss = ((action-target)**2).mean()
return loss
def actor_loss_fcn2(input): # 12x slower
jacob = model.jacobian(input)
loss = ((jacob-1)**2).mean()
return loss
Any insight on this would be greatly appreciated
| The second calculation of 'a' takes the most time on my machine (cpu).
# Here you increase the size of the matrix with a factor of "input_1"
expanded_deriv = tanh_deriv_tensor.unsqueeze(-1).expand(-1, -1, input_1)
partials = expanded_deriv * a.expand_as(expanded_deriv)
# Here your torch.matmul() needs to handle "input_1" times more computations than in a normal forward call
a = torch.matmul(self.h_1_2.weight, partials)
On my machine the time of computing the Jacobian is roughly the time it takes torch to compute
a = torch.rand(hidden_1, hidden_2)
b = torch.rand(n_inputs, hidden_1, input_1)
%timeit torch.matmul(a,b)
I don't think it is possible to speed this up, computationally wise. Unless you can move from CPU to GPU, because GPU get better on larges matrices.
| https://stackoverflow.com/questions/54383474/ |
How to fix ' ImportError: cannot import name 'numpy_type_map' ' in Python? | I've followed the instructions in Detectron and I've configured it several times: the code compiles as it should. When it comes to run the code, I get this error:
Traceback (most recent call last):
File "tools/train_net_step.py", line 21, in <module>
import nn as mynn
File "/home/federico/PycharmProjects/Detectron.pytorch/lib/nn/__init__.py", line 2, in <module>
from .parallel import DataParallel
File "/home/federico/PycharmProjects/Detectron.pytorch/lib/nn/parallel/__init__.py", line 3, in <module>
from .data_parallel import DataParallel, data_parallel
File "/home/federico/PycharmProjects/Detectron.pytorch/lib/nn/parallel/data_parallel.py", line 4, in <module>
from .scatter_gather import scatter_kwargs, gather
File "/home/federico/PycharmProjects/Detectron.pytorch/lib/nn/parallel/scatter_gather.py", line 8, in <module>
from torch.utils.data.dataloader import numpy_type_map
ImportError: cannot import name 'numpy_type_map'
I've also tried to google it many times, but I can't find a way to solve it. What can I do? I'm using PyTorch 0.4.1 and pytorch nightly 1.0.0-dev.
EDIT: Thanks to sancelot, I managed to solve that error (PyTorch 0.4.0 did the thing). Anyway, now I've got another error:
Traceback (most recent call last):
File "tools/train_net_step.py", line 27, in <module>
from modeling.model_builder import Generalized_RCNN
File "/home/federico/PycharmProjects/Detectron.pytorch/lib/modeling/model_builder.py", line 11, in <module>
from model.roi_pooling.functions.roi_pool import RoIPoolFunction
File "/home/federico/PycharmProjects/Detectron.pytorch/lib/model/roi_pooling/functions/roi_pool.py", line 3, in <module>
from .._ext import roi_pooling
File "/home/federico/PycharmProjects/Detectron.pytorch/lib/model/roi_pooling/_ext/roi_pooling/__init__.py", line 3, in <module>
from ._roi_pooling import lib as _lib, ffi as _ffi
ImportError: /home/federico/PycharmProjects/Detectron.pytorch/lib/model/roi_pooling/_ext/roi_pooling/_roi_pooling.so: undefined symbol: PyInt_FromLong
What I can't get this time is: is this an error given by an external library? I'm using an anaconda environment previously made by my professor, who has used it for Detectron... so I can't guess why I get this.
| I suppose there is a version mismatch between detectron and the needed pytorch release you are using.
if you look at latest pytorch source code, there is no numpy_type_map component.
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/dataloader.py
| https://stackoverflow.com/questions/54387659/ |
when training simple code of pytorch, cpu ratio increased. GPU is 0% approximately | I'm doing tutorial of Pytorch.
Code is clearly completed. but i have one problem.
It is about my CPU use ratio.
If I enter into training, CPU usage ratio is increasıng up to 100%.
but GPU is roughly 0%.
I installed CUDA 9.2 and cudnn.
and I already checked massage about torch.cuda.is_available()==True.
is it OK, or my setup is wrong?
| 1.. Did you upload your model and input tensors onto GPU explicitly, showing as follow
https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html#training-on-gpu
For example,
# Configure your device
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Upload your model onto GPU
net.to(device)
# Upload your tensor onto GPU
inputs, labels = inputs.to(device), labels.to(device)
2.. You also can use "gpustat" to check GPU usage.
https://github.com/wookayin/gpustat
After installing, you can type "gpustat" on terminal
If your code runs on GPU, GPU usage will increase.
3.. And check whether you've added following CUDA path into your bashrc file.
Following CUDA path is general path on Ubuntu Linux,
but that path can be different per OS or your setting.
You can open bashrc file by typing vim ./.bashrc
when your current directory is home in case where you use Ubuntu Linux.
export PATH=/usr/local/cuda/bin:$PATH
export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH
4.. Also check your graphic driver has been installed
by typing nvidia-smi on terminal if you use Ubuntu Linux.
| https://stackoverflow.com/questions/54387686/ |
Why does gpytorch seem to be less accurate than scikit-learn? | I current found gpytorch (https://github.com/cornellius-gp/gpytorch). It seems to be a great package for integrating GPR into pytorch. First tests were also positive. Using gpytorch the GPU-Power as well as intelligent algorithms can used in order to improve performance in comparison to other packages such as scikit-learn.
However, I found that it is much harder to estimate the hyperparameters that are needed. In scikit-learn that happens in the background and is very robust. I would like get some feed from the community about the reasons and to discuss if there might be a better way to estimatethese parameter than provided by the example in the documentation of gpytorch.
For comparisson, I took the code of a provided example on the offcial page of gpytorch (https://github.com/cornellius-gp/gpytorch/blob/master/examples/03_Multitask_GP_Regression/Multitask_GP_Regression.ipynb) and modified it in two parts:
I use a different kernel (gpytorch.kernels.MaternKernel(nu=2.5) in stead of gpytorch.kernels.RBFKernel())
I used a different output function
In the following, I provide first the code using gpytorch. Subsequently, I provide the code for scikit-learn. Finally, I compare the results
Importing (for gpytorch and scikit-learn):
import math
import torch
import numpy as np
import gpytorch
Generating data (for gpytorch and scikit-learn):
n = 20
train_x = torch.zeros(pow(n, 2), 2)
for i in range(n):
for j in range(n):
# Each coordinate varies from 0 to 1 in n=100 steps
train_x[i * n + j][0] = float(i) / (n-1)
train_x[i * n + j][1] = float(j) / (n-1)
train_y_1 = (torch.sin(train_x[:, 0]) + torch.cos(train_x[:, 1]) * (2 * math.pi) + torch.randn_like(train_x[:, 0]).mul(0.01))/4
train_y_2 = torch.sin(train_x[:, 0]) + torch.cos(train_x[:, 1]) * (2 * math.pi) + torch.randn_like(train_x[:, 0]).mul(0.01)
train_y = torch.stack([train_y_1, train_y_2], -1)
test_x = torch.rand((n, len(train_x.shape)))
test_y_1 = (torch.sin(test_x[:, 0]) + torch.cos(test_x[:, 1]) * (2 * math.pi) + torch.randn_like(test_x[:, 0]).mul(0.01))/4
test_y_2 = torch.sin(test_x[:, 0]) + torch.cos(test_x[:, 1]) * (2 * math.pi) + torch.randn_like(test_x[:, 0]).mul(0.01)
test_y = torch.stack([test_y_1, test_y_2], -1)
Now comes the estimation as described in the provided example from the cited documentation:
torch.manual_seed(2) # For a more robust comparison
class MultitaskGPModel(gpytorch.models.ExactGP):
def __init__(self, train_x, train_y, likelihood):
super(MultitaskGPModel, self).__init__(train_x, train_y, likelihood)
self.mean_module = gpytorch.means.MultitaskMean(
gpytorch.means.ConstantMean(), num_tasks=2
)
self.covar_module = gpytorch.kernels.MultitaskKernel(
gpytorch.kernels.MaternKernel(nu=2.5), num_tasks=2, rank=1
)
def forward(self, x):
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
return gpytorch.distributions.MultitaskMultivariateNormal(mean_x, covar_x)
likelihood = gpytorch.likelihoods.MultitaskGaussianLikelihood(num_tasks=2)
model = MultitaskGPModel(train_x, train_y, likelihood)
# Find optimal model hyperparameters
model.train()
likelihood.train()
# Use the adam optimizer
optimizer = torch.optim.Adam([
{'params': model.parameters()}, # Includes GaussianLikelihood parameters
], lr=0.1)
# "Loss" for GPs - the marginal log likelihood
mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)
n_iter = 50
for i in range(n_iter):
optimizer.zero_grad()
output = model(train_x)
loss = -mll(output, train_y)
loss.backward()
# print('Iter %d/%d - Loss: %.3f' % (i + 1, n_iter, loss.item()))
optimizer.step()
# Set into eval mode
model.eval()
likelihood.eval()
# Make predictions
with torch.no_grad(), gpytorch.settings.fast_pred_var():
predictions = likelihood(model(test_x))
mean = predictions.mean
lower, upper = predictions.confidence_region()
test_results_gpytorch = np.median((test_y - mean) / test_y, axis=0)
In the following, I provide the code for scikit-learn. Which is a little bit more convenient^^:
from sklearn.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import WhiteKernel, Matern
kernel = 1.0 * Matern(length_scale=0.1, length_scale_bounds=(1e-5, 1e5), nu=2.5) \
+ WhiteKernel()
gp = GaussianProcessRegressor(kernel=kernel, alpha=0.0).fit(train_x.numpy(),
train_y.numpy())
# x_interpolation = test_x.detach().numpy()[np.newaxis, :].transpose()
y_mean_interpol, y_std_norm = gp.predict(test_x.numpy(), return_std=True)
test_results_scitlearn = np.median((test_y.numpy() - y_mean_interpol) / test_y.numpy(), axis=0)
Finally I compare the results:
comparisson = (test_results_scitlearn - test_results_gpytorch)/test_results_scitlearn
print('Variable 1: scitkit learn is more accurate my factor: ' + str(abs(comparisson[0]))
print('Variable 2: scitkit learn is more accurate my factor: ' + str(comparisson[1]))
Unfortunatelly, I did not find an easy way to fix the seed for scikit-learn. The last time I have run the code, it returned:
Variable 1: scitkit learn is more accurate my factor: 11.362540360431087
Variable 2: scitkit learn is more accurate my factor: 29.64760087022618
In case of gpytorch, I assume that the optimizer runs in some local optima. But I cannot think of any more robust optimization algorithm that still uses pytorch.
I am looking forward for suggestions!
Lazloo
| (I also answer your question on the GitHub issue you created for it here)
Primarily this happened because you used different models in sklearn and gpytorch. In particular, sklearn learns independent GPs in the multi-output setting by default (see e.g., the discussion here). In GPyTorch, you used the multitask GP method introduced in Bonilla et al, 2008. Correcting for this difference yields:
test_results_gpytorch = [5.207913e-04 -8.469360e-05]
test_results_scitlearn = [3.65288816e-04 4.79017145e-05]
| https://stackoverflow.com/questions/54389944/ |
pretrained object detection models in keras | There are pretrained object recognition models in keras.applications library. But as far as I know, there is no pretrained object detection model available.
Does anyone know why it is the case? Object detection is a big part of problems when dealing with visual problems.
| That is because vanilla Keras does not include implementation of methods/models for object detection.
There are many approaches to object detection with deep learning (see Object Detection with Deep Learning: A Review for a survey), but none of them are implemented as a part of Keras library, so no official models as well. I have a feeling that François Chollet tries to keep it simple and minimalistic, so bloating the code with something like TensorFlow models will be against its philosophy.
However, Keras is easily extendable, so there are plenty of unofficial implementations (e.g. SSD or Mask R-CNN) supplied with the trained models though. See Keras model zoo for more.
| https://stackoverflow.com/questions/54396398/ |
RuntimeError: Expected a Tensor of type torch.FloatTensor but found a type torch.IntTensor for sequence element | I wanna generate some random number with python and transform it to tensor with pytorch. Here is my code for generating the random number and transform it into tensor.
import numpy as np
import torch
P = np.random.uniform(0.5, 1, size=[20, 1])
k = np.random.randint(1, 20, size=[20, 1])
d_k = np.random.uniform(0, np.sqrt(80000), size=[20, 1])
P = torch.from_numpy(P).float()
k = torch.from_numpy(k).int()
d_k = torch.from_numpy(d_k).float()
torch.cat((P, k, d_k), dim=-1)
Afterward, I got some error which showed:
RuntimeError: Expected a Tensor of type torch.FloatTensor but found a type torch.IntTensor for sequence element 1 in sequence argument at position #1 'tensors'
| The error is because k tensor is of dtype torch.int32 while other tensors P and d_k are of dtype torch.float32. But the cat operation requires all the input tensors to be of same type. From the documentation
torch.cat(tensors, dim=0, out=None) → Tensor
tensors (sequence of Tensors) – any python sequence of tensors of the
same type.
One of the solutions is to convert k to float dtype as follows:
k = torch.from_numpy(k).float()
| https://stackoverflow.com/questions/54403933/ |
name '_C' is not defined pytorch+jupyter notebook | I have some code that uses pytorch, that runs fine from my IDE (pycharm).
For research, I tried to run it from a jupyter notebook.
The code in the notebook:
from algorithms import Argparser
from algorithms import Session
def main():
print("main started")
args = Argparser.parse()
session = Session(args)
session.run()
The package looks like:
|-algorithms
|---__init__.py
|---Argparser.py
|---Session.py
|---<many more files that are being used by Session>.py
some of those files do import torch
When running the code in the notebook, I get
NameError Traceback (most recent call
last) in
1 from algorithms import Argparser
----> 2 from algorithms import Session
3 def main():
4 print("main started")
5 args = Argparser.parse()
D:\git\stav\stav-rl\algorithms\Session.py in
12
13
---> 14 from algorithms.Episode import Episode
15 from algorithms.Agent import Agent
16 import torch
D:\git\stav\stav-rl\algorithms\Episode.py in
1 author = 'Noam'
2
----> 3 import torch
4 import numpy as np
5 import cv2
c:\anaconda3\envs\threadartrl\lib\site-packages\torch__init__.py in
84 from torch._C import *
85
---> 86 all += [name for name in dir(C)
87 if name[0] != '' and
88 not name.endswith('Base')]
NameError: name '_C' is not defined
The error is on from algorithms import Session-->...-->import torch
How can i get the code to run?
| You need Cython for pytorch to work:
pip3 install Cython
See this comment on the issue on github.
My understanding is that there is a library called _C.cpython-37m-x86_64-linux-gnu.so in site-packages/torch which provides the shared object _C and requires Cython. PyCharm provides Cython support whereas the Jupyter environment doesn't.
| https://stackoverflow.com/questions/54408973/ |
LSTM autoencoder always returns the average of the input sequence | I'm trying to build a very simple LSTM autoencoder with PyTorch. I always train it with the same data:
x = torch.Tensor([[0.0], [0.1], [0.2], [0.3], [0.4]])
I have built my model following this link:
inputs = Input(shape=(timesteps, input_dim))
encoded = LSTM(latent_dim)(inputs)
decoded = RepeatVector(timesteps)(encoded)
decoded = LSTM(input_dim, return_sequences=True)(decoded)
sequence_autoencoder = Model(inputs, decoded)
encoder = Model(inputs, encoded)
My code is running with no errors but y_pred converge to:
tensor([[[0.2]],
[[0.2]],
[[0.2]],
[[0.2]],
[[0.2]]], grad_fn=<StackBackward>)
Here is my code:
import torch
import torch.nn as nn
import torch.optim as optim
class LSTM(nn.Module):
def __init__(self, input_dim, latent_dim, batch_size, num_layers):
super(LSTM, self).__init__()
self.input_dim = input_dim
self.latent_dim = latent_dim
self.batch_size = batch_size
self.num_layers = num_layers
self.encoder = nn.LSTM(self.input_dim, self.latent_dim, self.num_layers)
self.decoder = nn.LSTM(self.latent_dim, self.input_dim, self.num_layers)
def init_hidden_encoder(self):
return (torch.zeros(self.num_layers, self.batch_size, self.latent_dim),
torch.zeros(self.num_layers, self.batch_size, self.latent_dim))
def init_hidden_decoder(self):
return (torch.zeros(self.num_layers, self.batch_size, self.input_dim),
torch.zeros(self.num_layers, self.batch_size, self.input_dim))
def forward(self, input):
# Reset hidden layer
self.hidden_encoder = self.init_hidden_encoder()
self.hidden_decoder = self.init_hidden_decoder()
# Reshape input
input = input.view(len(input), self.batch_size, -1)
# Encode
encoded, self.hidden = self.encoder(input, self.hidden_encoder)
encoded = encoded[-1].repeat(5, 1, 1)
# Decode
y, self.hidden = self.decoder(encoded, self.hidden_decoder)
return y
model = LSTM(input_dim=1, latent_dim=20, batch_size=1, num_layers=1)
loss_function = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.0001)
x = torch.Tensor([[0.0], [0.1], [0.2], [0.3], [0.4]])
while True:
y_pred = model(x)
optimizer.zero_grad()
loss = loss_function(y_pred, x)
loss.backward()
optimizer.step()
print(y_pred)
| 1. Initializing hidden states
In your source code you are using init_hidden_encoder and init_hidden_decoder functions to zero hidden states of both recurrent units in every forward pass.
In PyTorch you don't have to do that, if no initial hidden state is passed to RNN-cell (be it LSTM, GRU or RNN from the ones currently available by default in PyTorch), it is implicitly fed with zeroes.
So, to obtain the same code as your initial solution (which simplifies next parts), I will scrap unneeded parts, which leaves us with the model seen below:
class LSTM(nn.Module):
def __init__(self, input_dim, latent_dim, num_layers):
super(LSTM, self).__init__()
self.input_dim = input_dim
self.latent_dim = latent_dim
self.num_layers = num_layers
self.encoder = nn.LSTM(self.input_dim, self.latent_dim, self.num_layers)
self.decoder = nn.LSTM(self.latent_dim, self.input_dim, self.num_layers)
def forward(self, input):
# Encode
_, (last_hidden, _) = self.encoder(input)
encoded = last_hidden.repeat(5, 1, 1)
# Decode
y, _ = self.decoder(encoded)
return torch.squeeze(y)
Addition of torch.squeeze
We don't need any superfluous dimensions (like the 1 in [5,1,1]).
Actually, it's the clue to your results equal to 0.2
Furthermore, I left input reshape out of the network (in my opinion, network should be fed with input ready to be processed), to separate strictly both tasks (input preparation and model itself).
This approach gives us the following setup code and training loop:
model = LSTM(input_dim=1, latent_dim=20, num_layers=1)
loss_function = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.0001)
y = torch.Tensor([[0.0], [0.1], [0.2], [0.3], [0.4]])
# Sequence x batch x dimension
x = y.view(len(y), 1, -1)
while True:
y_pred = model(x)
optimizer.zero_grad()
loss = loss_function(y_pred, y)
loss.backward()
optimizer.step()
print(y_pred)
Whole network is identical to yours (for now), except it is more succinct and readable.
2. What we want, describing network changes
As your provided Keras code indicates, what we want to do (and actually you are doing it correctly) is to obtain last hiddden state from the encoder (it encodes our entire sequence) and decode the sequence from this state to obtain the original one.
BTW. this approach is called sequence to sequence or seq2seq for short (often used in tasks like language translation). Well, maybe a variation of that approach, but I would classify it as that anyway.
PyTorch provides us the last hidden state as a separate return variable from RNNs family.
I would advise against yours encoded[-1]. The reason for it would be bidirectional and multilayered approach. Say, you wanted to sum bidirectional output, it would mean a code along those lines
# batch_size and hidden_size should be inferred cluttering the code further
encoded[-1].view(batch_size, 2, hidden_size).sum(dim=1)
And that's why the line _, (last_hidden, _) = self.encoder(input) was used.
3. Why does the output converge to 0.2?
Actually, it was a mistake on your side and only in the last part.
Output shapes of your predictions and targets:
# Your output
torch.Size([5, 1, 1])
# Your target
torch.Size([5, 1])
If those shapes are provided, MSELoss, by default, uses argument size_average=True. And yes, it averages your targets and your output, which essentially calculates loss for the average of your tensor (around 2.5 at the beginning) and average of your target which is 0.2.
So the network converges correctly, but your targets are wrong.
3.1 First and wrong solution
Provide MSELoss with argument reduction="sum", though it's really temporary and works accidentally.
Network, at first, will try to get all of the outputs to be equal to sum (0 + 0.1 + 0.2 + 0.3 + 0.4 = 1.0), at first with semi-random outputs, after a while it will converge to what you want, but not for the reasons you want!.
Identity function is the easiest choice here, even for summation (as your input data is really simple).
3.2 Second and correct solution.
Just pass appropriate shapes to loss function, e.g. batch x outputs, in your case, the final part would look like this:
model = LSTM(input_dim=1, latent_dim=20, num_layers=1)
loss_function = nn.MSELoss()
optimizer = optim.Adam(model.parameters())
y = torch.Tensor([0.0, 0.1, 0.2, 0.3, 0.4])
x = y.view(len(y), 1, -1)
while True:
y_pred = model(x)
optimizer.zero_grad()
loss = loss_function(y_pred, y)
loss.backward()
optimizer.step()
print(y_pred)
Your target is one dimensional (as batch is of size 1) and so is your output (after squeezing unnecessary dimensions).
I changed Adam's parameters to defaults as it converges faster that way.
4. Final working code
For brevity, here is the code and results:
import torch
import torch.nn as nn
import torch.optim as optim
class LSTM(nn.Module):
def __init__(self, input_dim, latent_dim, num_layers):
super(LSTM, self).__init__()
self.input_dim = input_dim
self.latent_dim = latent_dim
self.num_layers = num_layers
self.encoder = nn.LSTM(self.input_dim, self.latent_dim, self.num_layers)
self.decoder = nn.LSTM(self.latent_dim, self.input_dim, self.num_layers)
def forward(self, input):
# Encode
_, (last_hidden, _) = self.encoder(input)
# It is way more general that way
encoded = last_hidden.repeat(input.shape)
# Decode
y, _ = self.decoder(encoded)
return torch.squeeze(y)
model = LSTM(input_dim=1, latent_dim=20, num_layers=1)
loss_function = nn.MSELoss()
optimizer = optim.Adam(model.parameters())
y = torch.Tensor([0.0, 0.1, 0.2, 0.3, 0.4])
x = y.view(len(y), 1, -1)
while True:
y_pred = model(x)
optimizer.zero_grad()
loss = loss_function(y_pred, y)
loss.backward()
optimizer.step()
print(y_pred)
And here are the results after ~60k steps (it is stuck after ~20k steps actually, you may want to improve your optimization and play around with hidden size for better results):
step=59682
tensor([0.0260, 0.0886, 0.1976, 0.3079, 0.3962], grad_fn=<SqueezeBackward0>)
Additionally, L1Loss (a.k.a Mean Absolute Error) may get better results in this case:
step=10645
tensor([0.0405, 0.1049, 0.1986, 0.3098, 0.4027], grad_fn=<SqueezeBackward0>)
Tuning and correct batching of this network is left for you, hope you'll have some fun now and you get the idea. :)
PS. I repeat entire shape of input sequence, as it's more general approach and should work with batches and more dimensions out of the box.
| https://stackoverflow.com/questions/54411662/ |
How to balance (oversampling) unbalanced data in PyTorch (with WeightedRandomSampler)? | I have a 2-class problem and my data is highly unbalanced. I have 232550 samples from one class and 13498 from the second class. PyTorch docs and the internet tells me to use the class WeightedRandomSampler for my DataLoader.
I have tried using the WeightedRandomSampler but I keep getting errors.
trainratio = np.bincount(trainset.labels)
classcount = trainratio.tolist()
train_weights = 1./torch.tensor(classcount, dtype=torch.float)
train_sampleweights = train_weights[trainset.labels]
train_sampler = WeightedRandomSampler(weights=train_sampleweights,
num_samples = len(train_sampleweights))
trainloader = DataLoader(trainset, sampler=train_sampler,
shuffle=False)
I can not see why I am getting this error when initializing the WeightedRandomSampler class?
I have tried other similar workarounds but so far all attempts produce some error.
How should I implement this to balance my train, validation and test data?
Currently getting this error:
train__sampleweights = train_weights[trainset.labels] ValueError: too
many dimensions 'str'
| The problem is in the type of trainset.labels
To fix the error it is possible to convert trainset.labels to float
| https://stackoverflow.com/questions/54415345/ |
PyTorch runtime error : invalid argument 0: Sizes of tensors must match except in dimension 1 | I have a PyTorch model and I'm trying to test it by performing a forward pass. Here is the code:
class ResBlock(nn.Module):
def __init__(self, inplanes, planes, stride=1):
super(ResBlock, self).__init__()
self.conv1x1 = nn.Conv2d(inplanes, planes, kernel_size=1, stride=1, bias=False)
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
#batch normalization
self.bn1 = nn.BatchNorm2d(planes)
self.relu = nn.ReLU()
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.stride = stride
def forward(self, x):
residual = self.conv1x1(x)
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
#adding the skip connection
out += residual
out = self.relu(out)
return out
class ResUnet (nn.Module):
def __init__(self, in_shape, num_classes):
super(ResUnet, self).__init__()
in_channels, height, width = in_shape
#
#self.L1 = IncResBlock(in_channels,64)
self.e1 = nn.Sequential(
nn.Conv2d(in_channels, 64, kernel_size=4, stride=2,padding=1),
ResBlock(64,64))
self.e2 = nn.Sequential(
nn.LeakyReLU(0.2,),
nn.Conv2d(64, 128, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(128),
ResBlock(128,128))
#
self.e2add = nn.Sequential(
nn.Conv2d(128, 128, kernel_size=3, stride=1,padding=1),
nn.BatchNorm2d(128))
#
##
self.e3 = nn.Sequential(
nn.LeakyReLU(0.2,inplace=True),
nn.Conv2d(128, 128, kernel_size=3, stride=1,padding=1),
nn.BatchNorm2d(128),
nn.LeakyReLU(0.2,),
nn.Conv2d(128,256, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(256),
ResBlock(256,256))
self.e4 = nn.Sequential(
nn.LeakyReLU(0.2,),
nn.Conv2d(256,512, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(512),
ResBlock(512,512))
#
self.e4add = nn.Sequential(
nn.Conv2d(512,512, kernel_size=3, stride=1,padding=1),
nn.BatchNorm2d(512))
#
self.e5 = nn.Sequential(
nn.LeakyReLU(0.2,inplace=True),
nn.Conv2d(512,512, kernel_size=3, stride=1,padding=1),
nn.BatchNorm2d(512),
nn.LeakyReLU(0.2,),
nn.Conv2d(512,512, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(512),
ResBlock(512,512))
#
#
self.e6 = nn.Sequential(
nn.LeakyReLU(0.2,),
nn.Conv2d(512,512, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(512),
ResBlock(512,512))
#
self.e6add = nn.Sequential(
nn.Conv2d(512,512, kernel_size=3, stride=1,padding=1),
nn.BatchNorm2d(512))
#
self.e7 = nn.Sequential(
nn.LeakyReLU(0.2,inplace=True),
nn.Conv2d(512,512, kernel_size=3, stride=1,padding=1),
nn.BatchNorm2d(512),
nn.LeakyReLU(0.2,),
nn.Conv2d(512,512, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(512),
ResBlock(512,512))
#
self.e8 = nn.Sequential(
nn.LeakyReLU(0.2,),
nn.Conv2d(512,512, kernel_size=4, stride=2,padding=1))
#nn.BatchNorm2d(512))
self.d1 = nn.Sequential(
nn.ReLU(),
nn.ConvTranspose2d(512, 512, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(512),
nn.Dropout(p=0.5),
ResBlock(512,512))
#
self.d2 = nn.Sequential(
nn.ReLU(),
nn.ConvTranspose2d(1024, 512, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(512),
nn.Dropout(p=0.5),
ResBlock(512,512))
#
self.d3 = nn.Sequential(
nn.ReLU(),
nn.ConvTranspose2d(1024, 512, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(512),
nn.Dropout(p=0.5),
ResBlock(512,512))
#
self.d4 = nn.Sequential(
nn.ReLU(),
nn.ConvTranspose2d(1024, 512, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(512),
ResBlock(512,512))
#
self.d5 = nn.Sequential(
nn.ReLU(),
nn.ConvTranspose2d(1024, 256, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(256),
ResBlock(256,256))
#
self.d6 = nn.Sequential(
nn.ReLU(),
nn.ConvTranspose2d(512, 128, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(128),
ResBlock(128,128))
#
self.d7 = nn.Sequential(
nn.ReLU(),
nn.ConvTranspose2d(256, 64, kernel_size=4, stride=2,padding=1),
nn.BatchNorm2d(64),
ResBlock(64,64))
#
self.d8 = nn.Sequential(
nn.ReLU(),
nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2,padding=1))
#nn.BatchNorm2d(64),
#nn.ReLU())
self.out_l = nn.Sequential(
nn.Conv2d(64,num_classes,kernel_size=1,stride=1))
#nn.ReLU())
def forward(self, x):
#Image Encoder
#### Encoder #####
en1 = self.e1(x)
en2 = self.e2(en1)
en2add = self.e2add(en2)
en3 = self.e3(en2add)
en4 = self.e4(en3)
en4add = self.e4add(en4)
en5 = self.e5(en4add)
en6 = self.e6(en5)
en6add = self.e6add(en6)
en7 = self.e7(en6add)
en8 = self.e8(en7)
#### Decoder ####
de1_ = self.d1(en8)
de1 = torch.cat([en7,de1_],1)
de2_ = self.d2(de1)
de2 = torch.cat([en6add,de2_],1)
de3_ = self.d3(de2)
de3 = torch.cat([en5,de3_],1)
de4_ = self.d4(de3)
de4 = torch.cat([en4add,de4_],1)
de5_ = self.d5(de4)
de5 = torch.cat([en3,de5_],1)
de6_ = self.d6(de5)
de6 = torch.cat([en2add,de6_],1)
de7_ = self.d7(de6)
de7 = torch.cat([en1,de7_],1)
de8 = self.d8(de7)
out_l_mask = self.out_l(de8)
return out_l_mask
Here is how I attempt to test it:
modl = ResUnet((1,512,512), 1)
x = torch.rand(1, 1, 512, 512)
modl(x)
This works fine, as does for any size that are multiples of 64.
If I try:
modl = ResUnet((1,320,320), 1)
x = torch.rand(1, 1, 320, 320)
modl(x)
It throws an error
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-46-4ddc821c365b> in <module>
----> 1 modl(x)
~/.conda/envs/torch0.4/lib/python3.6/site-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
475 result = self._slow_forward(*input, **kwargs)
476 else:
--> 477 result = self.forward(*input, **kwargs)
478 for hook in self._forward_hooks.values():
479 hook_result = hook(self, input, result)
<ipython-input-36-f9eeefa3c0b8> in forward(self, x)
221 de2_ = self.d2(de1)
222 #print de2_.size()
--> 223 de2 = torch.cat([en6add,de2_],1)
224 #print de2.size()
225
RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 1. Got 5 and 4 in dimension 2 at /opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/TH/generic/THTensorMath.cpp:3616
I figure the problem is caused by the input size not being a power of 2 but I am not sure how to rectify it for the given input dimenstions (320, 320).
| This issue arises from mismatch in size between the variables in the downsampling (encoder) path and the upsampling (decoder) path. Your code is huge and difficult to understand, but by inserting print statements, we can check that
en6add is of size [1, 512, 5, 5]
en7 is [1, 512, 2, 2]
en8 is [1, 512, 1, 1]
then upsampling goes as powers of two: de1_ is [1, 512, 2, 2]
de1 [1, 1024, 2, 2]
de2_ [1, 512, 4, 4]
at which point you try to concatenate it with en6add, so apparently the code creating de2_ is not "upsampling enough". My strong guess is that you need to pay the attention to the output_padding parameter of nn.ConvTranspose2d and possibly set it to 1 in a couple of places. I would try and fix this error for you, but that example is so far from being minimal that I can't wrap my head around the whole of it.
| https://stackoverflow.com/questions/54417736/ |
PyTorch Dataloader - List is not callable error when enumerating | When iterating over a PyTorch dataloader, e.g.
# define dataset, dataloader
train_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)
test_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)
trainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)
testloader = torch.utils.data.DataLoader(test_data, batch_size=64)
# define model, optimizer, loss
# not included - irrelevant to the question
for ii, (inputs, labels) in enumerate(trainloader):
# Move input and label tensors to the GPU
inputs, labels = inputs.to(device), labels.to(device)
start = time.time()
outputs = model.forward(inputs)
loss = criterion(outputs, labels)
loss.backward()
I get a TypeError: 'list' object is not callable on this line
for ii, (inputs, labels) in enumerate(trainloader):
What dumb thing am I forgetting?
| Did you remember to call transforms.Compose on your list of transforms?
In this line
train_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)
the transform parameter is expecting a callable object, not a list.
So, for example, this is wrong:
train_transforms = [
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]
It should look like this
train_transforms = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
| https://stackoverflow.com/questions/54431671/ |
net.load_state_dict(torch.load('rnn_x_epoch.net')) not working on cpu | I am using pytorch to train a Neural Network. When I train and test on GPU, it works fine.
But When I try to load the model parameters on CPU using:
net.load_state_dict(torch.load('rnn_x_epoch.net'))
I get the following error:
RuntimeError: cuda runtime error (35) : CUDA driver version is insufficient for CUDA runtime version at torch/csrc/cuda/Module.cpp:51
I have searched for the error, it's mainly because of CUDA driver dependency, but since I'm running on CPU when I get this error,it must be something else, or may be I missed something.
Since it's working fine using GPU, I could just run it on GPU but I'm trying to train the network on GPU, store the parameters and then load it on CPU mode for predictions.
I am just looking for a way to load the parameters while on CPU mode.
I tried this as well to load the parameters:
check = torch.load('rnn_x_epoch.net')
It did not work.
I tried to save the model parameters in two ways, to see if any of these would work, but didn't:
1)
checkpoint = {'n_hidden': net.n_hidden,
'n_layers': net.n_layers,
'state_dict': net.state_dict(),
'tokens': net.chars}
with open('rnn_x_epoch.net', 'wb') as f:
torch.save(checkpoint, f)
2)
torch.save(model.state_dict(), 'rnn_x_epoch.net')
TraceBack:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-9-e61f28013b35> in <module>()
----> 1 net.load_state_dict(torch.load('rnn_x_epoch.net'))
/opt/conda/lib/python3.6/site-packages/torch/serialization.py in load(f, map_location, pickle_module)
301 f = open(f, 'rb')
302 try:
--> 303 return _load(f, map_location, pickle_module)
304 finally:
305 if new_fd:
/opt/conda/lib/python3.6/site-packages/torch/serialization.py in _load(f, map_location, pickle_module)
467 unpickler = pickle_module.Unpickler(f)
468 unpickler.persistent_load = persistent_load
--> 469 result = unpickler.load()
470
471 deserialized_storage_keys = pickle_module.load(f)
/opt/conda/lib/python3.6/site-packages/torch/serialization.py in persistent_load(saved_id)
435 if root_key not in deserialized_objects:
436 deserialized_objects[root_key] = restore_location(
--> 437 data_type(size), location)
438 storage = deserialized_objects[root_key]
439 if view_metadata is not None:
/opt/conda/lib/python3.6/site-packages/torch/serialization.py in default_restore_location(storage, location)
86 def default_restore_location(storage, location):
87 for _, _, fn in _package_registry:
---> 88 result = fn(storage, location)
89 if result is not None:
90 return result
/opt/conda/lib/python3.6/site-packages/torch/serialization.py in _cuda_deserialize(obj, location)
68 if location.startswith('cuda'):
69 device = max(int(location[5:]), 0)
---> 70 return obj.cuda(device)
71
72
/opt/conda/lib/python3.6/site-packages/torch/_utils.py in _cuda(self, device, non_blocking, **kwargs)
66 if device is None:
67 device = -1
---> 68 with torch.cuda.device(device):
69 if self.is_sparse:
70 new_type = getattr(torch.cuda.sparse,
self.__class__.__name__)
/opt/conda/lib/python3.6/site-packages/torch/cuda/__init__.py in __enter__(self)
223 if self.idx is -1:
224 return
--> 225 self.prev_idx = torch._C._cuda_getDevice()
226 if self.prev_idx != self.idx:
227 torch._C._cuda_setDevice(self.idx)
RuntimeError: cuda runtime error (35) : CUDA driver version is insufficient for CUDA runtime version at torch/csrc/cuda/Module.cpp:51
Also may be the save/load operations in Pytorch are only for GPU mode, but I am not really convinced by that.
| From the PyTorch documentation:
When you call torch.load() on a file which contains GPU tensors, those tensors will be loaded to GPU by default.
To load the model on CPU which was saved on GPU, you need to pass map_location argument as cpu in load function as follows:
# Load all tensors onto the CPU
net.load_state_dict(torch.load('rnn_x_epoch.net', map_location=torch.device('cpu')))
In doing so, the storages underlying the tensors are dynamically remapped to the CPU device using the map_location argument. You can read more on the official PyTorch tutorials.
This can also be done as follows:
# Load all tensors onto the CPU, using a function
net.load_state_dict(torch.load('rnn_x_epoch.net', map_location=lambda storage, loc: storage))
| https://stackoverflow.com/questions/54435133/ |
Application of nn.Linear layer in pytorch on additional dimentions | How is the fully-connected layer (nn.Linear) in pytorch applied on "additional dimensions"? The documentation says, that it can be applied to connect a tensor (N,*,in_features) to (N,*,out_features), where N in the number of examples in a batch, so it is irrelevant, and * are those "additional" dimensions. Does it mean that a single layer is trained using all possible slices in the additional dimensions or are separate layers trained for each slice or something yet different?
| There are in_features * out_features parameters learned in linear.weight and out_features parameters learned in linear.bias. You can think of nn.Linear working as
reshape the tensor to some (N', in_features), where N' is the product of N and all dimensions described with *: input_2d = input.reshape(-1, in_features)
Apply a standard matrix-matrix multiplication output_2d = linear.weight @ input_2d.
Add the bias output_2d += linear.bias.reshape(1, in_features) (notice we broadcast it across all N' dimensions)
Reshape the output to have the same dimensions as input, aside from the last one: output = output_2d.reshape(*input.shape[:-1], out_features)
return output
So the leading dimension N is treated the same as the * dimensions. The documentation makes N explicit to let you know that the input has to be at least 2d, but can be as many dimensional as you wish.
| https://stackoverflow.com/questions/54444630/ |
Unsupported Wheel Error when pip installing PyTorch without Conda | I have been trying to install PyTorch in Windows 10 for Python 3.7.1
I do not have Anaconda on my machine, and do not wish to install it. I believe I have already satisfied all the necessary prerequisites (CUDA v10.0, NumPy). When I run the following installation command in the admin command line, (found on the PyTorch webpage):
pip3 install https://download.pytorch.org/whl/cu100/torch-1.0.0-cp37-cp37m-win_amd64.whl
I received the following error:
torch-1.0.0-cp37-cp37m-win_amd64.whl is not a supported wheel on this platform.
I tried downloading the wheel file in my browser, then running a modified command in my downloads directory.
pip install torch-1.0.0-cp37-cp37m-win_amd64.whl
I received the same error message. My pip version is up to date and I am attempting to install the appropriate wheel file for my Python version. This problem is unique to others, as I do not want to use Conda to install PyTorch. What is causing this problem?
| The wheel I was trying to install required 32 bit Python, I had 64 bit Python installed. Therefore, the wheel I was trying to install was not compatible with my Python version.
Checking Python Version:
I confirmed my Python version using the following command:
python -c "import struct; print(struct.calcsize('P') * 8)"
Checking Wheel Version:
64 bit wheels typically contain amd64 or similar in their title
32 bit wheels typically contain win32or similar in their title
Switching to a 64 bit Python Installaion:
The default Windows Python installer does not have a 64 bit option. To acquire 64 bit Python, navigate to python.org/downloads/windows/, and select a version that specifies x86-64 (the other versions are all 32 bit).
Credit to phd for the comment that led to this solution.
A Redditor had the same problem here.
| https://stackoverflow.com/questions/54445160/ |
AND-gate with Pytorch | I'm new to PyTorch and deep learning generally.
The code I wrote can be seen longer down.
I'm trying to learn the simple 'And' problem, which is linearby separable.
The problem is, that I'm getting poor results. Only around 2/10 times it gets to the correct answer.
Sometimes the loss.item() values is stuck at 0.250.
Just to clear up
Why does it only work 2/10 times?
.
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autog
data_x = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
data_y = np.array([[0, 0, 0, 1]]).T
data_x = autog.Variable(torch.FloatTensor(data_x))
data_y = autog.Variable(torch.FloatTensor(data_y), requires_grad=False)
in_dim = 2
out_dim = 1
epochs = 15000
epoch_print = epochs / 5
l_rate = 0.001
class NeuralNet(nn.Module):
def __init__(self, input_size, output_size):
super(NeuralNet, self).__init__()
self.lin1 = nn.Linear(input_size, output_size)
self.relu = nn.ReLU()
def forward(self, x):
out = x
out = self.lin1(out)
out = self.relu(out)
return out
model = NeuralNet(in_dim, out_dim)
criterion = nn.L1Loss()
optimizer = optim.Adam(model.parameters(), lr=l_rate)
for epoch in range(epochs):
pred = model(data_x)
loss = criterion(pred, data_y)
loss.backward()
optimizer.step()
if (epoch + 1) % epoch_print == 0:
print("Epoch %d Loss %.3f" %(epoch + 1, loss.item()))
for x, y in zip(data_x, data_y):
pred = model(x)
print("Input", list(map(int, x)), "Pred", int(pred), "Output", int(y))
| 1. Using zero_grad with optimizer
You are not using optimizer.zero_grad() to clear the gradient. Your learning loop should look like this:
for epoch in range(epochs):
optimizer.zero_grad()
pred = model(data_x)
loss = criterion(pred, data_y)
loss.backward()
optimizer.step()
if (epoch + 1) % epoch_print == 0:
print("Epoch %d Loss %.3f" %(epoch + 1, loss.item()))
In this particular case it will not have any detrimental effect, the gradient is accumulating, but as you have the same dataset looped over and over it makes barely any difference (you should get into this habit though, as you will use it throughout your deep learning journey).
2. Cost Function
You are using Mean Absolute Error which is regression loss function, not a classification one (what you do is binary classification).
Accordingly, you should use BCELoss and sigmoid activation or (I prefer it that way), return logits from the network and use BCEWithLogitsLoss, both of them calculate binary cross entropy (simplified version of cross-entropy).
See below:
class NeuralNet(nn.Module):
def __init__(self, input_size, output_size):
super(NeuralNet, self).__init__()
self.lin1 = nn.Linear(input_size, output_size)
def forward(self, x):
# You may want to use torch.nn.functional.sigmoid activation
return self.lin1(x)
...
# Change your criterion to nn.BCELoss() if using sigmoid
criterion = nn.BCEWithLogitsLoss()
...
3. Predictions
If you used the logits version, classifier learns to assign negative values to 0 label and positive to indicate 1. Your display function has to be modified to incorporate this knowledge:
for x, y in zip(data_x, data_y):
pred = model(x)
# See int(pred > 0), that's the only change
print("Input", list(map(int, x)), "Pred", int(pred > 0), "Output", int(y))
This step does not apply if your forward applies sigmoid to the output. Oh, and it's better to use torch.round instead of casting to int.
| https://stackoverflow.com/questions/54445471/ |
How to properly update the weights in PyTorch? | I'm trying to implement the gradient descent with PyTorch according to this schema but can't figure out how to properly update the weights. It is just a toy example with 2 linear layers with 2 nodes in hidden layer and one output.
Learning rate = 0.05;
target output = 1
https://hmkcode.github.io/ai/backpropagation-step-by-step/
Forward
Backward
My code is as following:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class MyNet(nn.Module):
def __init__(self):
super(MyNet, self).__init__()
self.linear1 = nn.Linear(2, 2, bias=None)
self.linear1.weight = torch.nn.Parameter(torch.tensor([[0.11, 0.21], [0.12, 0.08]]))
self.linear2 = nn.Linear(2, 1, bias=None)
self.linear2.weight = torch.nn.Parameter(torch.tensor([[0.14, 0.15]]))
def forward(self, inputs):
out = self.linear1(inputs)
out = self.linear2(out)
return out
losses = []
loss_function = nn.L1Loss()
model = MyNet()
optimizer = optim.SGD(model.parameters(), lr=0.05)
input = torch.tensor([2.0,3.0])
print('weights before backpropagation = ', list(model.parameters()))
for epoch in range(1):
result = model(input )
loss = loss_function(result , torch.tensor([1.00],dtype=torch.float))
print('result = ', result)
print("loss = ", loss)
model.zero_grad()
loss.backward()
print('gradients =', [x.grad.data for x in model.parameters()] )
optimizer.step()
print('weights after backpropagation = ', list(model.parameters()))
The result is following :
weights before backpropagation = [Parameter containing:
tensor([[0.1100, 0.2100],
[0.1200, 0.0800]], requires_grad=True), Parameter containing:
tensor([[0.1400, 0.1500]], requires_grad=True)]
result = tensor([0.1910], grad_fn=<SqueezeBackward3>)
loss = tensor(0.8090, grad_fn=<L1LossBackward>)
gradients = [tensor([[-0.2800, -0.4200], [-0.3000, -0.4500]]),
tensor([[-0.8500, -0.4800]])]
weights after backpropagation = [Parameter containing:
tensor([[0.1240, 0.2310],
[0.1350, 0.1025]], requires_grad=True), Parameter containing:
tensor([[0.1825, 0.1740]], requires_grad=True)]
Forward pass values:
2x0.11 + 3*0.21=0.85 ->
2x0.12 + 3*0.08=0.48 -> 0.85x0.14 + 0.48*0.15=0.191 -> loss =0.191-1 = -0.809
Backward pass: let's calculate w5 and w6 (output node weights)
w = w - (prediction-target)x(gradient)x(output of previous node)x(learning rate)
w5= 0.14 -(0.191-1)*1*0.85*0.05= 0.14 + 0.034= 0.174
w6= 0.15 -(0.191-1)*1*0.48*0.05= 0.15 + 0.019= 0.169
In my example Torch doesn't multiply the loss by derivative so we get wrong weights after updating. For the output node we got new weights w5,w6 [0.1825, 0.1740] , when it should be [0.174, 0.169]
Moving backward to update the first weight of the output node (w5) we need to calculate: (prediction-target)x(gradient)x(output of previous node)x(learning rate)=-0.809*1*0.85*0.05=-0.034. Updated weight w5 = 0.14-(-0.034)=0.174. But instead pytorch calculated new weight = 0.1825. It forgot to multiply by (prediction-target)=-0.809. For the output node we got gradients -0.8500 and -0.4800. But we still need to multiply them by loss 0.809 and learning rate 0.05 before we can update the weights.
What is the proper way of doing this?
Should we pass 'loss' as an argument to backward() as following: loss.backward(loss) .
That seems to fix it. But I couldn't find any example on this in documentation.
| You should use .zero_grad() with optimizer, so optimizer.zero_grad(), not loss or model as suggested in the comments (though model is fine, but it is not clear or readable IMO).
Except that your parameters are updated fine, so the error is not on PyTorch's side.
Based on gradient values you provided:
gradients = [tensor([[-0.2800, -0.4200], [-0.3000, -0.4500]]),
tensor([[-0.8500, -0.4800]])]
Let's multiply all of them by your learning rate (0.05):
gradients_times_lr = [tensor([[-0.014, -0.021], [-0.015, -0.0225]]),
tensor([[-0.0425, -0.024]])]
Finally, let's apply ordinary SGD (theta -= gradient * lr), to get exactly the same results as in PyTorch:
parameters = [tensor([[0.1240, 0.2310], [0.1350, 0.1025]]),
tensor([[0.1825, 0.1740]])]
What you have done is taken the gradients calculated by PyTorch and multiplied them with the output of previous node and that's not how it works!.
What you've done:
w5= 0.14 -(0.191-1)*1*0.85*0.05= 0.14 + 0.034= 0.174
What should of been done (using PyTorch's results):
w5 = 0.14 - (-0.85*0.05) = 0.1825
No multiplication of previous node, it's done behind the scenes (that's what .backprop() does - calculates correct gradients for all of the nodes), no need to multiply them by previous ones.
If you want to calculate them manually, you have to start at the loss (with delta being one) and backprop all the way down (do not use learning rate here, it's a different story!).
After all of them are calculated, you can multiply each weight by optimizers learning rate (or any other formula for that matter, e.g. Momentum) and after this you have your correct update.
How to calculate backprop
Learning rate is not part of backpropagation, leave it alone until you calculate all of the gradients (it confuses separate algorithms together, optimization procedures and backpropagation).
1. Derivative of total error w.r.t. output
Well, I don't know why you are using Mean Absolute Error (while in the tutorial it is Mean Squared Error), and that's why both those results vary. But let's go with your choice.
Derivative of | y_true - y_pred | w.r.t. to y_pred is 1, so IT IS NOT the same as loss. Change to MSE to get equal results (here, the derivative will be (1/2 * y_pred - y_true), but we usually multiply MSE by two in order to remove the first multiplication).
In MSE case you would multiply by the loss value, but it depends entirely on the loss function (it was a bit unfortunate that the tutorial you were using didn't point this out).
2. Derivative of total error w.r.t. w5
You could probably go from here, but... Derivative of total error w.r.t to w5 is the output of h1 (0.85 in this case). We multiply it by derivative of total error w.r.t. output (it is 1!) and obtain 0.85, as done in PyTorch. Same idea goes for w6.
I seriously advise you not to confuse learning rate with backprop, you are making your life harder (and it's not easy with backprop IMO, quite counterintuitive), and those are two separate things (can't stress that one enough).
This source is nice, more step-by-step, with a little more complicated network idea (activations included), so you can get a better grasp if you go through all of it.
Furthermore, if you are really keen (and you seem to be), to know more ins and outs of this, calculate the weight corrections for other optimizers (say, nesterov), so you know why we should keep those ideas separated.
| https://stackoverflow.com/questions/54447084/ |
Pytorch Inner Product of 3D tensor with 1D Tensor to generate 2D Tensor | Operation : I have pytorch tensor A of dimension [n x m x c] and B of dimension [1 x 1 x c]. I want to take inner product of each of 1 x 1 x c vector from A with B and hence generate a tensor C of dimension [n x m].
Inside forward function of my network at a specific step I receive tensor of dimension [N, channels, Height, Width] where N is number of images, channels is number of channels in the feature map, and height and width are of the current feature map. I also have an [N x channels] feature map from some other subnetwork. In the next step I want to carry out the above mentioned operation.
Can somebody explain the best way and functions available in pytorch to achieve such step.
I am new to pytorch and was unable to find a proper way. Tensorflow supports NHWC format but I think pytorch doesn't, so one of the way is to reshape it to [N, Height, Width, channels] and then iterate like :
# if img is reshaped to [N, H, W, C]
img
# tensor of dimension [N, C]
aud
ans = torch.empty(N, H, W, dtype=torch.double)
for batches in range(img.shape[0]):
for i in range(img.shape[1]):
for j in range(img.shape[2]):
ans[batches][i][j] = torch.dot(img[batches][i][j], aud[batches])
Any other cleaner API ?
PS : This step is required in DeepMind's paper "Object That Sound" for sound localization step.
| There is a one-liner
ans = torch.einsum('nhwc,nc->nhw', img, aud)
The API of torch.einsum can be difficult to grasp if you haven't had any experience with it before, but it's extremely powerful and generalizes a great deal of liner algebra operations (transpositions, matrix multiplications and traces).
import torch
N, H, W, C = 10, 11, 12, 13
img = torch.randn(N, H, W, C)
aud = torch.randn(N, C)
ans = torch.empty(N, H, W)
for batches in range(img.shape[0]):
for i in range(img.shape[1]):
for j in range(img.shape[2]):
ans[batches][i][j] = torch.dot(img[batches][i][j], aud[batches])
ans2 = torch.einsum('nhwc,nc->nhw', img, aud)
assert torch.allclose(ans, ans2, atol=1e-6)
Note I had to increase the assertion tolerance above the standard 1e-8 because of numerical precision issues. If einsum becomes a bottleneck in more advanced usecases have a look at opt_einsum which optimizes the order of underlying operations for performance.
| https://stackoverflow.com/questions/54458911/ |
Error with _DataLoaderIter in torch.utils.data.dataloader | I want to run a code which needs to import _DataLoaderIter from torch.utils.data.dataloader. By checking the source code for dataloader class, that method exist. However, I get the error:
Traceback (most recent call last):
File "main.py", line 4, in
import data
File "D:\Hyperspectral Data\RCAN\RCAN_TrainCode\code\data\__init__.py", line 3, in module
from dataloader import MSDataLoader
File "D:\Hyperspectral Data\RCAN\RCAN_TrainCode\code\dataloader.py", line 14, in module
from torch.utils.data.dataloader import _DataLoaderIter
ImportError: cannot import name '_DataLoaderIter'
Why is this happening?
| Your comment answers the question: the _DataLoaderIter is there in 1.0.0 (for which you are linking documentation) but not in 0.3.1, as you can check here - its name has no preceding _.
This is a textbook example why it is a bad idea to access other packages' private classes/functions (customarily prefixed with an underscore) - you have zero guarantees on the stability of their implementation and behavior. If you need their code, it's usually better to copy-paste the code to your own file, because there it is at least guaranteed to not change between updates and bug fixes to torch.
| https://stackoverflow.com/questions/54467696/ |
Pytorch - Are gradients transferred on creation of new Variables? | I have the following code:
A = Tensor of [186,3]
If I create a new empty tensor as follows:
tempTens = torch.tensor(np.zeros((186,3)), requires_grad = True).cuda()
And I apply some operations on a block of A and output it into tempTens, which I use totally for further computation, say like this:
tempTens[20,:] = SomeMatrix * A[20,:]
Will the gradients actually be transferred correctly, lets say I am having a cost function that optimizes for the output of tempTens to some ground truth
| In this case, tempTens[20,:] = SomeMatrix * A[20,:] is an in-place operation with respect to tempTens, which is generally not guaranteed to work with autograd. However, if you create a new variable by applying an operation like concatenation
output = torch.cat([SomeMatrix * A[20, :], torch.zeros(163, 3, device='cuda')], dim=0)
you will get the same result in terms of math (a matrix with first 20 rows from SomeMatrix * A[20, :] and the following 166 rows of 0s), but this will work properly with autograd. This is, generally speaking, the right way to approach this kind of problems.
| https://stackoverflow.com/questions/54469928/ |
About custom operations in Tensorflow and PyTorch | I have to implement an energy function, termed Rigidity Energy, as in Eq 7 of this paper here.
The energy function takes as input two 3D object meshes, and returns the energy between them. The first mesh is the source mesh, and the second mesh is the deformed version of the source mesh. In rough psuedo-code, the computation would go like this:
Iterate over all the vertices in the source mesh.
For every vertex, compute its covariance matrix with its neighboring vertices.
Perform SVD on the computed covariance matrix and find the rotation matrix of the vertex.
Use the computed rotation matrix, the point coordinates in the original mesh and the corresponding coordinates in the deformed mesh, to compute the energy deviation of the vertex.
Thus this energy function requires me to iterate over each point in the mesh, and the mesh could have more than 2k such points. In Tensorflow, there are two ways to do this. I can have 2 tensors of shape (N,3), one representing the points of source and the other of the deformed mesh.
Do it purely using Tensorflow tensors. That is, iterate over elements of the above tensors using tf.gather and perform the computation on each point using only existing TF operations. This method, would be extremely slow. I've tried to define loss functions that iterate over 1000s of points before, and the graph construction itself takes too much time to be practical.
Add a new TF OP as explained in the TF documentation here . This involves writing the function in CPP (and Cuda, for GPU support), and registering the new OP with TF.
The first method is easy to write, but impractically slow. The second method is a pain to write.
I've used TF for 3 years, and have never used PyTorch before, but at this point I'm considering switching to it, if it offers a better alternative for such cases.
Does PyTorch have a way of implementing such loss functions both easily and performs as fast as it would on GPU. i.e, A pythonic way of writing my own loss functions that runs on GPU, without any C or Cuda code on my part?
| As far as I understand, you are essentially asking if this operation can be vectorized. The answer is no, at least not fully, because svd implementation in PyTorch is not vectorized.
If you showed the tensorflow implementation, it would help in understanding your starting point. I don't know what you mean by finding the rotation matrix of the vertex, but I would guess this can be vectorized. This would mean that svd is the only non-vectorized operation and you could perhaps get away with writing just a single custom OP, that is the vectorized svd - which is likely quite easy, because it would amount to calling some library routines in a loop in C++.
Two possible sources of problems I see are
if the neighborhoods of N(i) in equation 7 can be of significantly different sizes (which would mean that the covariance matrices are of different sizes and vectorization would require some dirty tricks)
the general problem of dealing with meshes and neighborhoods could be difficult. This is an innate property of irregular meshes, but PyTorch has support for sparse matrices and a dedicated package torch_geometry, which at least helps.
| https://stackoverflow.com/questions/54473620/ |
how to resolve the error while installing pytorch | When i am trying to install pytorch getting an error.
All my packages are upgraded to the latest version. The error is
setup.py::build_deps::run()
Failed to run 'bash ../tools/build_pytorch_libs.sh --use-fbgemm --use-nnpack --use-mkldnn --use-qnnpack caffe2'
thank you in Advance
| I also got same error with older python versions. It resolved for me when i tried with latest python version 3.7
Hope this information may help you.
| https://stackoverflow.com/questions/54476603/ |
Can we use pytorch scatter_ on GPU | I'm trying to do one hot encoding on some data with pyTorch on GPU mode, however, it keeps giving me an exception. Can anybody help me?
Here's one example:
def char_OneHotEncoding(x):
coded = torch.zeros(x.shape[0], x.shape[1], 101)
for i in range(x.shape[1]):
coded[:,i] = scatter(x[:,i])
return coded
def scatter(x):
return torch.zeros(x.shape[0], 101).scatter_(1, x.view(-1,1), 1)
So if I give it an tensor on GPU, it shows like this:
x_train = [[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[14, 13, 83, 18, 14],
[ 0, 0, 0, 0, 0]]
print(char_OneHotEncoding(torch.tensor(x_train, dtype=torch.long).cuda()).shape)
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-62-95c0c4ade406> in <module>()
4 [14, 13, 83, 18, 14],
5 [ 0, 0, 0, 0, 0]]
----> 6 print(char_OneHotEncoding(torch.tensor(x_train, dtype=torch.long).cuda()).shape)
7 x_train[:5, maxlen:maxlen+5]
<ipython-input-53-055f1bf71306> in char_OneHotEncoding(x)
2 coded = torch.zeros(x.shape[0], x.shape[1], 101)
3 for i in range(x.shape[1]):
----> 4 coded[:,i] = scatter(x[:,i])
5 return coded
6
<ipython-input-53-055f1bf71306> in scatter(x)
7
8 def scatter(x):
----> 9 return torch.zeros(x.shape[0], 101).scatter_(1, x.view(-1,1), 1)
RuntimeError: Expected object of backend CPU but got backend CUDA for argument #3 'index'
BTW, if we simply remove the .cuda() here, everything goes one well
print(char_OneHotEncoding(torch.tensor(x_train, dtype=torch.long)).shape)
torch.Size([5, 5, 101])
| Yes, it is possible. You have to pay attention that all tensors are on GPU. In particular, by default, constructors like torch.zeros allocate on CPU, which will lead to this kind of mismatches. Your code can be fixed by constructing with device=x.device, as below
import torch
def char_OneHotEncoding(x):
coded = torch.zeros(x.shape[0], x.shape[1], 101, device=x.device)
for i in range(x.shape[1]):
coded[:,i] = scatter(x[:,i])
return coded
def scatter(x):
return torch.zeros(x.shape[0], 101, device=x.device).scatter_(1, x.view(-1,1), 1)
x_train = torch.tensor([
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0],
[14, 13, 83, 18, 14],
[ 0, 0, 0, 0, 0]
], dtype=torch.long, device='cuda')
print(char_OneHotEncoding(x_train).shape)
Another alternative are constructors called xxx_like, for instance zeros_like, though in this case, since you need different shapes than x, I found device=x.device more readable.
| https://stackoverflow.com/questions/54479547/ |
Why can't I install new version of Pytorch? | My OS is CentOS 7, and I want to install PyTorch so I did the following:
(pt_gpu) [martin@A08-R32-I196-3-FZ2LTP2 mlm]$ conda -V
conda 4.6.2
(pt_gpu) [martin@A08-R32-I196-3-FZ2LTP2 mlm]$ conda install -c anaconda pytorch-gpu
What's strange is that the installation message shows that it is installing a very old version of PyTorch:
Collecting package metadata: done
Solving environment: done
## Package Plan ##
environment location: /home/martin/anaconda3/envs/pt_gpu
added / updated specs:
- pytorch-gpu
The following packages will be downloaded:
package | build
---------------------------|-----------------
ca-certificates-2018.12.5 | 0 123 KB anaconda
certifi-2018.11.29 | py36_0 146 KB anaconda
pytorch-gpu-0.1.12 | py36_0 16.8 MB anaconda
------------------------------------------------------------
Total: 17.0 MB
The following packages will be UPDATED:
openssl pkgs/main::openssl-1.1.1a-h7b6447c_0 --> anaconda::openssl-1.1.1-h7b6447c_0
The following packages will be SUPERSEDED by a higher-priority channel:
ca-certificates pkgs/main --> anaconda
certifi pkgs/main --> anaconda
mkl pkgs/main::mkl-2017.0.4-h4c4d0af_0 --> anaconda::mkl-2017.0.1-0
pytorch-gpu pkgs/free --> anaconda
Proceed ([y]/n)? y
Downloading and Extracting Packages
certifi-2018.11.29 | 146 KB | ########################################################################################################################## | 100%
ca-certificates-2018 | 123 KB | ########################################################################################################################## | 100%
pytorch-gpu-0.1.12 | 16.8 MB | ########################################################################################################################## | 100%
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
To verify what's installed, I did:
(pt_gpu) [martin@A08-R32-I196-3-FZ2LTP2 mlm]$ python -c "import torch; print(torch.__version__)"
0.1.12
Why is it that?
| According to their official website( https://pytorch.org ) , they install package named pytorch, not pytorch-gpu.
conda install pytorch torchvision -c pytorch
| https://stackoverflow.com/questions/54484769/ |
PyTorch: Is there a way to store model in CPU ram, but run all operations on the GPU for large models? | From what I see, most people seem to be initializing an entire model, and sending the whole thing to the GPU. But I have a neural net model that is too big to fit entirely on my GPU. Is it possible to keep the model saved in ram, but run all the operations on the GPU?
| I do not believe this is possible. However, one easy work around would be to split you model into sections that will fit into gpu memory along with your batch input.
Send the first part(s) of the model to gpu and calculate outputs
Release the former part of the model from gpu memory, and send the next section of the model to the gpu.
Input the output from 1 into the next section of the model and save outputs.
Repeat 1 through 3 until you reach your models final output.
| https://stackoverflow.com/questions/54485815/ |
Pytorch Argrelmax function (or C++) | I'm trying to find the equivalent pytorch (or C++) for scipy.signal.argrelmax(), which finds the peaks in a 1D array with some padding. https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.argrelmax.html
Here's what I've come up with and it is faster than scipy.signal.argrelmax - but I'm missing a fast solution to the last step which deletes peaks within some window.
import torch
# initalize an array (not the one in plot below)
gpu_max = torch.rand(100000)
# find peaks and troughs by subtracting shifted versions
gpu_temp1 = gpu_max[1:-1]-gpu_max[:-2]
gpu_temp2 = gpu_max[1:-1]-gpu_max[2:]
# and checking where both shifts are positive;
out1 = torch.where(gpu_temp1>0, gpu_temp1*0+1, gpu_temp1*0)
out2 = torch.where(gpu_temp2>0, out1, gpu_temp2*0)
# argrelmax containing all peaks
argrelmax_gpu = torch.nonzero(out2, out=None)+1
So the top plot which marks every single relmaxpeak is pretty fast. But need the bottom one - which comes from scipy.signal.argrelmax() and uses a 30sample time window (i.e. it only returns maxima within a 60 time point window).
EDIT: I've updated code to reflect updated torch.nonzero() search. But still need to figure out how to do the last step (in figure below).
| Ok, so someone on pytorch forums did have a pretty good solution: https://discuss.pytorch.org/t/pytorch-argrelmax-or-c-function/36404
Here's the full answer in case it gets deleted:
a = #1D Array of your choice
window_maxima = torch.nn.functional.max_pool1d_with_indices(a.view(1,1,-1), width, 1, padding=width//2)[1].squeeze()
candidates = window_maxima.unique()
nice_peaks = candidates[(window_maxima[candidates]==candidates).nonzero()]
| https://stackoverflow.com/questions/54498775/ |
Get corner of rectangle near to origin in batch of tensor given any two diagonal coordinates in pytorch | Let's say I have pytorch tensor of batch of coordinates of off diagonal elements and I want to get coordinate of the corner which is near to origin. coordinates are in (x1, y1, x2, y2) form.
a = torch.tensor([[3,2,2,3], [1,1,2,2])
# expected output
[[2,2], [1,1]]
| You can just iterate over all tensors and for each of them calculate distance to four corners and take the corner with minimum distance.
import torch
a = torch.tensor([[3,2,2,3], [1,1,2,2]])
c = torch.zeros(a.shape[0], 2)
for idx, x in enumerate(a):
d1 = x[0] ** 2 + x[1] ** 2
d2 = x[2] ** 2 + x[3] ** 2
d3 = x[0] ** 2 + x[3] ** 2
d4 = x[2] ** 2 + x[1] ** 2
dmin = min(d1, d2, d3, d4)
if d1 == dmin:
c[idx] = torch.tensor([x[0], x[1]])
elif d2 == dmin:
c[idx] = torch.tensor([x[2], x[3]])
elif d3 == dmin:
c[idx] = torch.tensor([x[0], x[3]])
elif d4 == dmin:
c[idx] = torch.tensor([x[2], x[1]])
print(c) # tensor([[2., 2.], [1., 1.]])
| https://stackoverflow.com/questions/54507023/ |
More efficient way of implement this equation in pytorch (or Numpy) | I'm implementing the analytical form of this function
where k(x,y) is a RBF kernel k(x,y) = exp(-||x-y||^2 / (2h))
My function prototype is
def A(X, Y, grad_log_px,Kxy):
pass
and X, Y are NxD matrix where N is batch size and D is a dimension. So X is a batch of x with size N in the above equation grad_log_px is some NxD matrix I've computed using autograd.
Kxy is NxN matrix where each entry (i,j) is the RBF kernel K(X[i],Y[j])
The challenge here is that in the above equation, y is just a vector with dimension D. I kind of want to pass into a batch of y. (So to pass matrix Y with NxD size)
The equation is fine using loop through the batch size but I'm having trouble to implement in a more neat way
here is my attempted loop solution:
def A(X, Y, grad_log_px,Kxy):
res = []
for i in range(Y.shape[0]):
temp = 0
for j in range(X.shape[0]):
# first term of equation
temp += grad_log_px[j].reshape(D,1)@(Kxy[j,i] * (X[i] - Y[j]) / h).reshape(1,D)
temp += Kxy[j,i] * np.identity(D) - ((X[i] - Y[j]) / h).reshape(D,1)@(Kxy[j,i] * (X[i] - Y[j]) / h).reshape(1,D) # second term of equation
temp /= X.shape[0]
res.append(temp)
return np.asarray(res) # return NxDxD array
In the equation: grad_{x} and grad_{y} both dimension D
| Given that that I inferred all the dimensions of the various terms correctly here's a way to go about it. But first a summary of the dimensions (screenshot as it's easier to explain with math type setting; please verify if they are correct):
Also note the double derivative of the second term which gives:
where subscripts denote samples and superscripts denote features.
So we can create the two terms by using np.einsum (similarly torch.einsum) and array broadcasting:
grad_y_K = (X[:, None, :] - Y) / h * K[:, :, None] # Shape: N_x, N_y, D
term_1 = np.einsum('ij,ikl->ikjl', grad_log_px, grad_y_K) # Shape: N_x, N_y, D_x, D_y
term_2_h = np.einsum('ij,kl->ijkl', K, np.eye(D)) / h # Shape: N_x, N_y, D_x, D_y
term_2_h2_xy = np.einsum('ijk,ijl->ijkl', grad_y_K, grad_y_K) # Shape: N_x, N_y, D_x, D_y
term_2_h2 = K[:, :, None, None] * term_2_h2_xy / h**2 # Shape: N_x, N_y, D_x, D_y
term_2 = term_2_h - term_2_h2 # Shape: N_x, N_y, D_x, D_y
Then the result is given by:
(term_1 + term_2).sum(axis=0) / N # Shape: N_y, D_x, D_y
| https://stackoverflow.com/questions/54509150/ |
PyTorch weak_script_method decorator | I came across some code in an introduction to Word2Vec and PyTorch that I'm not quite familiar with. I haven't seen this type of code structure before.
>>> import torch
>>> from torch import nn
>>> # an Embedding module containing 10 tensors of size 3
>>> embedding = nn.Embedding(10, 3)
>>> # a batch of 2 samples of 4 indices each
>>> input = torch.LongTensor([[1,2,4,5],[4,3,2,9]])
>>> embedding(input)
tensor([[[-0.0251, -1.6902, 0.7172],
[-0.6431, 0.0748, 0.6969],
[ 1.4970, 1.3448, -0.9685],
[-0.3677, -2.7265, -0.1685]],
[[ 1.4970, 1.3448, -0.9685],
[ 0.4362, -0.4004, 0.9400],
[-0.6431, 0.0748, 0.6969],
[ 0.9124, -2.3616, 1.1151]]])
I'm a little confused about the following line of code.
>>> embedding(input)
I may have inadvertently ignored this syntax in the past, but I don't recall seeing a variable being passed to a class instance before? Referring to the PyTorch documentation where Class Embedding() is defined, is this behaviour enabled with decorator @weak_script_method wrapping def forward()? The code below suggests this may be the case?
>>> torch.manual_seed(2)
>>> torch.eq(embedding(input), embedding.forward(input)).all()
tensor(1, dtype=torch.uint8)
Why is the use of decorator @weak_script_method preferable in this case?
| No, @weak_script_method has nothing to do with it. embedding(input) follows the Python function call syntax, which can be used with both "traditional" functions and with objects which define the __call__(self, *args, **kwargs) magic function. So this code
class Greeter:
def __init__(self, name):
self.name = name
def __call__(self, name):
print('Hello to ' + name + ' from ' + self.name + '!')
greeter = Greeter('Jatentaki')
greeter('EBB')
will result in Hello to EBB from Jatentaki! being printed to stdout. Similarly, Embedding is an object which you construct by telling it how many embeddings it should contain, what should be their dimensionality, etc, and then, after it is constructed, you can call it like a function, to retrieve the desired part of the embedding.
The reason you do not see __call__ in nn.Embedding source is that it subclasses nn.Module, which provides an automatic __call__ implementation which delegates to forward and calls some extra stuff before and afterwards (see the documentation). So, calling module_instance(arguments) is roughly equivalent to calling module_instance.forward(arguments).
The @weak_script_method decorator has little to do with it. It is related to jit compatibility, and @weak_script_method is a variant of @script_method designed for internal use in PyTorch - the only message for you should be that nn.Embedding is compatible with jit, if you wanted to use it.
| https://stackoverflow.com/questions/54518808/ |
Best practices for exploration/exploitation in Reinforcement Learning | My question follows my examination of the code in the PyTorch DQN tutorial, but then refers to Reinforcement Learning in general: what are the best practices for optimal exploration/exploitation in reinforcement learning?
In the DQN tutorial, the steps_done variable is a global variable, and the EPS_DECAY = 200. This means that: after 128 steps, the epsilon threshold = 0.500; after 889 steps, the epsilon threshold = 0.0600; and after 1500 steps, the epsilon threshold = 0.05047.
This might work for the CartPole problem featured in the tutorial – where the early episodes might be very short and the task fairly simple – but what about on more complex problems in which far more exploration is required? For example, if we had a problem with 40,000 episodes, each of which had 10,000 timesteps, how would we set up the epsilon greedy exploration policy? Is there some rule of thumb that’s used in RL work?
Thank you in advance for any help.
| well, for that I guess it is better to use the linear annealed epsilon-greedy policy which updates epsilon based on steps:
EXPLORE = 3000000 #how many time steps to play
FINAL_EPSILON = 0.001 # final value of epsilon
INITIAL_EPSILON = 1.0# # starting value of epsilon
if epsilon > FINAL_EPSILON:
epsilon -= (INITIAL_EPSILON - FINAL_EPSILON) / EXPLORE
| https://stackoverflow.com/questions/54519830/ |
I was training the lstm network using pytorch and encountered this error | I was training the lstm network using pytorch and encountered this error in jupyter notebook.
RuntimeError Traceback (most recent call last)
<ipython-input-16-b6b1e0b8cad1> in <module>()
4
5 # train the model
----> 6 train(net, encoded, epochs=n_epochs, batch_size=batch_size, seq_length=seq_length, lr=0.001, print_every=10)
<ipython-input-14-43dc0cc515e7> in train(net, data, epochs, batch_size, seq_length, lr, clip, val_frac, print_every)
55
56 # calculate the loss and perform backprop
---> 57 loss = criterion(output, targets.view(batch_size*seq_length))
58 loss.backward()
59 # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs.
~\Anaconda3\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)
~\Anaconda3\lib\site-packages\torch\nn\modules\loss.py in forward(self, input, target)
902 def forward(self, input, target):
903 return F.cross_entropy(input, target, weight=self.weight,
--> 904 ignore_index=self.ignore_index, reduction=self.reduction)
905
906
~\Anaconda3\lib\site-packages\torch\nn\functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
1968 if size_average is not None or reduce is not None:
1969 reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 1970 return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
1971
1972
~\Anaconda3\lib\site-packages\torch\nn\functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
1788 .format(input.size(0), target.size(0)))
1789 if dim == 2:
-> 1790 ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
1791 elif dim == 4:
1792 ret = torch._C._nn.nll_loss2d(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: Expected object of scalar type Long but got scalar type Int for argument #2 'target'
| Cast output vector of your network to Long (you have Int) as the error says.
Oh, and please provide Minimal, Complete and Verifiable example next time you ask a question.
| https://stackoverflow.com/questions/54522426/ |
Subsets and Splits