instruction
stringlengths 13
150
| input
stringlengths 36
29.1k
| output
stringlengths 31
29.5k
| source
stringlengths 45
45
|
---|---|---|---|
Identical random crop on two images Pytorch transforms | I am trying to feed two images into a network and I want to do identical transform between these two images. transforms.Compose() takes one image at a time and produces output independent to each other but I want same transformation. I did my own coding for hflip() now I am interested to get the random crop. Is there any way to do that without writing custom functions?
| I would use workaround like this - make my own crop class inherited from RandomCrop, redefining call with
…
if self.call_is_even :
self.ijhw = self.get_params(img, self.size)
i, j, h, w = self.ijhw
self.call_is_even = not self.call_is_even
instead of
i, j, h, w = self.get_params(img, self.size)
The idea is to suppress randomizer on odd calls
| https://stackoverflow.com/questions/62473828/ |
Pytorch: Add input normalization to model (division layer) | I want to add the image normalization to an existing pytorch model, so that I don't have to normalize the input image anymore.
Say I have an existing model
model = torch.hub.load('pytorch/vision:v0.6.0', 'mobilenet_v2', pretrained=True)
model.eval()
Now I can add new layers (for example a relu) using torch.nn.Sequential:
new_model = nn.Sequential(
model,
nn.ReLU()
)
However I couldn't find a layer to do perform just a division or subtraction as needed for the input normalization here shown in numpy:
import cv2
import numpy as np
img = cv2.imread("my_img.jpg")
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = img.astype(np.float32)
mean = np.array([0.485, 0.456, 0.406], dtype=np.float32)
std = np.array([0.229, 0.224, 0.225], dtype=np.float32)
img = img / 255.0
img = img - mean
img = img / std
img = np.transpose(img, (2, 0, 1))
img = np.expand_dims(img, axis=0)
The goal is that normalization is eventually done on GPU to save time during inference. Also I cannot use torchvision transforms as those operation are not stored inside the model itself. For example, if I want to save the model to disk (in order to convert it to tflite using onnx) the torchvision transform operations will not be saved along with the model. Is there an elegant way of doing this?
(preferably without using a linear layer, which would fix my model input size, which should be flexible as my real model is fully convolutional)
| Untested code which hopefully you can vet yourself.
import torch.nn as nn
cuda0 = torch.device('cuda:0')
class Normalize(nn.Module):
def __init__(self, mean, std):
super(Normlize, self).__init__()
self.mean = torch.tensor(mean, device=cuda0)
self.std = torch.tensor(std, device=cuda0)
def forward(self, input):
x = input / 255.0
x = x - self.mean
x = x / self.std
return x
In your model you can do
new_model = nn.Sequential(
Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
model,
nn.ReLU()
)
| https://stackoverflow.com/questions/62475627/ |
How to run a pre-trained pytorch model on the GPU? | Here I am trying to use the mobilenetv2 mobile to train on a custom dataset. I can get it to work on the CPU, but I would prefer to run it on the GPU. Instead, I am getting errors like these:
RuntimeError: Expected object of backend CPU but got backend CUDA for argument #2 'weight'
RuntimeError: Expected object of backend CPU but got backend CUDA for argument #4 'mat1
So like my Post asks how can I get the pre-trained model to run on the GPU?
MobileNet = models.mobilenet_v2(pretrained = True)
if torch.cuda.is_available():
MobileNet.cuda()
for param in MobileNet.parameters():
param.requires_grad = False
torch.manual_seed(50)
MobileNet.classifier = nn.Sequential(nn.Linear(1280, 1000), nn.ReLU(), nn.Dropout(0.5), nn.Linear(1000,3), nn.LogSoftmax(dim=1))
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(MobileNet.classifier.parameters(), lr=0.001)
train_transform = transforms.Compose([
transforms.RandomRotation(10), # rotate +/- 10 degrees
transforms.RandomHorizontalFlip(), # reverse 50% of images
transforms.Resize(224), # resize shortest side to 224 pixels
transforms.CenterCrop(224), # crop longest side to 224 pixels at center
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
])
test_transform = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
])
train_data = datasets.ImageFolder('C:/Users/mixv/Pictures/Summer/datasets/train', transform=train_transform)
test_data = datasets.ImageFolder('C:/Users/mix/Pictures/Summer/datasets/test', transform=test_transform)
torch.manual_seed(42)
batch=64
train_loader = DataLoader(train_data, batch_size=batch, shuffle=True)
test_loader = DataLoader(test_data, batch_size=batch, shuffle=True)
if torch.cuda.is_available():
train_loader = DataLoader(train_data, batch_size=batch, shuffle=True, pin_memory = True)
test_loader = DataLoader(test_data, batch_size=batch, shuffle=True, pin_memory = True)
epochs = 10
train_losses = []
test_losses = []
train_correct = []
test_correct = []
start_time =time.time()
for i in range(epochs):
trn_corr = 0
tst_corr = 0
# Run the training batches
for b, (images, labels) in enumerate(train_loader):
if torch.cuda.is_available():
images = images.cuda()
labels = labels.cuda()
b+=1
# Apply the model
y_pred = MobileNet(images)
loss = criterion(y_pred, labels)
# Tally the number of correct predictions
predicted = torch.max(y_pred.data, 1)[1]
batch_corr = (predicted == labels).sum()
trn_corr += batch_corr
accuracy = trn_corr.item()*100/(b*batch)
# Update parameters
optimizer.zero_grad()
loss.backward()
optimizer.step()
| As the RuntimeError said, some weights are still in cpu. One possible flaw I suspect is MobileNet.classifier = nn.Sequential(nn.Linear(1280, 1000), nn.ReLU(), nn.Dropout(0.5), nn.Linear(1000,3), nn.LogSoftmax(dim=1)) is done after MobileNet.cuda(), which mean these new created weight probably did not be sent to gpu. Try reverse these two's sequence and see
| https://stackoverflow.com/questions/62476250/ |
How is data augmentation done in each epoch? | I'm new to PyTorch and want to apply data augmentation to the datasets on each epoch. I
train_transform = Compose([
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomCrop(32, padding=4),
transforms.ToTensor(),
transforms.Normalize([0, 0, 0], [1, 1, 1])
])
test_transform = Compose([
transforms.ToTensor(),
transforms.Normalize([0, 0, 0], [1, 1, 1])
])
cifar10_train = CIFAR10(root = "/data", train=True, download = True, transform=train_transform)
train_loader = torch.utils.data.DataLoader(cifar10_train, batch_size=128, shuffle=True)
cifar10_test = CIFAR10(root = "/data", train=False, download = True, transform=test_transform)
test_loader = torch.utils.data.DataLoader(cifar10_test, batch_size=128, shuffle=True)
I got the code from an online tutorial. So from what I understand train_transform and test_transform is the augmentation code while cifar10_train and cifar10_test are where data is loaded and augmentation is done at the same time. Does this mean data augmentation is only done once before training? What if I want to do data augmentation for each epoch.
| I think you have some misunderstandings in your code. The cifar10_train and cifar10_test actually load the dataset into python (this data is not augmented and is the raw data), then the data goes through the transforms. In most cases, the training set is where the data augmentation is done, and the testing set is not augmented because it is supposed to replicate real-world data. The transforms (train_transform and test_transforms) are what decide how the data is augmented, normalized, and converted into PyTorch Tensors, you can think of it as a set of guidelines/rules for the dataset to follow. As mentioned before, the training set only gets augmented, which is why the train_transform has RandomHorizontalFlip and RandomCrop (which does augmentation), and why test_transforms does not have RandomHorizontalFlip and RandomCrop. The loaders (train_loader and test_loader) is what splits the data into batches (groups of data), and applies the transforms to the cifar10 dataset.
| https://stackoverflow.com/questions/62476547/ |
Pytorch for loop inefficience | I have a efficient issue with some tensor for loop.
I’m extracting the features from the last layer of a CNN through a image data loader (I’m using batch size 8). Im getting the euclidean distance of the batch tensor and a table with previous features.
I want to add to the table a tensor every time all the tensors in the table are above a threshole. I have implemented a successful running code but the loop i use its not efficient and im wondering how i could do something similar using something more efficient rather than this secuential way.
for i, data in enumerate(dataloader, 0):
input, label = data
input, label = input.to(device), label.to(device)
n,c h,w = input.size()
outputs = model(input)
if (i == 0):
features_list = torch.cat( (features_list, outputs[0].view(1,-1)), 0)
dist_tensores = torch.cdist(outputs, features_list, p=2.0)
activation = torch.gt(dist_tensores, AVG, out=torch.cuda.FloatTensor(len(outputs), len(features_list)))
counter = len(features_list)
activation_list = torch.sum(activation, dim=0)
for x in range(len(activation)):
if (torch.sum(activation[x], dim=0) == counter):
features_list = torch.cat( (features_list, outputs[x].view(1,-1)), 0)
The last loop is the part i want to change but i really don´t know how to assign and add the tensor i want if it's not by creating a loop where i can control the tensor to add.
| idx = activation.sum(1) == counter
features_list = torch.cat((features_list, outputs[idx]), 0)
This would replace the loop and save computational and inefficiences issues.
| https://stackoverflow.com/questions/62480165/ |
torch.einsum 'RuntimeError: dimension mismatch for operand 0: equation 4 tensor 2' | I'm trying to manually calculate a gradient of a matrix and I can do it by using numpy but I don't know to do the same thing in pytorch.
the equation in NumPy is
def grad(A, W0, W1, X):
dim = A.shape
assert len(dim) == 2
A_rows = dim[0]
A_cols = dim[1]
gradient = (np.einsum('ik, jl', np.eye(A_cols, A_rows), (((A).dot(X)).dot(W0)).dot(W1).T) + np.einsum('ik, jl', A, ((X).dot(W0)).dot(W1).T))
return gradient
I wrote a function in pytorch but it's giving me an error saying 'RuntimeError: dimension mismatch for operand 0: equation 4 tensor 2'
The function I wrote using pytorch is
def torch_grad(A, W0, W1, X):
dim = A.shape
A_rows = dim[0]
A_cols = dim[1]
W0W1 = torch.mm(W0, W1)
AX = torch.mm(A, X)
AXW0W1 = torch.mm(AX, W0W1)
XW0W1 = torch.mm(X, W0W1)
print(torch.eye(A_cols, A_rows).shape, torch.t(AXW0W1).shape)
e1 = torch.einsum('ik jl', torch.eye(A_cols, A_rows), torch.t(AXW0W1))
e2 = torch.einsum('ik, jl', A, torch.t(XW0W1))
return e1 + e2
I would appreciate if someone can show me how to implement the numpy code in pytorch.
Thanks!
| You are missing a comma in the first torch.einsum call.
e1 = torch.einsum('ik, jl', torch.eye(A_cols, A_rows), torch.t(AXW0W1))
Besides the typo, that's not how the gradients with respect to A are calculated, and it fails when A and AX have different sizes, which would be otherwise valid for the forward pass. For the e1, that should be a matrix multiplication, maybe that was your intention, in which case the torch.einsum should be 'ik, kl', but that's just an overly complicated way to perform a matrix multiplication and using torch.mm is simpler and more efficient. And the e2 is not involved in anything calculation that was performed with respect to A, therefore it is not part of gradients.
def torch_grad(A, W0, W1, X):
# Forward
W0W1 = torch.mm(W0, W1)
AX = torch.mm(A, X)
AXW0W1 = torch.mm(AX, W0W1)
XW0W1 = torch.mm(X, W0W1)
# Backward / Gradients
rows, cols = AXW0W1.size()
grad_AX = torch.mm(torch.eye(rows, cols), W0W1.t())
grad_A = torch.mm(grad_AX, X.t())
return grad_A
# Autograd version to verify that the gradients are correct
def torch_autograd(A, W0, W1, X):
# Forward
W0W1 = torch.mm(W0, W1)
AX = torch.mm(A, X)
AXW0W1 = torch.mm(AX, W0W1)
XW0W1 = torch.mm(X, W0W1)
# Backward / Gradients
rows, cols = AXW0W1.size()
AXW0W1.backward(torch.eye(rows, cols))
return A.grad
# requires_grad=True for the autograd version to track
# gradients with respect to A
A = torch.randn(3, 4, requires_grad=True)
X = torch.randn(4, 5)
W0 = torch.randn(5, 6)
W1 = torch.randn(6, 5)
grad_result = torch_grad(A, W0, W1, X)
autograd_result = torch_autograd(A, W0, W1, X)
torch.equal(grad_result, autograd_result) # => True
| https://stackoverflow.com/questions/62481079/ |
Classification with pretrained pytorch vgg16 model and its classes | I wrote a image vgg classification model with pytorch's pretrained vgg16 model.
import matplotlib.pyplot as plt
import numpy as np
import torch
from PIL import Image
import urllib
from skimage.transform import resize
from skimage import io
import yaml
# Downloading imagenet 1000 classes list
file = urllib. request. urlopen("https://gist.githubusercontent.com/yrevar/942d3a0ac09ec9e5eb3a/raw/238f720ff059c1f82f368259d1ca4ffa5dd8f9f5/imagenet1000_clsidx_to_labels.txt")
classes = ''
for f in file:
classes = classes + f.decode("utf-8")
classes = yaml.load(classes)
# Downloading pretrained vgg16 model
model = torch.hub.load('pytorch/vision:v0.6.0', 'vgg16', pretrained=True)
print(model)
for param in model.parameters():
param.requires_grad = False
url, filename = ("https://raw.githubusercontent.com/pytorch/hub/master/dog.jpg", "dog.jpg")
image=io.imread(url)
plt.imshow(image)
plt.show()
# resize to 224x224x3
img = resize(image,(224,224,3))
plt.imshow(img)
plt.show()
# Normalizing input for vgg16
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
img1 = mean*img+std
img1 = np.clip(img1,0,1)
img1 = torch.from_numpy(img1).unsqueeze(0)
img1 = img1.permute(0,3,2,1) # batch_size x channels x height x width
model.eval()
pred = model(img1.float())
print(classes[torch.argmax(pred).numpy().tolist()])
The code works fine but its outputting wrong classes. I am not sure where I did wrong but If I have to guess it might be the imagenet yaml classes list or at the normalizing input image. Can anyone tell me where I am making the mistakes?
| There are some issues with the image preprocessing. Firstly, the normalisation is calculated as (value - mean) / std), not value * mean + std. Secondly, the values should not be clipped to [0, 1], the normalisation purposely shifts the values away from [0, 1]. Secondly, the image as NumPy array has shape [height, width, 3], when you permute the dimensions you swap the height and width dimension, creating a tensor with shape [batch_size, channels, width, height].
img = resize(image,(224,224,3))
# Normalizing input for vgg16
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
img1 = (img1 - mean) / std
img1 = torch.from_numpy(img1).unsqueeze(0)
img1 = img1.permute(0, 3, 1, 2) # batch_size x channels x height x width
Instead of doing that manually, you can use torchvision.transforms.
from torchvision import transforms
preprocess = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
img = resize(image,(224,224,3))
img1 = preprocess(img)
img1 = img1.unsqueeze(0)
If you use PIL to load the images, you could also resize the images by adding transforms.Resize((224, 224)) to the preprocessing pipeline, or you could even add transforms.ToPILImage() to first convert the image to a PIL image (transforms.Resize requires a PIL image).
| https://stackoverflow.com/questions/62482336/ |
Sampling data batch wise from tensor Pytorch | I have train_x and valid_x splited from trainX ,train_y and valid_y splited from trainY and they are having shapes as per below. i want to classify images of labels LABELS = set(["Faces", "Leopards", "Motorbikes", "airplanes"]).
print(train_x.shape, len(train_y))
torch.Size([1339, 96, 96, 3]) 1339
print(valid_x.shape, len(valid_y))
torch.Size([335, 96, 96, 3]) 335
print(testX.shape, len(testY))
torch.Size([559, 96, 96, 3]) 559
so i want to use regular train/valid on data batch-wise code as per below :
#train the network
n_epochs = 20
valid_loss = []
train_loss = []
for epoch in range(1,n_epochs+1):
cur_train_loss = 0.0
cur_valid_loss = 0.0
#####################
#### Train model ####
#####################
cnn_model.train()
for data, target in trainLoader:
if train_on_gpu:
data, target = data.cuda(), target.cuda()
optimizer.zero_grad()
output = cnn_model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
cur_train_loss += loss.item() * data.size(0)
########################
#### Validate model ####
########################
cnn_model.eval()
for data, target in validLoader:
if train_on_gpu:
data, target = data.cuda(), target.cuda()
output = cnn_model(data)
loss = criterion(output, target)
cur_valid_loss += loss.item() * data.size(0)
# calculate avg loss
avg_train_loss = cur_train_loss / len(trainLoader.sampler)
avg_valid_loss = cur_valid_loss / len(validLoader.sampler)
train_loss.append(avg_train_loss)
valid_loss.append(avg_valid_loss)
print('Epoch: {} \t train_loss: {:.6f} \t valid_loss: {:.6f}'.format(epoch, avg_train_loss, avg_valid_loss))
so what i have to do for that ?
i have search for that but nothing specific i found out. i want to use pytorch for this. i have built model for another problem same like this but in that i have used DataLoader for loading one batch of data at a time for training and validation.
| You can create a dataset with torch.utils.data.TensorDataset, where each sample of train_x is associated with its corresponding label in train_y, such that the DataLoader can create batches as you are used to.
from torch.utils.data import DataLoader, TensorDataset
train_dataset = TensorDataset(train_x, train_y)
train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
valid_dataset = TensorDataset(valid_x, valid_y)
valid_dataloader = DataLoader(valid_dataset, batch_size=BATCH_SIZE, shuffle=False)
test_dataset = TensorDataset(testX, testY)
test_dataloader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False)
| https://stackoverflow.com/questions/62484661/ |
Why pytorch transformer src_mask doesn't block positions from attending? | I am trying to train word embedding with transformer encoder by masking the word itself with diagonal src_mask:
def _generate_square_subsequent_mask(self, sz):
mask = torch.diag(torch.full((sz,),float('-inf')))
return mask
def forward(self, src):
if self.src_mask is None or self.src_mask.size(0) != len(src):
device = src.device
mask = self._generate_square_subsequent_mask(len(src)).to(device)
self.src_mask = mask
src = self.embedding(src) * math.sqrt(self.ninp)
src = self.dropout(src)
src = self.pos_encoder(src)
src = self.transformer_encoder(src, self.src_mask)
output = self.decoder(src) # Linear layer
return output
After training the model predicts exactly the same sentence from the input. If I change any word in the input - it predict the new word. So the model doesn't block according to the mask.
Why is it ?
I understand that there is a mistake in my logic because BERT would probably be much simpler if it worked. But where am I wrong ?
Edit:
I am using the a sequence of word indices as input. Output is the same sequence as input.
| As far as I understand - the model doesn't prevent each word to indirectly “see itself” in multylayer context. I tried to use one layer - it looks like the model works. But training is too slow.
| https://stackoverflow.com/questions/62485231/ |
How to use a layer with gradient but without weight adjustment? | Is it possible to mark part of the forward pass to only backpropagate the gradient but not to adjust weights?
In the following example code I have a Module that uses only one layer (one set of parameters) but it is used twice in the forward step. During the optimization I would expect the weights to be adjusted twice as well. If I want to only adjust the weights for one of the layer usages, what can I do?
import torch
class ExampleModel(torch.nn.Module):
def __init__(self, dim) -> None:
super(ExampleModel, self).__init__()
self.linear = torch.nn.Linear(dim, dim)
def forward(self, x):
out1 = self.linear(x) # backprop gradients and adjust weights here
out2 = self.linear(out1) # only backprop gradients here
return out2
# Random input output data for this example
N, D = 64, 100
x = torch.randn(N, D)
y = torch.randn(N, D)
model = ExampleModel(D)
criterion = torch.nn.MSELoss(reduction='sum')
optimizer = torch.optim.Adam(model.parameters())
y_pred = model(x)
loss = criterion(y_pred, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
The following will not work since with torch.no_grad() no gradient at all is backpropagated:
def forward(self, x):
out1 = self.linear(x) # backprop gradients and adjust weights here
with torch.no_grad():
out2 = self.linear(out1) # only backprop gradients here
return out2
I can not simply exclude the parameters from the optimization since they need to be optimized in the first part (i.e. out1 = self.linear(x)).
For the same reason I can also not set a learning rate of 0 for these parameters.
What else can I do to achieve this?
| One way to do it is to use requires_grad_ to temporarily disable gradients on the layer's parameters:
def forward(self, x):
out1 = self.linear(x) # backprop gradients and adjust weights here
self.linear.requires_grad_(False)
out2 = self.linear(out1) # only backprop gradients here
self.linear.requires_grad_(True)
return out2
This still lets gradients flow through the activations; it merely stops them from reaching the parameters.
You could also consider manipulating the weight tensors manually and calling .detach():
import torch.nn.functional as F
def forward(self, x):
out1 = self.linear(x)
out2 = F.linear(out1, self.linear.weight.detach(), self.linear.bias.detach())
return out2
| https://stackoverflow.com/questions/62487201/ |
DeepFix - Location Biased Convolution | I got a question regarding this paper: https://arxiv.org/pdf/1510.02927.pdf
In the Network Architecture they implement something called location biased convolution.
Basically it is 16 2d-gausians appended to the 512 filters of the convolutional layer (See figure 5 from the paper)
Picture of Location Biased Convolution.
I want to implement this in PyTorch, but have no clue how to add fixed filters to a convolutional block. The weights should be trained as discussed in the paper.
Can anyone give a hint of what to do or has done this before?
| From what it looks like in the figure you provided, they append the location priors to the data, i.e.
location_priors = generate_gaussians(positions, variances, data.size())
data_w_loc_priors = T.cat((data, location_priors), dim=1)
Now, the number of in_channels for your convolution just needs to be adjusted accordingly: If you had 512 in_channels before, you now have 512 + number of location priors.
| https://stackoverflow.com/questions/62490528/ |
How to do Class Activation Mapping in pytorch vgg16 model? | I wrote a pretrained vgg16 model for image classification and its layers are
VGG(
(features): Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU(inplace=True)
(2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(3): ReLU(inplace=True)
(4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(6): ReLU(inplace=True)
(7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(8): ReLU(inplace=True)
(9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(11): ReLU(inplace=True)
(12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(13): ReLU(inplace=True)
(14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(15): ReLU(inplace=True)
(16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(17): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(18): ReLU(inplace=True)
(19): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(20): ReLU(inplace=True)
(21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(22): ReLU(inplace=True)
(23): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(24): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(25): ReLU(inplace=True)
(26): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(27): ReLU(inplace=True)
(28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(29): ReLU(inplace=True)
(30): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
(avgpool): AdaptiveAvgPool2d(output_size=(7, 7))
(classifier): Sequential(
(0): Linear(in_features=25088, out_features=4096, bias=True)
(1): ReLU(inplace=True)
(2): Dropout(p=0.5, inplace=False)
(3): Linear(in_features=4096, out_features=4096, bias=True)
(4): ReLU(inplace=True)
(5): Dropout(p=0.5, inplace=False)
(6): Linear(in_features=4096, out_features=1000, bias=True)
)
)
After some initial hick-up its now working fine. I want to use this model for class activation mapping (CAM) for visualizing CNN outputs. I know that in order to do that first we have to get the activations of last convolutional layer in vgg16 then the weight matrix of the last fully connected layer and lastly take the dot product of the two.
First I got the class index for the query image using this code
model.eval()
pred = model(img1.float())
class_idx = torch.argmax(pred).detach().numpy().tolist()
classes[class_idx]
Then I fetched the input images last convolutional layer activations which is of the size torch.Size([1, 512, 14, 14])
last_conv_feat = torch.nn.Sequential(*list(model.features)[:30])
pred_a = last_conv_feat(img1.float())
print(pred_a.shape)
After this I extracted the weights of the fully connected layers of vgg16 classifier and it has a shape of torch.Size([1000, 4096])
model.classifier[6].weight.shape
From this weight matrix then I recovered the weight parameters for the relevant class index
w_idx = model.classifier[6].weight[class_idx] # torch.Size([4096])
The problem is the shape of the convolutional activation matrix and the fully connected layer doest match, one is [1, 512, 14, 14] and the other is [4096]. How do I take dot product of these two matrix and get the CAM output?
| This particular model isn't suitable for the simple approach you've pointed out. The CAM you refer to are extracted from models that have only one linear layer at the end, preceeded by a global average pooling layer, like this
features = MyConvolutions(x)
pooled_features = AveragePool(features)
predictions = Linear(pooled_features)
This typically works with ResNet architectures or one of their many derivates. Hence, my recommendation would be that unless there's a specific reason to use VGG you adopt a ResNet architecture.
------- EDIT -------
If you want to go with VGG, there are two options:
The easy one: cut off the VGG's last three (linear) layers, replace them by AveragePooling and a single Linear layer and finetune for ImageNet or whatever dataset you are using.
Approximate a CAM by converting VGG's last three layers into convolutional layers (i.e. 4096x512x7x7 with no padding and then 4096x4096x1x1 and 1000x4096x1x1), and reorgnise the parameters. This whole thing has only convolutional layers now and you can operate it like a huge convolutional filter. Only problem: It's output is still size 1x1. Therefore, you will need to enlarge your image (try maybe 2x) and then convolve it with the newly created fully-convolutional network. This gives you an approximate CAM.
| https://stackoverflow.com/questions/62494963/ |
Explanation behind the following Pytorch results | I am trying to get a deeper understanding of how Pytorch's autograd works. I am unable to explain the following results:
import torch
def fn(a):
b = torch.tensor(5,dtype=torch.float32,requires_grad=True)
return a*b
a = torch.tensor(10,dtype=torch.float32,requires_grad=True)
output = fn(a)
output.backward()
print(a.grad)
The output is tensor(5.). But my question is that the variable b is created within the function and so should be removed from memory after the function returns a*b right? So when I call backward how is the value of b still present for allowing this computation?
As far as I understand each operation in Pytorch has a context variable which tracks "which" tensor to use for backward computation and there are also versions present in each tensor, and if the version changes then backward should raise an error right?
Now when I try to run the following code,
import torch
def fn(a):
b = a**2
for i in range(5):
b *= b
return b
a = torch.tensor(10,dtype=torch.float32,requires_grad=True)
output = fn(a)
output.backward()
print(a.grad)
I get the following error: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor []], which is output 0 of MulBackward0, is at version 5; expected version 4 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).
But if I run the following code, there is no error:
import torch
def fn(a):
b = a**2
for i in range(2):
b = b*b
return b
def fn2(a):
b = a**2
c = a**2
for i in range(2):
c *= b
return c
a = torch.tensor(5,dtype=torch.float32,requires_grad=True)
output = fn(a)
output.backward()
print(a.grad)
output2 = fn2(a)
output2.backward()
print(a.grad)
The output for this is :
tensor(625000.)
tensor(643750.)
So for a standard computation graphs with quite a few variables, in the same function, I am able to understand how the computation graph works. But when there is a variable changing before the call of backward function, I am having a lot of trouble understanding the results. Can someone explain?
| Please note that b *=b is not same as b = b*b.
It is perhaps confusing, but the underlying operations vary.
In case of b *=b, an in-place operation takes place which messes up with the gradients and hence the RuntimeError.
In case of b = b*b, two tensor objects gets multiplied and the resulting object is assigned the name b. Thus no RuntimeError when you run this way.
Here is a SO question on the underlying python operation: The difference between x += y and x = x + y
Now what is the difference between fn in first case and fn2 in the second case? The operation c*=b does not destroy the graph links to b from c. The operation c*=c would make it impossible to have a graph connecting two tensors via an operation.
Well, I cannot work with tensors to showcase that because they raise RuntimeError. So I'll try with python list.
>>> x = [1,2]
>>> y = [3]
>>> id(x), id(y)
(140192646516680, 140192646927112)
>>>
>>> x += y
>>> x, y
([1, 2, 3], [3])
>>> id(x), id(y)
(140192646516680, 140192646927112)
Notice that there is no new object created. So it is not possible to trace from the output to initial variables. We cannot distinguish the object_140192646516680 to be an output or an input. So how does one create a graph with that..
Consider the following alternate case:
>>> a = [1,2]
>>> b = [3]
>>>
>>> id(a), id(b)
(140192666168008, 140192666168264)
>>>
>>> a = a + b
>>> a, b
([1, 2, 3], [3])
>>> id(a), id(b)
(140192666168328, 140192666168264)
>>>
Notice that the new list a is in fact a new object with id 140192666168328. Here we can trace that the object_140192666168328 came from the addition operation between two other objects object_140192666168008 and object_140192666168264. Thus a graph can be dynamically created and gradients can be propagated back from output to previous layers.
| https://stackoverflow.com/questions/62496172/ |
Can I extract all indices that correspond to a certain key in a pytorch tensor? | Say I have a pytorch tensor tensor([3,5,7,3,9,3,0]). I'd like to extract the indices where 3 appears, i.e. tensor([0,3,5]). Is there a built-in function for this?
| There is a dedicated function for this:
torch.where(my_tensor == the_number)
| https://stackoverflow.com/questions/62499307/ |
RuntimeError: _th_exp_out not supported on CUDAType for Long | Questions and Help
I'm trying to finetune a transformer model for question answering, and am using the BCEWithLogitsLoss function.
However when I try calculating loss i get this error:
RuntimeError: _th_exp_out not supported on CUDAType for Long
I'm inputting matrices with the shape and dtype of [16, 2] and Long
Bud sadly I've no idea to solve this. I tried using another dtype (int32, float32, double), which didn't work.
Here is the code:
def loss_fn(self, preds, labels):
return torch.nn.BCEWithLogitsLoss()(preds, labels)
def train_fn(self, dataloader, model, optimizer, device):
# Some other stuff here
pred = model(
token_ids = token_ids,
attention_mask = attention_mask,
token_type_ids = token_type_ids)
start_scores = torch.argmax(pred[0], dim=1)
end_scores = torch.argmax(pred[1], dim=1)
pred = torch.tensor(list(zip(start_scores, end_scores)))
pred = pred.to(device, dtype=torch.long)
batch_loss = self.loss_fn(pred, label)
| Passing both, pred and label as float worked in my case.
| https://stackoverflow.com/questions/62503769/ |
pretrained fasterrcnn_resnet50_fpn: "forward() takes 2 positional arguments but 5 were given" on single image test | I am receving an error when executing the code below:
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision.models.detection import fasterrcnn_resnet50_fpn
import PIL.Image as Image
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
model = fasterrcnn_resnet50_fpn(pretrained=True)
model.roi_heads = nn.Sequential()
model.to(device)
img = Image.open('frame_00001.jpg')
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])])
img = transform(img).unsqueeze(0).to(device)
model.eval()
output = model(img)
The last line causes a "TypeError: forward() takes 2 positional arguments but 5 were given."
The size of img is [1, 3, 960, 1280].
If I add square brackets around img before passing into the model (output = model([img])), I get a "ValueError: images is expected to be a list of 3d tensors of shape [C, H, W], got torch.Size([1, 3, 960, 1280])." Then, if I use "img.view(3, 960, 1280)," I get the original error again.
What is the solution to this problem? Thank you.
| I'm not sure what you're trying to do with the line:
model.roi_heads = nn.Sequential()
This line is causing the problem, I ran you're code excerpt without this line and it worked as expected (minus a few warnings about deprecation coming from the model being used, but the output looks reasonable)
| https://stackoverflow.com/questions/62504048/ |
PyTorch save prediction as CSV for each epoch | I'm trying save the predictions I am getting from a model in PyTorch as csv. The following code. However, the code seem to overwrite the prediction at each epoch and the final .csv file only contains 3 values. Any idea what I am doing wrong please:
output = model(images)
preds = output.sum(dim=[1,2,3])
np.savetxt('preds.csv', preds.detach())
| Assuming your output will be float, you can map that to str and apply join as a comma separated string, finally append row to csv.
import pandas as pd
import numpy as np
import torch
output = torch.rand(5,5,5,5)
preds = output.sum(dim=[1,2,3])
print(preds)
with open('preds.csv','a') as fd:
fd.write( ','.join(map(str, preds.detach().tolist())) + '\n')
| https://stackoverflow.com/questions/62504157/ |
Unable to load quantized pytorch mobile model on android | I am struggling to get my quantized pytorch mobile model (custom MobilenetV3) running on android. I have followed this tutorial https://pytorch.org/tutorials/advanced/static_quantization_tutorial.html and I managed to quantize my model without any problems. However, when I try to load the model via. module = Module.load(assetFilePath(this, MODEL_NAME));
I get the following Exception:
Unknown builtin op: quantized::linear_unpack_fp16.
Could not find any similar ops to quantized::linear_unpack_fp16. This
op may not exist or may not be currently supported in TorchScript.
Why are there even float16 values in the quantized model, I thought quantization would replace all float32 vlaues with qint8/quint8? Any ideas on how this can be fixed?
This is how the pytorch model was quantized and saved:
torch.quantization.get_default_qconfig(backend='qnnpack')
model.qconfig = torch.quantization.default_qconfig
torch.quantization.prepare(model, inplace=True)
torch.quantization.convert(model, inplace=True)
traced_script_module = torch.jit.trace(model,dummyInput)
traced_script_module.save("model/modelQuantized.pt")
| I found that this error was caused by a version mismatch between the pytorch version that was used for model quantization and pytorch_android.
The model was quantized with pytorch 1.5.1 torchvision 0.6.1 cudatoolkit 10.2.89 but I used org.pytorch:pytorch_android:1.4.0 for building.
Switching to org.pytorch:pytorch_android:1.5.0 solved it.
| https://stackoverflow.com/questions/62506729/ |
cannot install pip install torchvision | I am using python 3.8.3 version, I tried to install torchvision and torch module and faced this error, none of them are installed. The error comes as ERROR:could not find a version that satisfies the requirement torch==1.4.0(from versions:0.1.2,0.1.2,post1,0.1.2.post2)
Error:No matching distribution found for torch==1.4.0
| According to PyTorch's website, you must specify if you are using cpu or the version of CUDA when installing from pip.
For instance, if I wanted to install on a Linux system without CUDA, version 1.5.1 of PyTorch, I would run:
pip install torch==1.5.1+cpu torchvision==0.6.1+cpu -f https://download.pytorch.org/whl/torch_stable.html
You can use the link I provided above to get the syntax for your specific environment.
| https://stackoverflow.com/questions/62513412/ |
Finetuning embeddings with torchtext - nn.Embedding vs. nn.Embedding.from_pretrained | I have been working with pretrained embeddings (Glove) and would like to allow these to be finetuned. I currently use embeddings like this:
word_embeddingsA = nn.Embedding(vocab_size, embedding_length)
word_embeddingsA.weight = nn.Parameter(TEXT.vocab.vectors, requires_grad=False)
Should I simply set requires_grad=True to allow the embeddings to be trained? Or should I do something like this
word_embeddingsA = nn.Embedding.from_pretrained(TEXT.vocab.vectors, freeze=False)
Are these equivalent, and do I have a way to check that the embeddings are getting trained?
| Yes they are equivalent as states in embedding:
freeze (boolean, optional) – If True, the tensor does not get updated in the learning process. Equivalent to embedding.weight.requires_grad = False. Default: True
If word_embeddingsA.requires_grad == True, then embedding is getting trained, else it's not.
| https://stackoverflow.com/questions/62515985/ |
Using PyTorch for computing derivative of a function | When I execute the code below:
import torch
def g(x):
return 4*x + 3
x=3.0
g_hat=torch.tensor(g(x), requires_grad= True)
g_hat.backward()
I get the following output:
>>>g_hat.grad
tensor(1.)
But this is not the result that I was expecting to get from my code above... what I want to do is, I want to find the value of dg/dx, at x = 3.0 (so in the example above, the correct output should be tensor(4.)).
How can I achieve this with PyTorch? or if I can't carry out this task with PyTorch, how can I do this type of task easily on Python?
Thank you,
| x = torch.autograd.Variable(torch.Tensor([1.0]),requires_grad=True)
y = 4 * x + 3
y.backward()
x.grad
Works fine.
| https://stackoverflow.com/questions/62526583/ |
Hugginface transformers module not recognized by anaconda | I am using Anaconda, python 3.7, windows 10.
I tried to install transformers by https://huggingface.co/transformers/ on my env.
I am aware that I must have either pytorch or TF installed, I have pytorch installed - as seen in anaconda navigator environments.
I would get many kinds of errors, depending on where (anaconda / prompt) I uninstalled and reinstalled pytorch and transformers. Last attempt using
conda install pytorch torchvision cpuonly -c pytorch and
conda install -c conda-forge transformers
I get an error:
from transformers import BertTokenizer
bert_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
def tok(dataset):
input_ids = []
attention_masks = []
sentences = dataset.Answer2EN.values
labels = dataset.Class.values
for sent in sentences:
encoded_sent = bert_tokenizer.encode(sent,
add_special_tokens=True,
max_length = 64,
pad_to_max_length =True)
TypeError: _tokenize() got an unexpected keyword argument
'pad_to_max_length'
Does anyone know a secure installation of transformers using Anaconda?
Thank you
| The problem is that conda only offers the transformers library in version 2.1.1 (repository information) and this version didn't have a pad_to_max_length argument. I'm don't want to look it up if there was a different parameter, but you can simply pad the result (which is just a list of integers):
from transformers import BertTokenizer
bert_tokenizer = BertTokenizer.from_pretrained('bert-base-uncased', do_lower_case=True)
sentences = ['this is just a test', 'this is another test']
max_length = 64
for sent in sentences:
encoded_sent = bert_tokenizer.encode(sent,
add_special_tokens=True,
max_length = max_length)
encoded_sent.extend([0]* (max_length - len(encoded_sent)))
###your other stuff
The better option in my opinion is to create a new conda environment and install everything via pip and not via conda. This will allow you to work with the most recent transformers version (2.11).
| https://stackoverflow.com/questions/62538079/ |
Display Pytorch tensor as image using Matplotlib | I am trying to display an image stored as a pytorch tensor.
trainset = datasets.ImageFolder('data/Cat_Dog_data/train/', transform=transforms)
trainload = torch.utils.data.DataLoader(trainset, batch_size=32, shuffle=True)
images, labels = iter(trainload).next()
image = images[0]
image.shape
>>> torch.Size([3, 224, 224]) # pyplot doesn't like this, so reshape
image = image.reshape(224,224,3)
plt.imshow(image.numpy())
This method is displaying a 3 by 3 grid of the same image, always in greyscale. For example:
How do I fix this so that the single color image is displayed correctly?
| That's very odd. Try putting the channels last by permuting rather than reshaping:
image.permute(1, 2, 0)
| https://stackoverflow.com/questions/62541192/ |
How to use pytorch's cat function for K-Fold Validation (i.e. concatenate a list of pytorch chunks together) | I'm working on splitting up a data set for k-fold cross validation but having trouble with concatenating a list of tensors using Pytorch's stack/cat functions.
First, I split the training and test set into chunks using the .chunk method as follows
x_train_folds = torch.chunk(x_train, num_folds)
y_train_folds = torch.chunk(y_train, num_folds)
Where x_train is a tensor of torch.Size([5000, 3, 32, 32]) and y_train is a tensor of torch.Size([5000])
x_train_folds and y_train_folds are now tuples of num_folds tensors
Then, I need to setup a series of nested loops to iterate through the different values for K, and the various folds, while always excluding one fold from the training set to be used at test/validation time:
for k in k_choices:
k_to_accuracies[k] = [] # create empty space to append for a given k-value
for fold in range(num_folds):
# create training sets by excluding the current loop index fold and using that as the test set
x_train_cross_val = torch.cat((x_train_folds[:fold], x_train_folds[fold+1:]), 0)
y_train_cross_val = torch.cat((y_train_folds[:fold], y_train_folds[fold+1:]), 0)
classifier = KnnClassifier(x_train_cross_val, y_train_cross_val)
k_to_accuracies[k].append(classifier.check_accuracy(x_train_folds[fold], y_train_folds[fold], k=k))
As you can see, I'm always skipping one fold from the original training set to be used for validation. This is standard K-fold cross validation.
Unfortunately, I am getting the following error which I cannot seem to figure out:
TypeError: expected Tensor as element 0 in argument 0, but got tuple
As you can see in the API listing, .cat seems to need a tuple of tensors which is what I have.
https://pytorch.org/docs/stable/torch.html#torch.cat
Does anyone have any suggestions?
Much appreciated
-Drew
| try:
x_train_cross_val = torch.cat((*x_train_folds[:fold], *x_train_folds[fold+1:]), 0)
y_train_cross_val = torch.cat((*y_train_folds[:fold], *y_train_folds[fold+1:]), 0)
torch.cat receives a tuple whose elements are torch.Tensor type. However, the elements in your tuple x_train_folds[:fold] are still tuple. So, you need to remove the tuple 'decorator' of your tensors.
| https://stackoverflow.com/questions/62545533/ |
What does next() and iter() do in PyTorch's DataLoader() | I have the following code:
import torch
import numpy as np
import pandas as pd
from torch.utils.data import TensorDataset, DataLoader
# Load dataset
df = pd.read_csv(r'../iris.csv')
# Extract features and target
data = df.drop('target',axis=1).values
labels = df['target'].values
# Create tensor dataset
iris = TensorDataset(torch.FloatTensor(data),torch.LongTensor(labels))
# Create random batches
iris_loader = DataLoader(iris, batch_size=105, shuffle=True)
next(iter(iris_loader))
What does next() and iter() do in the above code? I have went through PyTorch's documentation and still can quite understand what is next() and iter() doing here. Can anyone help in explaining this? Many thanks in advance.
| These are built-in functions of python, they are used for working with iterables.
Basically iter() calls the __iter__() method on the iris_loader which returns an iterator. next() then calls the __next__() method on that iterator to get the first iteration. Running next() again will get the second item of the iterator, etc.
This logic often happens 'behind the scenes', for example when running a for loop. It calls the __iter__() method on the iterable, and then calls __next__() on the returned iterator until it reaches the end of the iterator. It then raises a stopIteration and the loop stops.
Please see the documentation for further details and some nuances: https://docs.python.org/3/library/functions.html#iter
| https://stackoverflow.com/questions/62549990/ |
How the gradient is calculated in pytorch | I have an example code. When I calculate dloss/dw manually I get the result 8, but the following code gives me a 16. Please tell me how the gradient is 16.
import torch
x = torch.tensor(2.0)
y = torch.tensor(2.0)
w = torch.tensor(3.0, requires_grad=True)
# forward
y_hat = w * x
s = y_hat - y
loss = s**2
#backward
loss.backward()
print(w.grad)
| I think you simply miscalculated.
The derivation of loss = (w * x - y) ^ 2 is:
dloss/dw = 2 * (w * x - y) * x = 2 * (3 * 2 - 2) * 2 = 16
Keep in mind that back-propagation in neural networks is done by applying the chain rule: I think you forgot the *x at the end of the derivation
To be specific:
chain rule for derivation says that df(g(x))/dx = f'(g(x)) * g'(x) (derivated with respect to x)
the whole loss function in your case is built like this:
loss(y_hat) = (y_hat - y)^2
y_hat(x) = w * x
thus: loss(y_hat(x)) = (y_hat(x) - y)^2
the derivation of this is according to chain rule:
dloss(y_hat(x))/dw = loss'(y_hat(x)) * dy_hat(x)/dw
for any z:
loss'(z) = 2 * (z - y) * 1 and dy_hat(z)/dw = z
thus: dloss((y_hat(x))/dw = dloss(y_hat(x))/dw = loss'(y_hat(x)) * y_hat'(x) = 2 * (y_hat(x) - z) * dy_hat(x)/dw = 2 * (y_hat(x) - z) * x = 2 * (w * x - z) * x = 16
pytorch knows that in your forward pass each layer applies some kind of function to its input and that your forward pass is 1 * loss(y_hat(x)) and than keeps applying the chain rule for the backward pass (each layer requires one application of the chain rule).
| https://stackoverflow.com/questions/62559008/ |
pytorch: how to multiply 3d tensor with 2d tensor | I got a 3D tensor three and a 2D tensor two, which need to be multiplied. For example, the dimensions are:
three.shape = 4x100x700
two.shape = 4x100
Output shape should be:
output.shape = 4x100x700
So basically, in output[a,b] there should be 700 scalars which were computed by multiplying all 700 scalars from three[a,b] with the single scalar from two[a,b].
| You can simply add an extra dimension to two:
output = three * two.unsqueeze(-1)
There are alternative syntax, e.g.:
output = three * two[..., None]
| https://stackoverflow.com/questions/62559382/ |
Why am I getting a divide by zero error here? | So I'm following along this tutorial in the docs on custom datasets. I'm using the MNIST dataset instead of the fancy one in the tutorial. This is the extension of the Dataset class I wrote:
class KaggleMNIST(Dataset):
def __init__(self, csv_file, transform=None):
self.pixel_frame = pd.read_csv(csv_file)
self.transform = transform
def __len__(self):
return len(self.pixel_frame)
def __getitem__(self, index):
if torch.is_tensor(index):
index = index.tolist()
image = self.pixel_frame.iloc[index, 1:]
image = np.array([image])
if self.transform:
image = self.transform(image)
return image
It works, until I try to use a transform on it:
tsf = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5,), (0.5,))
])
trainset = KaggleMNIST('train/train.csv', transform=tsf)
image0 = trainset[0]
I've looked at the stack trace, and it seems like the normalization is happening in this line of code:
c:\program files\python38\lib\site-packages\torchvision\transforms\functional.py in normalize(tensor, mean, std, inplace)
--> 218 tensor.sub_(mean[:, None, None]).div_(std[:, None, None])
So I don't get why there is divide by zero since std should be 0.5, nowhere remotely close to a small value.
Thanks for your help!
EDIT:
This does not answer my question, but I discovered that if I change these lines of code:
image = self.pixel_frame.iloc[index, 1:]
image = np.array([image])
to
image = self.pixel_frame.iloc[index, 1:].to_numpy(dtype='float64').reshape(1, -1)
Essentially, making sure the datatype was float64 fixed the problem. I'm still not sure why the problem existed in the first place, so I'd still be happy for a well-explained answer!
| The dtype of the data read is int64
img = np.array([pixel_frame.iloc[0, 1:]])
img.dtype
# output
dtype('int64')
This forces the mean and std to be converted to int64 and as std is 0.5, it becomes 0, and raises the following error:
>>> tsf(img)
ValueError: std evaluated to zero after conversion to torch.int64, leading to division by zero.
It's because the mean and std are converted to dtype of the dataset during normalization.
def normalize(tensor, mean, std, inplace=False):
...
dtype = tensor.dtype
mean = torch.as_tensor(mean, dtype=dtype, device=tensor.device)
std = torch.as_tensor(std, dtype=dtype, device=tensor.device)
if (std == 0).any():
raise ValueError('std evaluated to zero after conversion to {}, leading to division by zero.'.format(dtype))
That's why converting the dtype to float fixes the error.
| https://stackoverflow.com/questions/62559389/ |
PyTorch code stops with message "Killed". What killed it? | I train a network on GPU with Pytorch. However, after at most 3 epochs, code stops with a message :
Killed
No other error message is given.
I monitored the memory and gpu usage, there were still space during the run. I reviewed the /var/sys/dmesg to find a detailed message regarding to this, however no message with "kill" was entered. What might be the problem?
Cuda version: 9.0
Pytorch version: 1.1.0
| In order to give an idea to people who will enconter this:
Apparently, Slurm was installed on the machine so that I needed to give the tasks on Slurm.
| https://stackoverflow.com/questions/62560145/ |
Does cv2.rectangle() have an argument named “rec”? | I was trying to draw some rectangles within an image but the system gave me this error:
Here is my code:
cv2.rectangle(img=sample,
pt1=(box[0], box[1]),
pt2=(box[2], box[3]),
color=(220, 0, 0), thickness=2)
Any advice will be appreciated!
PS: I tried this piece of codes on kaggle notebok and it ran successfully but it crashed when I want to apply streamlit to deploy a web app (using my local machine). Not sure if it makes a difference, just FYI.
| I figured out this issue, it is about the version. When I downgraded to 4.1.0.25, problem is solved.
| https://stackoverflow.com/questions/62566576/ |
Invalid syntax error when setting root = to in PyTorch | import torchvision
from torchvision import transforms
train_data_path="./train/"
transforms = transforms.Compose([
transforms.Resize(64),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225] )
])
train_data = torchvision.datasets.ImageFolder
(root=train_data_path,transform=transforms)
This is the error message:
File "<ipython-input-4-e470172b3902>", line 8
(root=train_data_path,transform=transforms)
^
SyntaxError: invalid syntax
How would I be able to fix this?
| You need the opening parentheses to be directly connected to the function, without any whitespace separating them. Try replacing the final two lines with:
train_data = torchvision.datasets.ImageFolder(
root=train_data_path, transform=transforms
)
| https://stackoverflow.com/questions/62567073/ |
importing error default_collate is not defined | I tried to import default_collate from torch.utils.data.dataloader but it gives me default_collate is not exsit and another function is exist (_collate_fn_t)
from torch.utils.data.dataloader import default_collate
from torch.utils.data.dataloader import _collate_fn_t
Are these commands are similar
| The _collate_fn_t is the type definition of a collate function in general, it is defined here as:
_collate_fn_t = Callable[[List[T]], Any]
default_collate is the default collate function used by the DataLoader class.
Importing these is not equivalent, you should check your spelling and try again with:
from torch.utils.data.dataloader import default_collate
| https://stackoverflow.com/questions/62584755/ |
How many weight convolution layer has? | I have a simple convolution network:
import torch.nn as nn
class model(nn.Module):
def __init__(self, ks=1):
super(model, self).__init__()
self.conv1 = nn.Conv2d(in_channels=4, out_channels=32, kernel_size=ks, stride=1)
self.fc1 = nn.Linear(8*8*32*ks, 64)
self.fc2 = nn.Linear(64, 64)
def forward(self, x):
x = F.relu(self.conv1(x))
x = x.view(x.size(0), -1)
x = F.relu(self.fc1(x))
x = self.fc2(x)
return x
cnn = model(1)
Since the kernel size is 1 and the output channel is 32, I assume that there should be 32*1*1 weights in this layer. But, when I ask pytorch about the shape of the weight matrix cnn.conv1.weight.shape, it returns torch.Size([32, 4, 1, 1]). Why the number of input channel should matter on the weight of a conv2d layer?
Am I missing something?
| It matters because you are doing 2D convolution over the images which means the depth of the filter(kernel) must be equal to the number of in_channels(pytorch sets it for you) so the true kernel size is [in_channels,1,1]. On the other hands we can say that out_channels number is the number of kernels so the number of weights = number of kernels * size of kernel = out_channels * (in_channels * kernel_size). Here is 2D conv with 3D input
| https://stackoverflow.com/questions/62586931/ |
Pytorch differences between two tensors | I have two tensors like this:
1st tensor
[[0,0],[0,1],[0,2],[1,3],[1,4],[2,1],[2,4]]
2nd tensor
[[0,1],[0,2],[1,4],[2,4]]
I want the result tensor to be like this:
[[0,0],[1,3],[2,1]] # differences between 1st tensor and 2nd tensor
I have tried to use set, list, torch.where,.. and couldn't find any good way to achieve this. Is there any way to get the different rows between two different sizes of tensors? (need to be efficient)
| You can perform a pairwairse comparation to see which elements of the first tensor are present in the second vector.
a = torch.as_tensor([[0,0],[0,1],[0,2],[1,3],[1,4],[2,1],[2,4]])
b = torch.as_tensor([[0,1],[0,2],[1,4],[2,4]])
# Expand a to (7, 1, 2) to broadcast to all b
a_exp = a.unsqueeze(1)
# c: (7, 4, 2)
c = a_exp == b
# Since we want to know that all components of the vector are equal, we reduce over the last fim
# c: (7, 4)
c = c.all(-1)
print(c)
# Out: Each row i compares the ith element of a against all elements in b
# Therefore, if all row is false means that the a element is not present in b
tensor([[False, False, False, False],
[ True, False, False, False],
[False, True, False, False],
[False, False, False, False],
[False, False, True, False],
[False, False, False, False],
[False, False, False, True]])
non_repeat_mask = ~c.any(-1)
# Apply the mask to a
print(a[non_repeat_mask])
tensor([[0, 0],
[1, 3],
[2, 1]])
If you feel cool you can do it one liner :)
a[~a.unsqueeze(1).eq(b).all(-1).any(-1)]
| https://stackoverflow.com/questions/62588779/ |
Why use multiple ReLU objects in Neural Net class definition? | Recently I observed that a lot of times while defining the neural nets we define separate ReLU objects for each layer. Why can't we use the same ReLU object wherever it is needed.
For example instead of writing like this-
def __init__(self):
self.fc1 = nn.Linear(784, 500)
self.ReLU_1 = nn.ReLU()
self.fc2 = nn.Linear(500, 300)
self.ReLU_2 = nn.ReLU()
def forward(x):
x = self.fc1(x)
x = self.ReLU_1(x)
x = self.fc2(x)
x = self.ReLU_2(x)
why can't we use
def __init__(self):
self.fc1 = nn.Linear(784, 500)
self.ReLU = nn.ReLU()
self.fc2 = nn.Linear(500, 300)
def forward(x):
x = self.fc1(x)
x = self.ReLU(x)
x = self.fc2(x)
x = self.ReLU(x)
Is this something specific to PyTorch?
| We can do so. First variant is just for clarity.
| https://stackoverflow.com/questions/62593134/ |
What does 'requires grad' do in PyTorch and should I use it? | I have a network where I need to add my own parameter that I want to be trainable. I am using nn.Parameter() to add this but there's a 'Requires Grad' argument and I can't really make sense as to whether I want this to be true or false from reading the documentation. It makes sense that I would set this to be true, because I want this parameter to be optimised as part of the learning process -- but the need for this argument confuses me: if False means it is not optimised as part of the training process, then why would you use nn.Parameter() rather than just using a normal Tensor?
From the documentation I see that it adds the parameter to the list of utterable parameters that you obtain from the model, but I don't see why you would want this if you're not optimising it.
| As far as I know, sometimes you might need to freeze/unfreeze some part of your neural network and avoid/let some of the parameters to be optimized during the training. "requires_grad" argument provides an easy way to include or exclude your network's parameters in the backpropagation phase. You just set it to True or False and it's done.
| https://stackoverflow.com/questions/62598640/ |
Slicing pytorch tensors and use of data_ptr() | a = tensor([[ 1, 2, 3, 4, 5],
[ 6, 7, 8, 8, 10],
[11, 12, 13, 14, 15]])
I have a torch tensor and I need to index a tensor c such that c = [[3], [8], [13]]
So I did c = a[:,[2]] which gave me the expected answer, but it still failed on the autograder.
The autograder uses a check function as follows -
def check(orig, actual, expected):
expected = torch.tensor(expected)
same_elements = (actual == expected).all().item() == 1
same_storage = (orig.storage().data_ptr() == actual.storage().data_ptr())
return same_elements and same_storage
print('c correct:', check(a, c, [[3], [8], [13]]))
I tried debugging it and it turns out that same_storage is false, I don't understand why orig.storage().data_ptr() == actual.storage().data_ptr() should be True, and how it makes a difference.
Update
I was able to get the correct answer by doing c = a[:, 2:3] instead of c = a[:, [2]] what is the difference?
| PyTorch allows tensor to be a "view" of an existing tensor, such that it shares the same underlying data with its base tensor, thus avoiding explicit data copy to be able to perform fast and memory efficient operations.
As mentioned in the Tensor View docs,
When accessing the contents of a tensor via indexing, PyTorch follows Numpy behaviors that basic indexing returns views, while advanced indexing returns a copy.
In your example, c = a[:, 2:3] is basic indexing, while, c = a[:, [2]] is advanced indexing. That's why a view is created in the first case only. Thus, .storage().data_ptr() gives same result.
You can read about basic and advanced indexing in Numpy indexing docs.
Advanced indexing is triggered when the selection object, obj, is a non-tuple sequence object, an ndarray (of data type integer or bool), or a tuple with at least one sequence object or ndarray (of data type integer or bool).
| https://stackoverflow.com/questions/62607863/ |
How to convert a string of pixels into an image with python? | I am having a string of pixels of a B/W image in this manner:-
48 34 21 18 16 21 26 36 40...44 53 57 64 82 95 9
of string length 547, and I want these pixels to be converted into an image of 48*48 pixel B/W image.
Is there any python library or PyTorch function to make it possible?
Link to the Notebook
| You can use PIL.Image.frombuffer() function for example.
from PIL import Image
pixels = '126 126 129 120 110 168 174 172 173 174 170 157 134 97 78 75 118 119 97 117 142 86 58 71 124 161 162 134 100 119 124 118 153 135 143 180 180 172 153 128 98 67 60 75 85 89 85 98 123 126 131 119 119 172 180 171 155 127 100 82 77 72 54 97 184 151 157 176 125 74 71 114 173 171 136 109 116 118 118 150 152 150 178 191 188 187 180 169 152 127 86 60 74 91 92 95 119 131 127 115 113 153 130 94 71 62 65 69 83 95 79 137 181 174 196 148 88 75 103 149 135 107 100 105 104 112 140 162 178 191 187 181 171 166 159 156 159 155 144 97 54 69 83 91 112 116 100 85 74 73 59 58 67 75 74 80 104 110 96 153 180 182 151 100 103 139 167 172 152 141 135 135 141 163 182 191 191 183 179 169 144 127 132 147 156 154 152 143 92 52 56 78 97 86 69 60 51 48 55 65 74 74 71 92 121 122 115 155 177 166 151 158 181 200 201 208 207 198 187 181 182 189 187 187 179 170 154 119 91 86 101 124 139 154 153 153 132 73 51 60 63 52 48 45 46 54 65 78 79 86 96 131 163 146 133 162 179 193 202 211 205 208 216 218 209 204 191 183 184 183 176 170 153 127 96 98 127 148 148 142 134 140 150 154 149 102 49 53 57 58 65 68 70 75 75 74 90 121 151 176 176 148 156 170 193 209 215 211 203 213 219 212 206 201 183 174 173 166 162 135 101 86 99 147 176 175 166 164 157 146 148 155 154 128 55 53 54 54 77 92 89 68 58 61 69 94 143 171 155 150 161 163 185 197 203 202 207 213 212 209 202 195 176 163 157 153 125 83 86 118 160 179 172 165 161 161 166 164 155 155 153 138 74 54 40 70 110 122 106 92 112 123 116 108 96 94 118 146 155 159 166 174 180 187 198 213 216 205 196 192 178 155 139 117 88 96 131 163 159 142 130 126 123 123 132 139 147 156 158 145 75 59 60 117 163 157 138 157 176 179 186 189 167 121 98 105 123 149 161 162 165 178 196 213 214 199 188 181 171 147 117 97 104 124 134 127 123 131 135 139 138 137 144 146 139 147 135 106 75 69 98 155 184 180 178 189 187 182 181 190 203 198 165 126 102 109 138 162 171 193 216 225 222 204 191 182 154 130 116 118 137 143 125 108 100 96 96 102 122 129 145 158 142 96 90 127 88 50 125 175 195 191 191 189 178 166 165 172 175 178 177 162 139 116 112 130 158 194 211 216 218 202 189 165 132 129 134 143 129 104 86 98 80 90 128 97 70 90 117 149 161 109 127 151 112 58 145 187 200 198 192 185 174 171 180 162 135 117 120 126 128 128 124 116 124 157 171 166 156 126 107 92 101 127 129 104 93 105 119 137 113 136 145 136 118 107 119 149 162 147 152 152 125 77 142 183 189 176 177 178 174 163 118 109 118 109 95 83 94 101 114 134 125 120 152 153 154 152 156 124 99 103 122 111 112 136 151 156 163 160 160 163 155 143 145 159 163 137 141 147 126 86 119 158 161 184 183 185 163 100 98 167 135 126 89 99 116 104 101 146 144 115 162 197 201 191 189 156 112 94 103 108 112 127 141 150 153 155 156 148 141 149 156 157 165 155 144 146 129 86 112 140 156 191 190 179 144 126 159 179 160 150 148 143 135 127 135 138 137 117 151 199 195 178 177 169 123 105 100 106 115 132 138 143 145 145 143 139 149 156 156 151 141 141 143 143 130 94 131 136 142 181 198 188 177 189 193 185 183 166 152 136 123 121 130 125 132 143 186 207 192 177 177 169 140 119 128 141 142 147 154 159 158 155 158 156 153 146 132 114 122 136 136 134 127 105 136 143 151 167 184 190 198 189 175 168 160 148 138 131 131 144 160 181 176 168 212 206 202 198 185 173 160 150 133 139 148 155 158 164 165 158 146 133 119 113 118 127 130 127 126 125 124 113 176 181 163 183 177 177 184 186 183 172 164 160 160 164 165 174 189 184 171 206 218 212 206 198 187 180 177 171 157 125 113 116 121 127 126 126 126 129 133 136 134 128 121 118 117 115 113 111 175 199 166 177 196 190 188 189 190 190 188 186 184 182 183 189 179 150 171 208 219 209 201 191 181 173 167 152 150 159 157 148 149 154 155 157 153 146 142 140 130 124 117 112 113 108 100 104 175 199 190 163 181 191 187 187 191 191 189 185 179 170 161 155 150 168 168 185 221 204 193 181 168 165 157 137 120 126 158 167 164 168 168 166 160 152 147 144 138 127 118 113 106 103 95 95 173 196 200 206 189 175 168 169 171 167 166 159 154 155 162 176 190 172 147 191 213 202 193 179 162 158 154 137 124 108 123 155 163 167 169 167 164 157 151 144 135 128 120 113 106 99 92 89 164 192 203 215 214 208 206 193 183 175 173 176 179 185 194 196 182 142 148 202 213 204 202 187 173 165 154 151 135 112 102 131 154 157 162 161 158 149 142 137 129 123 117 108 101 95 88 85 156 189 205 211 206 206 206 202 197 198 194 197 201 201 195 178 156 129 171 211 216 214 208 190 179 171 168 149 132 117 102 112 134 152 154 150 150 143 137 131 123 119 112 103 96 91 83 84 148 189 202 204 201 198 199 201 202 201 197 194 192 191 177 159 133 136 189 206 208 210 199 186 180 176 161 129 129 117 106 114 126 144 149 149 145 141 135 130 122 116 108 98 93 90 81 83 149 190 200 199 194 196 199 194 193 192 185 182 180 172 161 141 129 159 188 186 193 194 185 176 173 164 123 93 105 104 117 127 125 132 145 149 142 137 134 129 119 111 103 96 92 87 79 83 159 190 197 198 190 188 188 186 182 180 174 169 165 160 145 126 134 180 187 154 158 186 175 154 151 137 99 84 87 101 124 130 131 131 140 146 143 136 133 126 117 109 99 92 88 85 76 80 171 189 192 187 184 182 182 179 173 169 168 160 156 148 135 124 158 191 196 172 158 169 146 126 123 117 103 102 104 114 128 132 135 133 133 143 144 138 130 122 112 104 96 90 87 84 76 73 175 190 184 180 178 173 171 169 167 162 159 156 152 139 123 131 177 189 192 188 177 167 147 122 111 101 100 110 116 117 131 133 133 135 134 140 144 138 129 117 108 103 97 95 92 85 76 69 179 191 186 178 171 168 164 162 156 151 153 150 144 131 118 151 181 191 198 193 183 175 163 136 112 109 115 118 121 126 136 132 130 132 129 137 144 140 127 116 108 105 101 99 92 86 76 67 160 190 184 173 169 161 156 152 148 144 146 147 141 120 126 172 184 195 203 200 191 184 174 159 142 139 133 129 133 138 135 131 124 124 127 130 141 145 132 119 112 109 106 104 96 88 73 64 110 184 188 176 168 158 145 143 144 147 146 146 136 115 145 176 184 198 199 196 197 190 178 163 159 157 149 145 144 141 134 129 121 119 126 128 138 151 141 124 117 113 110 106 98 88 69 60 89 172 189 178 170 163 149 138 144 152 155 154 128 128 166 178 184 193 197 200 198 192 182 170 163 168 162 156 147 140 136 132 121 115 118 124 130 155 152 132 126 118 110 106 98 86 66 56 60 157 186 180 173 167 153 142 155 167 166 156 125 151 174 178 178 185 193 189 191 188 175 168 167 162 144 130 126 122 122 124 118 112 117 121 124 155 163 137 129 118 110 107 104 86 63 57 41 140 184 178 178 170 159 154 172 183 181 158 134 161 170 176 176 184 184 169 156 138 129 134 136 114 101 99 100 99 99 98 103 108 119 128 131 160 171 140 126 113 106 112 108 82 64 60 39 116 184 173 179 171 165 161 182 199 198 170 149 170 170 174 185 173 148 132 123 122 126 120 106 109 124 129 124 97 64 61 58 78 112 130 136 165 177 143 121 106 104 124 107 75 63 60 40 86 181 175 176 175 169 162 175 203 203 179 164 179 175 172 143 109 97 84 106 158 175 184 171 164 168 134 76 43 33 65 86 90 105 122 142 174 175 134 116 98 119 135 99 70 60 59 48 69 169 183 173 174 170 164 169 197 209 190 164 179 170 142 130 126 79 44 55 82 127 142 124 112 105 72 54 71 89 111 102 88 96 120 149 180 163 127 110 100 136 126 84 60 57 60 50 59 146 190 174 173 174 168 167 189 204 199 175 164 150 145 168 171 143 111 125 135 144 135 133 139 136 129 128 128 126 112 85 78 102 128 155 174 141 127 100 119 144 114 73 58 60 62 50 50 118 189 181 173 175 171 167 180 196 194 181 166 162 161 163 151 155 164 168 166 164 155 155 155 148 141 135 124 105 85 78 90 122 138 156 149 140 124 98 140 138 94 64 60 63 64 47 48 80 170 191 177 174 180 172 169 187 189 177 170 172 172 169 159 148 142 141 140 139 137 139 133 125 116 106 96 86 81 88 113 122 127 135 142 155 102 119 154 118 76 62 68 65 65 39 46 52 130 185 185 174 182 178 170 174 186 178 171 176 187 178 164 151 135 121 115 118 121 116 110 104 99 93 92 92 93 111 127 125 137 138 161 126 94 144 139 96 70 69 71 61 74 35 40 44 84 166 188 183 176 180 178 174 179 185 180 193 193 180 171 160 150 151 154 152 151 146 141 135 119 108 101 96 102 128 137 145 144 133 126 91 118 147 117 82 74 78 72 61 101 38 36 44 53 127 181 187 178 174 181 180 173 183 190 190 196 195 178 164 161 167 172 168 165 171 163 154 141 128 115 104 117 149 155 139 124 111 96 99 139 135 102 88 86 82 72 64 140 43 37 41 43 75 161 181 183 173 174 179 180 175 190 199 197 198 189 181 173 166 171 173 180 176 158 148 141 126 115 113 129 147 136 132 115 97 91 125 148 124 105 94 87 77 66 82 181 44 41 35 41 45 114 177 177 181 177 175 183 184 176 192 198 184 186 195 198 188 173 174 172 167 157 145 138 121 121 115 113 125 146 133 98 83 111 148 145 122 107 90 85 75 58 118 203 48 44 35 36 42 58 144 181 189 188 182 182 187 181 172 180 189 192 193 198 192 186 178 165 160 152 138 128 128 129 110 111 139 132 105 83 97 143 153 137 118 97 87 79 68 68 168 211 45 45 41 32 38 40 90 163 179 190 184 186 185 189 182 176 185 194 199 187 175 173 162 156 156 145 128 125 127 121 104 111 121 110 89 87 131 153 148 130 106 85 77 71 60 107 199 208'
b = bytes(int(p) for p in pixels.split())
i = Image.frombuffer('L', (48, 48), b)
print(i)
i.save('example.png')
Outputs example.png:
| https://stackoverflow.com/questions/62619586/ |
Can't import sklearn ([WinError 126] The specified module could not be found) | from sklearn import datasets
I can't import sklearn
here is the error:
OSError Traceback (most recent call last)
<ipython-input-13-f9e6334b9a20> in <module>
1 import torch
2 import numpy as np
----> 3 from sklearn import datasets
4
5 X_numpy, y_numpy = datasets.make_regression(n_samples=100, n_features=1, noise=20,
random_state=1)
c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-
packages\sklearn\__init__.py in <module>
78 from . import _distributor_init # noqa: F401
79 from . import __check_build # noqa: F401
---> 80 from .base import clone
81 from .utils._show_versions import show_versions
82
c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-packages\sklearn\base.py in <module>
19 from . import __version__
20 from ._config import get_config
---> 21 from .utils import _IS_32BIT
22 from .utils.validation import check_X_y
23 from .utils.validation import check_array
c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-packages\sklearn\utils\__init__.py in <module>
18 import warnings
19 import numpy as np
---> 20 from scipy.sparse import issparse
21
22 from .murmurhash import murmurhash3_32
c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-packages\scipy\__init__.py in <module>
102
103 # Allow distributors to run custom init code
--> 104 from . import _distributor_init
105
106 __all__ += _num.__all__
c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-packages\scipy\_distributor_init.py in <module>
59 os.chdir(libs_path)
60 for filename in glob.glob(os.path.join(libs_path, '*dll')):
---> 61 WinDLL(os.path.abspath(filename))
62 finally:
63 os.chdir(owd)
c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\ctypes\__init__.py in __init__(self, name, mode, handle, use_errno, use_last_error)
362
363 if handle is None:
--> 364 self._handle = _dlopen(self._name, mode)
365 else:
366 self._handle = handle
OSError: [WinError 126] The specified module could not be found
when I type pip install sklearn I get Requirement already satisfied:
Requirement already satisfied: sklearn in c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-packages (0.0) Requirement already satisfied: scikit-learn in c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-packages (from sklearn) (0.23.1) Requirement already satisfied: joblib>=0.11 in c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-packages (from scikit-learn->sklearn) (0.15.1) Requirement already satisfied: threadpoolctl>=2.0.0 in c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-packages (from scikit-learn->sklearn) (2.1.0) Requirement already satisfied: numpy>=1.13.3 in c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-packages (from scikit-learn->sklearn) (1.18.5) Requirement already satisfied: scipy>=0.19.1 in c:\users\kadiem alqazzaz\appdata\local\programs\python\python37\lib\site-packages (from scikit-learn->sklearn) (1.5.0)
so why can't I use sklearn, any help is appreciated thanks.
EDIT: when I import sklearn in cmd it works with no issues, however, when I run using Jupyter Notebook I get the error above.
| Just make sure OpenSlide DLL in your library search path
Otherwise:
download the OpenSlide Windows binaries, then you need to add the 'bin' folder to your environmental path
| https://stackoverflow.com/questions/62624804/ |
Where do the input flatten value come from in fully connected 1 (fc1) layer (MNIST Example) | here's some of the convolutional neural network sample code from Pytorch's examples directory on their github:
https://github.com/pytorch/examples/blob/master/mnist/main.py
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, 3, 1)
self.conv2 = nn.Conv2d(32, 64, 3, 1)
self.dropout1 = nn.Dropout2d(0.25)
self.dropout2 = nn.Dropout2d(0.5)
self.fc1 = nn.Linear(9216, 128)
self.fc2 = nn.Linear(128, 10)
If I understand this, we need to flatten the output from the last convolutional layer before we can pass it through a linear layer (fc1). So, looking at this code, we see the input to the first fully connected layer is: 9216.
Where has this number (9216) come from?
| You also need to look at the forward method and the network input shape in order to compute the input shape of the linear/fully-connected layer. In the case of MNIST we have a single channel 28x28 input image. Using the following formulas from the docs you can compute the output shape of each convolution operation. The max-pooling operation follows the same input-output relationship as convolution layers.
Since the shape of the input before flattening is a 64 channel 12x12 feature map, then the total size of the feature is 64*12*12 = 9216.
Input/Output relation for conv2d and max_pool2d operations
def forward(self, x):
""" For each line which changes the feature shape additional comment
indicates <input_shape> -> <output_shape> """
x = self.conv1(x) # [1, 28, 28] -> [32, 26, 26]
x = F.relu(x)
x = self.conv2(x) # [32, 26, 26] -> [64, 24, 24]
x = F.relu(x)
x = F.max_pool2d(x, 2) # [64, 24, 24] -> [64, 12, 12]
x = self.dropout1(x)
x = torch.flatten(x, 1) # [64, 12, 12] -> [9216]
x = self.fc1(x) # [9216] -> [128]
x = F.relu(x)
x = self.dropout2(x)
x = self.fc2(x) # [128] -> [10]
output = F.log_softmax(x, dim=1)
return output
| https://stackoverflow.com/questions/62628734/ |
what the difference between att_mask and key_padding_mask in MultiHeadAttnetion | What the difference between att_mask and key_padding_mask in MultiHeadAttnetion of pytorch:
key_padding_mask – if provided, specified padding elements in the key will be ignored by the attention. When given a binary mask and a value is True, the corresponding value on the attention layer will be ignored. When given a byte mask and a value is non-zero, the corresponding value on the attention layer will be ignored
attn_mask – 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all the batches while a 3D mask allows to specify a different mask for the entries of each batch.
Thanks in advance.
| The key_padding_mask is used to mask out positions that are padding, i.e., after the end of the input sequence. This is always specific to the input batch and depends on how long are the sequence in the batch compared to the longest one. It is a 2D tensor of shape batch size × input length.
On the other hand, attn_mask says what key-value pairs are valid. In a Transformer decoder, a triangle mask is used to simulate the inference time and prevent the attending to the "future" positions. This is what att_mask is usually used for. If it is a 2D tensor, the shape is input length × input length. You can also have a mask that is specific to every item in a batch. In that case, you can use a 3D tensor of shape (batch size × num heads) × input length × input length. (So, in theory, you can simulate key_padding_mask with a 3D att_mask.)
| https://stackoverflow.com/questions/62629644/ |
Argmax indexing in pytorch with 2 tensors of equal shape | Summarize the problem
I am working with high dimensional tensors in pytorch and I need to index one tensor with the argmax values from another tensor. So I need to index tensor y of dim [3,4] with the results from the argmax of tensor xwith dim [3,4]. If tensors are:
import torch as T
# Tensor to get argmax from
# expected argmax: [2, 0, 1]
x = T.tensor([[1, 2, 8, 3],
[6, 3, 3, 5],
[2, 8, 1, 7]])
# Tensor to index with argmax from preivous
# expected tensor to retrieve [2, 4, 9]
y = T.tensor([[0, 1, 2, 3],
[4, 5, 6, 7],
[8, 9, 10, 11]])
# argmax
x_max, x_argmax = T.max(x, dim=1)
I would like an operation that given the argmax indexes of x, or x_argmax, retrieves the values in tensor y in the same indexes x_argmax indexes.
Describe what you’ve tried
This is what I have tried:
# What I have tried
print(y[x_argmax])
print(y[:, x_argmax])
print(y[..., x_argmax])
print(y[x_argmax.unsqueeze(1)])
I have been reading a lot about numpy indexing, basic indexing, advanced indexing and combined indexing. I have been trying to use combined indexing (since I want a slice in first dimension of the tensor and the indexes values on the second one). But I have not been able to come up with a solution for this use case.
| You are looking for torch.gather:
idx = torch.argmax(x, dim=1, keepdim=true) # get argmax directly, w/o max
out = torch.gather(y, 1, idx)
Resulting with
tensor([[2],
[4],
[9]])
| https://stackoverflow.com/questions/62635492/ |
PyTorch: batching from multiple datasets | I have multiple datasets that I want to use in the training. I want each batch to be from one dataset but have batches from (possibly) all of the datasets in each epoch.
Merging the datasets into one simple Dataset object and using the default Dataloader leads to having samples from different datasets in one batch.
My own guess is to have a separate Dataset object for each dataset and override the Dataloader or the sampler, but I don't know how to do it.
| I think the best way to solve your problem is to have a single merged dataset with a single data loader, but have a custom BatchSampler that yields indices based on the different datasets inside the merged dataset.
| https://stackoverflow.com/questions/62637515/ |
Mask for neural network training | I am training a neural network and I found a dataset of pictures taken by drones. It says that it has 20 classes that should be detected. However the masks all looks like this (I'm sorry the image is really dark!):
This is my mask
When I try to train the network it always says that the image only has 3 channels. (I figured it was probably RGB). The problem is that my network expects a 20 channels input for the mask (one for each category to detect like tree, car, human, etc.) Is there a way for me to transform the image in a 20 channels image? I looked if the mask only had 20 different values for the pixel colors but it has 254 so I do not think there is something to do with that...
Thank you! (It is my first question on StackOverflow so if there is a problem in the question just tell me! :-) )
| I am not sure I understand your question correctly but yes, there is a way to upsample the image to make it a 20 channel input. All you have to do is take the original image (lets assume its size is [batch, height, width, #channels]) and convolve it with a kernel ([#channels, height, width, 20]) while keeping the padding mode 'same'. This would convert your 3 channel image into a 20 channel array (wouldn't call it an image anymore).
| https://stackoverflow.com/questions/62644584/ |
PyTorch arguments not valid on android | I want to use this model in my android app. But when I start the app it falls with an error. The model works fine on my PC.
To Reproduce
Steps to reproduce the behavior:
Clone repository and use instructions in readme to run the model.
Add code below to save the model
traced_script_module = torch.jit.trace(i2d, data)
traced_script_module.save("i2d.pt")
I used PyTorch Android DemoApp link to run the model on android.
Error:
E/AndroidRuntime: FATAL EXCEPTION: ModuleActivity
Process: com.hypersphere.depthvisor, PID: 4765
com.facebook.jni.CppException:
Arguments for call are not valid.
The following variants are available:
aten::upsample_bilinear2d(Tensor self, int[2] output_size, bool align_corners) -> (Tensor):
Expected at most 3 arguments but found 5 positional arguments.
aten::upsample_bilinear2d.out(Tensor self, int[2] output_size, bool align_corners, *, Tensor(a!) out) -> (Tensor(a!)):
Argument out not provided.
The original call is:
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\torch\nn\functional.py(3013): interpolate
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\torch\nn\functional.py(2797): upsample
<ipython-input-1-e1d92bec6901>(75): _upsample_add
<ipython-input-1-e1d92bec6901>(89): forward
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\torch\nn\modules\module.py(534): _slow_forward
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\torch\nn\modules\module.py(548): __call__
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\torch\jit\__init__.py(1027): trace_module
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\torch\jit\__init__.py(875): trace
<ipython-input-12-19d2ccccece4>(16): <module>
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\IPython\core\interactiveshell.py(3343): run_code
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\IPython\core\interactiveshell.py(3263): run_ast_nodes
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\IPython\core\interactiveshell.py(3072): run_cell_async
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\IPython\core\async_helpers.py(68): _pseudo_sync_runner
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\IPython\core\interactiveshell.py(2895): _run_cell
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\IPython\core\interactiveshell.py(2867): run_cell
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\ipykernel\zmqshell.py(536): run_cell
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\ipykernel\ipkernel.py(300): do_execute
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\tornado\gen.py(209): wrapper
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\ipykernel\kernelbase.py(545): execute_request
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\tornado\gen.py(209): wrapper
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\ipykernel\kernelbase.py(268): dispatch_shell
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\tornado\gen.py(209): wrapper
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\ipykernel\kernelbase.py(365): process_one
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\tornado\gen.py(748): run
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\tornado\gen.py(787): inner
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\tornado\ioloop.py(743): _run_callback
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\tornado\ioloop.py(690): <lambda>
D:\ProgramData\Anaconda\envs\ml3 torch\lib\asyncio\events.py(88): _run
D:\ProgramData\Anaconda\envs\ml3 torch\lib\asyncio\base_events.py(1786): _run_once
D:\ProgramData\Anaconda\envs\ml3 torch\lib\asyncio\base_events.py(541): run_forever
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\tornado\platform\asyncio.py(149): start
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\ipykernel\kernelapp.py(597): start
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\traitlets\config\application.py(664): launch_instance
D:\ProgramData\Anaconda\envs\ml3 torch\lib\site-packages\ipykernel_launcher.py(16): <module>
D:\ProgramData\Anaconda\envs\ml3 torch\lib\runpy.py(85): _run_code
D:\ProgramData\Anaconda\envs\ml3 torch\lib\runpy.py(193): _run_module_as_main
Serialized File "code/__torch__/___torch_mangle_907.py", line 39
_17 = ops.prim.NumToTensor(torch.size(_16, 2))
_18 = ops.prim.NumToTensor(torch.size(_16, 3))
2020-06-29 23:50:09.536 4765-4872/com.hypersphere.depthvisor E/AndroidRuntime: _19 = torch.upsample_bilinear2d(_15, [int(_17), int(_18)], False, None, None)
~~~~~~~~~~~~~~~~~~~~~~~~~ <--- HERE
input = torch.add(_19, _16, alpha=1)
_20 = (_6).forward(input, )
at org.pytorch.NativePeer.initHybrid(Native Method)
at org.pytorch.NativePeer.<init>(NativePeer.java:18)
at org.pytorch.Module.load(Module.java:23)
at com.hypersphere.depthvisor.MainActivity.analyzeImage(MainActivity.java:56)
at com.hypersphere.depthvisor.MainActivity.analyzeImage(MainActivity.java:21)
at com.hypersphere.depthvisor.AbstractCameraXActivity.lambda$setupCameraX$2$AbstractCameraXActivity(AbstractCameraXActivity.java:86)
at com.hypersphere.depthvisor.-$$Lambda$AbstractCameraXActivity$KgCZmrRflavSsq5aSHYb53Fi-P4.analyze(Unknown Source:2)
at androidx.camera.core.ImageAnalysisAbstractAnalyzer.analyzeImage(ImageAnalysisAbstractAnalyzer.java:57)
at androidx.camera.core.ImageAnalysisNonBlockingAnalyzer$1.run(ImageAnalysisNonBlockingAnalyzer.java:135)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.os.HandlerThread.run(HandlerThread.java:65)
Environment
PyTorch version: 1.5.0
Is debug build: No
CUDA used to build PyTorch: Could not collect
OS: Windows 10 Pro
GCC version: Could not collect
CMake version: Could not collect
Python version: 3.7
Is CUDA available: No
CUDA runtime version: 10.2.89
GPU models and configuration: Could not collect
Nvidia driver version: Could not collect
cuDNN version: Could not collect
Versions of relevant libraries:
[pip3] numpy==1.18.5
[pip3] torch==1.5.0
[pip3] torchvision==0.6.0
[conda] _pytorch_select 0.1 cpu_0
[conda] blas 1.0 mkl
[conda] cudatoolkit 10.2.89 h74a9793_1
[conda] libmklml 2019.0.5 0
[conda] mkl 2019.4 245
[conda] mkl-service 2.3.0 py37hb782905_0
[conda] mkl_fft 1.1.0 py37h45dec08_0
[conda] mkl_random 1.1.0 py37h675688f_0
[conda] numpy 1.18.5 py37h6530119_0
[conda] numpy-base 1.18.5 py37hc3f5095_0
[conda] pytorch 1.5.0 cpu_py37h9f948e0_0
[conda] torchvision 0.6.0 py37_cu102 pytorch
Android Studio 4.0
Device: Samsung s8 plus
Android version: 9
| My pc PyTorch version was 1.5 and in dependences were 1.4. So solution is:
implementation 'org.pytorch:pytorch_android:1.5.0'
implementation 'org.pytorch:pytorch_android_torchvision:1.5.0'
| https://stackoverflow.com/questions/62646775/ |
What's the best way to load two pretrained model partially from state-dict in Pytorch? | I am trying to load two separately trained models except for the last layer and want to train the last layer separately combining these two models. I defined e new nn.Module class and load these pretrained model inside that class and in the forward path tried to return the value before the last layer.
class New_net(nn.Module):
def __init__(self):
super(New_net, self).__init__()
self.net1 = net1()
self.net2 = net2()
self.fc= nn.Linear(512, 2)
self._initialize_weights()
def _initialize_weights(self):
checkpoint = torch.load('save_model/checkpoint_net1.t7')
self.net1.load_state_dict(checkpoint['state_dict'])
checkpoint = torch.load('save_model/checkpoint_net2.t7')
self.net2.load_state_dict(checkpoint['state_dict'])
def forward(self, x):
x1 = self.net1(x)
x2 = self.net2(x)
x=torch.cat((x1,x2),dim=1)
x=self.fc(x)
return x
but it seems it is not loading the model accurately. What's the correct way to do that
| I figured that. Instead of weight initialization, I did the following
#load net1 model partially
checkpoint = torch.load('save_model/checkpoint_net1.t7')
pretrained_dict=checkpoint['state_dict']
net1_dict=net.net1.state_dict()
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in net1_dict}
net1_dict.update(pretrained_dict)
net.net1.load_state_dict(net1_dict)
#load net2 model partially
checkpoint = torch.load('save_model/checkpoint_net2.t7')
pretrained_dict=checkpoint['state_dict']
net2_dict=net.net2.state_dict()
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in net2_dict}
net2_dict.update(pretrained_dict)
net.net2.load_state_dict(net2_dict)
| https://stackoverflow.com/questions/62649109/ |
How can I load a partially trained model in PyTorch? | Let's suppose that the model I'm loading has 4 layers (layer0, layer1, layer2, layer3) for simplicity. If I only wanted that model to be pretrained for say layer0 and layer1, but have randomly initialized parameters for layer2 and layer3, how would I be able to do that?
| You can do it by freezing the layers you want it not to change(pretrained) and leave the other unfreezed(they will continue to train)
model_ft = models.resnet50(pretrained=True)
ct = 0
for child in model_ft.children():
ct += 1
if ct < 7:
for param in child.parameters():
param.requires_grad = False
This freezes layers 1-6 in the total 10 layers of Resnet50.
| https://stackoverflow.com/questions/62659706/ |
PyTorch Multi Class Classification using CrossEntropyLoss - not converging | I am trying to get a simple network to output the probability that a number is in one of three classes. These are, smaller than 1.1, between 1.1 and 1.5 and bigger than 1.5. I am using cross entropy loss with class labels of 0, 1 and 2, but cannot solve the problem.
Every time I train, the network outputs the maximum probability for class 2, regardless of input. The lowest loss I seem to be able to achieve is 0.9ish. Any advice on where I am going wrong would be greatly appreciated!! All code is below.
class gating_net(nn.Module):
def __init__(self, input_dim, output_dim):
super(gating_net, self).__init__()
self.linear1 = nn.Linear(input_dim, 32)
self.linear2 = nn.Linear(32, output_dim)
def forward(self, x):
# The original input (action) is used as the residual.
x = F.relu(self.linear1(x))
x = F.sigmoid(self.linear2(x))
return x
learning_rate = 0.01
batch_size = 64
epochs = 500
test = 1
gating_network = gating_net(1,3)
optimizer = torch.optim.SGD(gating_network.parameters(), lr=learning_rate, momentum=0.9)
scheduler = ReduceLROnPlateau(optimizer, mode='max', factor=0.5, patience=20, verbose=True)
for epoch in range (epochs):
input_ = []
label_ = []
for i in range (batch_size):
scale = random.randint(10,20)/10
input = scale
if scale < 1.1:
label = np.array([0])
elif 1.1 < scale < 1.5:
label = np.array([1])
else:
label = np.array([2])
input_.append(np.array([input]))
label_.append(label)
optimizer.zero_grad()
# get output from the model, given the inputs
output = gating_network.forward(torch.FloatTensor(input_))
old_label = torch.FloatTensor(label_)
# get loss for the predicted output
loss = nn.CrossEntropyLoss()(output, old_label.squeeze().long())
# get gradients w.r.t to parameters
loss.backward()
# update parameters
optimizer.step()
scheduler.step(loss)
print('epoch {}, loss {}'.format(epoch, loss.item()))
if loss.item() < 0.01:
print("########## Solved! ##########")
torch.save(mod_network.state_dict(), './supervised_learning/run_{}.pth'.format(test))
break
# save every 500 episodes
if epoch % 100 == 0:
torch.save(gating_network.state_dict(), './run_{}.pth'.format(test))
|
Your code generates training data every epochs (which is also every batch in this case). This is very redundant, but it doesn't mean the code won't work. However one thing that does influence the training is the imbalance of training data between classes. With your code majority of the training data is always labeled 2. So intuitively, your network will always learn more about class 2. That is why with the very small epoch of 500, the network classified all the classes as 2, because it is a fast and easy way to lower the loss. However when the network can't get the loss much lower by applying the knowledge about label 2, it will learn about 1 and 0 too. So it is possible to train the network, though not so efficient.
Continuing from the previous issue, using ReduceLROnPlateau also isn't efficient because at the time the network starts to learn about label 0 and 1, the learning rate is already to small(intuitively speaking). Doesn't mean it is untrainable, but it will probably take a lot of time.
CrossEntropyLoss calculates LogSoftmax internally, so having Sigmoid at the end of the network means you have a Softmax layer right after Sigmoid layer, which is probably not what you want. I think the network isn't necessarily 'wrong', but it will be much harder to train.
actually scale 1.1 is being labeled 2 because you have <1.1 and >1.1.
TL;DR
Get rid of sigmoid and scheduler.
I was able to get Solved! somewhere around 15000 epoch (with learning rate and batch size as same as your code).
| https://stackoverflow.com/questions/62660950/ |
How can I visualize network architectures effectively? | Is there some sort of software that can do so? Specifically, I would like to visualize Resnet18. Is there no other way other than to just draw it myself? Here is an example of what I want to see:
Sample Architecture Visualization
| You can use this one : http://alexlenail.me/NN-SVG/LeNet.html . It lets you visualize neural networks by letting you modify several parameters and finally lets you export the architectures as SVG files. You can also choose between 3 visualization styles, namely FCNN, LeNet & AlexNet.
| https://stackoverflow.com/questions/62669316/ |
Process got killed when building docker image on GCP | I am a newbie of cloud computing and struggling to deploy my web app on google cloud platform for the first time. When I was building docker image, which means I ran the following code
docker build -t gcr.io/${PROJECT_ID}/insurance-streamlit:v1 .
the process got killed, showing the following error:
Killed
The command '/bin/sh -c pip install -r requirements.txt' returned a non-zero code: 137
I guessed my app might be too large because the weight file has been more than 100MB. So is there a way to fix it? Please tell me the details, thanks in advance!
PS: my Dockerfile is as below:
FROM python:3.7
RUN pip install virtualenv
ENV VIRTUAL_ENV=/venv
RUN virtualenv venv -p python3
ENV PATH="VIRTUAL_ENV/bin:$PATH"
WORKDIR /app
ADD . /app
# Install dependencies
RUN pip install -r requirements.txt
# copying all files over
COPY . /app
# Expose port
ENV PORT 8501
# cmd to launch app when container is run
CMD streamlit run app.py
# streamlit-specific commands for config
ENV LC_ALL=C.UTF-8
ENV LANG=C.UTF-8
RUN mkdir -p /root/.streamlit
RUN bash -c 'echo -e "\
[general]\n\
email = \"\"\n\
" > /root/.streamlit/credentials.toml'
RUN bash -c 'echo -e "\
[server]\n\
enableCORS = false\n\
" > /root/.streamlit/config.toml
And my requirements.txt is like:
albumentations==0.4.5
numpy==1.19.0
opencv-python==4.1.0.25
opencv-python-headless==4.2.0.34
pandas==1.0.5
Pillow==7.1.2
streamlit==0.62.0
torch==1.4.0
torchvision==0.5.0
matplotlib
| I found that to build your Docker image you should have enough disk space and Python 3.7 installed, also there's a typo at your Docker file - no single quotes ' at the end of the last string. Beside of that, everything looks good and runs.
Please find my steps below:
Enable Google Container Registry API
Create VM instance:
gcloud compute instances create instance-4 --zone=europe-west3-a --machine-type=e2-medium --image=ubuntu-1804-bionic-v20200701 --image-project=ubuntu-os-cloud --boot-disk-size=50GB
Follow documentation Pushing and pulling images.
Install Python 3.7:
sudo apt install python3.7
Build Docker image:
docker build -t gcr.io/test-prj/testimage:v1 .
...
Step 16/16 : RUN bash -c 'echo -e "[server]\nenableCORS = false\n" > /root/.streamlit/config.toml
---> Running in 57502f97cfbe
/bin/sh: 1: Syntax error: Unterminated quoted string
The command '/bin/sh -c bash -c 'echo -e "[server]\nenableCORS = false\n" > /root/.streamlit/config.toml' returned a non-zero code: 2
Change last string of the Docker file:
" > /root/.streamlit/config.toml'
Build Docker image again:
docker build -t gcr.io/test-prj/testimage:v1 .
...
Step 16/16 : RUN bash -c 'echo -e "[server]\nenableCORS = false\n" > /root/.streamlit/config.toml'
---> Running in c1c1f81a2d09
Removing intermediate container c1c1f81a2d09
---> 24b6609de554
Successfully built 24b6609de554
Successfully tagged gcr.io/test-prj/testimage:v1
$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
gcr.io/test-prj/testimage v1 24b6609de554 14 minutes ago 3.87GB
Push Docker image to the registry:
gcloud docker -- push gcr.io/test-prj/testimage:v1
Create new VM instance and deploy image:
gcloud compute instances create-with-container instance-5 --zone=europe-west3-a --machine-type=e2-medium --image=cos-stable-81-12871-148-0 --image-project=cos-cloud --boot-disk-size=50GB --container-image=gcr.io/test-prj/testimage:v1
Check status of Docker container:
instance-5 ~ $ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e21b80dc0de7 gcr.io/test-prj/testimage:v1 "/bin/sh -c 'streaml…" 28 seconds ago Restarting (2) Less than a second ago klt-instance-5-caqx
and it doesn't look very good.
Stop container:
instance-5 ~ $docker stop e21b80dc0de7
Follow the documentation and run container interactively:
instance-5 ~ $docker run --name test -it gcr.io/test-prj/testimage:v1
Usage: streamlit run [OPTIONS] TARGET [ARGS]...
Error: Invalid value: File does not exist: app.py
no surprise because I don't have app.py.
After that, I've added some dummy app.py, rebuild and finally it works:
instance-6 ~ $ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1de2e8ded5d8 gcr.io/test-prj/testimage:v2 "/bin/sh -c 'streaml…" 7 minutes ago Up 7 minutes klt-instance-6-yezv
| https://stackoverflow.com/questions/62669720/ |
What is the role of pytorch dataset.imagefolder's loader option? | Loader option
What is the role of PyTorch dataset.imagefolder's loader option?
Actually, now I have a 10,000 images in a folder, but I want to use only 100 images. Now I load all the image and subset dataset by index.
from torch.utils.data import Subset
a = dset.ImageFolder(root=path_F,transform=transform)
index = list(range(0,100))
b = Subset(a,index)
Can loader option make my code simple?
| loader is responsible for loading the image given path. By default PyTorch uses pillow and it's Image.open(path) functionality see docs.
You can specify custom loading like this (load and rotate by 45 degrees):
import torchvision
from PIL import Image
def loader(path):
return Image.open(path).rotate(45)
dataset = torchvision.datasets.ImageFolder("images", loader=loader)
So no, you shouldn't use it for choosing images.
You could, in principle, use is_valid_file argument to do it like this though:
class Chooser:
def __init__(self):
self._counter = -1
def __call__(self, path):
self._counter += 1
return self._counter < 100
dataset = torchvision.datasets.ImageFolder("images", is_valid_file=Chooser())
I would highly discourage this approach though as the intent isn't immediately clear and it will go through whole dataset checking each image. Your current way is the way to go.
| https://stackoverflow.com/questions/62672870/ |
Multi class classification - RuntimeError: 1D target tensor expected, multi-target not supported | My goal is to build a multi-class image classifier using Pytorch and based on the EMNIST dataset (black and white pictures of letters).
The shape of my training data X_train is (124800, 28, 28).
The shape of the original target variables y_train is (124800, 1), however I created a one-hot encoding so that now the shape is (124800, 26).
The model that I am building should have 26 output variables, each representing the probability of one letter.
I read in my data as follows:
import scipy .io
emnist = scipy.io.loadmat(DATA_DIR + '/emnist-letters.mat')
data = emnist ['dataset']
X_train = data ['train'][0, 0]['images'][0, 0]
X_train = X_train.reshape((-1,28,28), order='F')
y_train = data ['train'][0, 0]['labels'][0, 0]
Then, I created a one-hot-encoding as follows:
y_train_one_hot = np.zeros([len(y_train), 27])
for i in range (0, len(y_train)):
y_train_one_hot[i, y_train[i][0]] = 1
y_train_one_hot = np.delete(y_train_one_hot, 0, 1)
I create the dataset with:
train_dataset = torch.utils.data.TensorDataset(torch.from_numpy(X_train), torch.from_numpy(y_train_one_hot))
batch_size = 128
n_iters = 3000
num_epochs = n_iters / (len(train_dataset) / batch_size)
num_epochs = int(num_epochs)
train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True)
And then I build my model as follows:
class CNNModel(nn.Module):
def __init__(self):
super(CNNModel, self).__init__()
# Convolution 1
self.cnn1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=5, stride=1, padding=0)
self.relu1 = nn.ReLU()
# Max pool 1
self.maxpool1 = nn.MaxPool2d(2,2)
# Convolution 2
self.cnn2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=5, stride=1, padding=0)
self.relu2 = nn.ReLU()
# Max pool 2
self.maxpool2 = nn.MaxPool2d(kernel_size=2)
# Fully connected 1 (readout)
self.fc1 = nn.Linear(32 * 4 * 4, 26)
def forward(self, x):
# Convolution 1
out = self.cnn1(x.float())
out = self.relu1(out)
# Max pool 1
out = self.maxpool1(out)
# Convolution 2
out = self.cnn2(out)
out = self.relu2(out)
# Max pool 2
out = self.maxpool2(out)
# Resize
# Original size: (100, 32, 7, 7)
# out.size(0): 100
# New out size: (100, 32*7*7)
out = out.view(out.size(0), -1)
# Linear function (readout)
out = self.fc1(out)
return out
model = CNNModel()
criterion = nn.CrossEntropyLoss()
learning_rate = 0.01
optimizer = torch.optim.SGD(model.parameters(), lr = learning_rate)
And then I train the model as follows:
iter = 0
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# Add a single channel dimension
# From: [batch_size, height, width]
# To: [batch_size, 1, height, width]
images = images.unsqueeze(1)
# Forward pass to get output/logits
outputs = model(images)
# Clear gradients w.r.t. parameters
optimizer.zero_grad()
# Forward pass to get output/logits
outputs = model(images)
# Calculate Loss: softmax --> cross entropy loss
loss = criterion(outputs, labels)
# Getting gradients w.r.t. parameters
loss.backward()
# Updating parameters
optimizer.step()
iter += 1
if iter % 500 == 0:
# Calculate Accuracy
correct = 0
total = 0
# Iterate through test dataset
for images, labels in test_loader:
images = images.unsqueeze(1)
# Forward pass only to get logits/output
outputs = model(images)
# Get predictions from the maximum value
_, predicted = torch.max(outputs.data, 1)
# Total number of labels
total += labels.size(0)
correct += (predicted == labels).sum()
accuracy = 100 * correct / total
# Print Loss
print('Iteration: {}. Loss: {}. Accuracy: {}'.format(iter, loss.data[0], accuracy))
However, when I run this, I get the following error:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-11-c26c43bbc32e> in <module>()
21
22 # Calculate Loss: softmax --> cross entropy loss
---> 23 loss = criterion(outputs, labels)
24
25 # Getting gradients w.r.t. parameters
3 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
548 result = self._slow_forward(*input, **kwargs)
549 else:
--> 550 result = self.forward(*input, **kwargs)
551 for hook in self._forward_hooks.values():
552 hook_result = hook(self, input, result)
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/loss.py in forward(self, input, target)
930 def forward(self, input, target):
931 return F.cross_entropy(input, target, weight=self.weight,
--> 932 ignore_index=self.ignore_index, reduction=self.reduction)
933
934
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
2315 if size_average is not None or reduce is not None:
2316 reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 2317 return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
2318
2319
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
2113 .format(input.size(0), target.size(0)))
2114 if dim == 2:
-> 2115 ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
2116 elif dim == 4:
2117 ret = torch._C._nn.nll_loss2d(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: 1D target tensor expected, multi-target not supported
I expect that I do something wrong when I initialize/use my loss function. What can I do so that I can start training my model?
| If you are using crossentropy loss you shouldn't one-hot encode your target variable y.
Pytorch crossentropy expects just the class indices as target not their one-hot encoded version.
To cite the doc https://pytorch.org/docs/master/generated/torch.nn.CrossEntropyLoss.html :
This criterion expects a class index in the range [0, C-1] as the target for each value of a 1D tensor of size minibatch;
| https://stackoverflow.com/questions/62673238/ |
PyTorch differentiable mask | How would I go about blacking out a portion of an image or feature map such that AutoGrad can backprop through the operation?
Specifically I want to black out everything except for n layers of border pixels. So if we consider a single channel of the feature map which looks like:
[
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
]
I set a constant n=1 so my operation does the following to the input:
[
[1, 1, 1, 1],
[1, 0, 0, 1],
[1, 0, 0, 1],
[1, 1, 1, 1],
]
In my case I'd be doing it to a multi channel feature map and all channels would be treated the same way.
If possible, I want to do it in a functional manner.
| Considering the comments you added, i.e. that you don't need the output to be differentiable wrt. to the mask (said differently, the mask is constant), you could just store the indices of the 1s in the mask and act only on the corresponding elements of whatever Tensor you're considering. Or if you don't want to deal with fancy indexing, you could just keep the mask as a Tensor of 0s and 1s and do an element-wise multiplication of it with whatever Tensor you're considering. Or, if you truly just need to compute a loss along just the border pixels, just extract the first and last row, and first and last column, and avoid double-counting the corners. This latter solution is essentially just the first solution recast in a special case.
To address the question in your comment to my answer:
x = torch.tensor([[1.0,2,3],[4,5,6]], requires_grad = True)
print(x[:,0])
gives
tensor([1., 4.], grad_fn=<SelectBackward>)
, so we see that slicing does not mess with the autograd engine (it's still tracking the contribution to the gradient). It is not too surprising that this works automatically; slicing can be viewed as the (mathematical) function that of projecting onto a subspace of R^n, for which it's easy to compute the gradient.
| https://stackoverflow.com/questions/62674414/ |
Change expectation to multi dimensional rather than 1D in nn.crossentropyloss | My goal is to do multi class image classification in Pytorch using the EMNIST dataset.
As a loss function, I would like to use Multi-Class Cross-Entropy Loss.
Currently, I define my loss function as follows:
criterion = nn.CrossEntropyLoss()
I train my model as follows:
iter = 0
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# Add a single channel dimension
# From: [batch_size, height, width]
# To: [batch_size, 1, height, width]
images = images.unsqueeze(1)
# Forward pass to get output/logits
outputs = model(images)
# Clear gradients w.r.t. parameters
optimizer.zero_grad()
# Forward pass to get output/logits
outputs = model(images)
# Calculate Loss: softmax --> cross entropy loss
loss = criterion(outputs, labels)
# Getting gradients w.r.t. parameters
loss.backward()
# Updating parameters
optimizer.step()
iter += 1
if iter % 500 == 0:
# Calculate Accuracy
correct = 0
total = 0
# Iterate through test dataset
for images, labels in test_loader:
images = images.unsqueeze(1)
# Forward pass only to get logits/output
outputs = model(images)
# Get predictions from the maximum value
_, predicted = torch.max(outputs.data, 1)
# Total number of labels
total += labels.size(0)
correct += (predicted == labels).sum()
accuracy = 100 * correct / total
# Print Loss
print('Iteration: {}. Loss: {}. Accuracy: {}'.format(iter, loss.data[0], accuracy))
However, the error that I get is:
RuntimeError Traceback (most recent call last)
<ipython-input-15-c26c43bbc32e> in <module>()
21
22 # Calculate Loss: softmax --> cross entropy loss
---> 23 loss = criterion(outputs, labels)
24
25 # Getting gradients w.r.t. parameters
3 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
2113 .format(input.size(0), target.size(0)))
2114 if dim == 2:
-> 2115 ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
2116 elif dim == 4:
2117 ret = torch._C._nn.nll_loss2d(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: 1D target tensor expected, multi-target not supported
My CNN outputs 26 variables and my target variables are also 26D.
How can I change my code so that nn.crossentropyloss() expects a 26D input rather than 1D?
| nn.CrossEntropy()(input, target) expects input to be an one-hot vector with size batchsize X num_classes, and target to be the id of true class with size batchsize.
So in short, you can change your target with target = torch.argmax(target, dim=1) to have it fit nn.CrossEntropy().
| https://stackoverflow.com/questions/62677285/ |
Get variable from a Numpy array | For a image classification problem with Pytorch, I read in my data as follows:
import scipy .io
emnist = scipy.io.loadmat(DATA_DIR + '/emnist-letters.mat')
data = emnist ['dataset']
X_train = data ['train'][0, 0]['images'][0, 0]
X_train = X_train.reshape((-1,28,28), order='F')
y_train = data ['train'][0, 0]['labels'][0, 0]
X_test = data ['test'][0, 0]['images'][0, 0]
X_test = X_test.reshape((-1,28,28), order = 'F')
y_test = data ['test'][0, 0]['labels'][0, 0]
I aim to create a dataset, using:
train_dataset = torch.utils.data.TensorDataset(torch.from_numpy(X_train), torch.from_numpy(y_train))
Currently, when I run an instance of y_train, the output is an array:
y_train[0]
>>> array([23], dtype=uint8)
However, I want train_dataset to contain only the number that's inside the array at the 0th index (in this case 23) instead of the entire array.
How can I change my code so that the TensorDataset that is created contains only the first element of the array of y_train, instead of the entire array?
| You can use np.squeeze() to get rid of dimensions of the data with size 1. If you mean to remove a specific dimension, pass it to squeeze.
import numpy as np
arr = np.random.randn(1, 2, 1, 3, 1)
arr.squeeze().shape # (2, 3)
arr.squeeze(2).shape # (1, 2, 3, 1)
| https://stackoverflow.com/questions/62679615/ |
How to disable TOKENIZERS_PARALLELISM=(true | false) warning? | I use pytorch to train huggingface-transformers model, but every epoch, always output the warning:
The current process just got forked. Disabling parallelism to avoid deadlocks... To disable this warning, please explicitly set TOKENIZERS_PARALLELISM=(true | false)
How to disable this warning?
| Set the environment variable to the string "false"
either by
TOKENIZERS_PARALLELISM=false
in your shell
or by:
import os
os.environ["TOKENIZERS_PARALLELISM"] = "false"
in the Python script
| https://stackoverflow.com/questions/62691279/ |
Unexpected model output running Onnx model in Unity using Barracuda | Context
I am trying to use a pre-trained model in ONNX format to do inference on image data in Unity. The model is linked to the executing component in Unity as an asset called modelAsset. I am using Barracuda version 1.0.0 for this and executing the model as follows:
// Initialisation
this.model = ModelLoader.Load(this.modelAsset);
this.worker = WorkerFactory.CreateWorker(WorkerFactory.Type.CSharpBurst, model);
// Loop
Tensor tensor = new Tensor(1, IMAGE_H, IMAGE_W, 3, data);
worker.Execute(tensor);
Tensor modelOutput = worker.PeekOutput(OUTPUT_NAME);
The data going into the input tensor (of which the model has only 1) is image data of h * w with 3 channels for RGB values between -0.5 and 0.5. The model has multiple outputs which I retrieve in the last line shown above.
Expected behavior
Using the same input data, the PyTorch model and converted ONNX model produce the same output data in Python (ONNXRuntime and PyTorch) as in Barracuda in Unity.
Problem
In python both the ONNX and PyTorch model produce the same output. However, the same ONNX model running in Barracuda produces a different output. The difference is mainly that we expect a heatmap but Barracuda consistently produces values somewhere between 0.001 and -0.0004 in these patterns:
This makes it almost seem like the model weights are not properly loaded.
What we found
When converting to ONNX as per the Barracuda manual we found that if we did not set the model to inference mode in the PyTorch net before conversion (link), these same, incorrect, results were generated by ONNXRuntime in Python. In other words, it looks like this inference mode is saved in the ONNX model and is recognized by ONNXRuntime in Python but not in Barracuda.
Our question
In general:
How do we get this model in Barracuda in Unity to produce the same results as ONNXRuntime/PyTorch in Python?
And potentially:
How does the inference mode get embedded into the ONNX file and how is it used in ONNXRuntime vs Barracuda?
| So it turned out that there were 2 problems.
First, the input data had been orchestrated according to the ONNX model dimensions, however, Barracuda expects differently oriented data. "The native ONNX data layout is NCHW, or channels-first. Barracuda automatically converts ONNX models to NHWC layout." So our data was flattened into an array similar to the Python implementation which created the first mismatch.
Secondly, the Y-axis of the input image was inverted, making the model unable to recognize any people.
After correcting for these issues, the implementation works fine!
| https://stackoverflow.com/questions/62698346/ |
Using torch.cat on list of tensors | I have a list of torch tensors
list_tensor = [tensor([[1, 2, 3],
[3, 4, 5]]),
tensor([[4, 5, 6],
[6, 4, 3]]),
tensor([[4, 2, 1],
[3, 3, 1]]),
tensor([[1, 4, 5],
[3, 1, 0]]),
tensor([[1, 3, 3],
[2, 2, 2]])]
I want to do a cross validation on this set, so I want to consider four tensors as training, and keep 1 for testing - and I want to do this for len(list_tensor) times.
So I thought of doing,
for num in range(1, len(list_tensor) + 1):
train_x = torch.cat((list_tensor[:num], list_tensor[num:]))
The problem is I cannot use lists for a torch.cat operation because both list_tensor[:num] and list_tensor[num:] return lists. For example, for num = 1,
list_tensor[:num] = [tensor([[1, 2, 3], [3, 4, 5]])]
list_tensor[num:] = [tensor([[4, 5, 6], [6, 4, 3]]), tensor([[4, 2, 1],[3, 3, 1]]), tensor([[1, 4, 5],
[3, 1, 0]]), tensor([[1, 3, 3], [2, 2, 2]])]
How do I perform torch.cat on this?
| I found a work around without using reduce.
train_x = torch.cat((torch.cat(list_tensor[:num+1]),torch.cat(list_tensor[num+1:])))
Basically concatenate all tensors in the individual list, this returns a torch.tensor object, then use torch.cat on both.
| https://stackoverflow.com/questions/62706747/ |
Does tf.math.reduce_max allows gradient flow like torch.max? | I am trying to build a multi-label binary classification model in Tensorflow. The model has a tf.math.reduce_max operator between two layers (It is not Max Pooling, it's for a different purpose).
And the number of classes is 3.
I am using Binary Cross Entropy loss and using Adam optimizer.
Even after hours of training, when I check the predictions, all the predictions are in the range 0.49 to 0.51.
It seems that the model is not learning anything and is making random predictions, which is making me think that using a tf.math.reduce_max function may be causing the problems.
However, I read on the web that the torch.max function allows back propagation of gradients through it.
When I checked the Graph in Tensorboard, I saw that the graph is showing unconnected at the tf.math.reduce_max operator.
SO, does this operator allows gradients ot back propagate through it?
EDIT :
Addin the code
input_tensor = Input(shape=(256, 256, 3))
base_model_toc = VGG16(input_tensor=input_tensor,weights='imagenet',pooling=None, include_top=False)
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = tf.math.reduce_max(x,axis=0,keepdims=True)
x = Dense(1024,activation='relu')(x)
output_1 = Dense(3, activation='sigmoid')(x)
model_a = Model(inputs=base_model_toc.input, outputs=output_1)
for layer in base_model.layers:
layer.trainable = True
THe tf.math.reduce_max is done along axis = 0 becasue that is what needs to be done in this model
Optimizer that I am using is Adam with initial learning rate 0.00001
| Yes, tf.math.reduce_max does allow gradients to flow. It is easy to check (this is TensorFlow 2.x but it is the same result in 1.x):
import tensorflow as tf
with tf.GradientTape() as tape:
x = tf.linspace(0., 2. * 3.1416, 10)
tape.watch(x)
# A sequence of operations involving reduce_max
y = tf.math.square(tf.math.reduce_max(tf.math.sin(x)))
# Check gradients
g = tape.gradient(y, x)
print(g.numpy())
# [ 0. 0. 0.3420142 -0. -0. -0.
# -0. 0. 0. 0. ]
As you can see, there is a valid gradient for y with respect to x. Only one of the values is not zero, because it is the value that then resulted in the maximum value, so it is the only value in x that affects the value of y. This is the correct gradient for the operation.
| https://stackoverflow.com/questions/62715811/ |
Why PyTorch model takes multiple image size inside the model? | I am using a simple object detection model in PyTorch and using a Pytoch Model for Inferencing.
When I am using a simple iterator over the code
for k, image_path in enumerate(image_list):
image = imgproc.loadImage(image_path)
print(image.shape)
with torch.no_grad():
y, feature = net(x)
result = image.cuda()
It prints our variable sized images such as
torch.Size([1, 3, 384, 320])
torch.Size([1, 3, 704, 1024])
torch.Size([1, 3, 1280, 1280])
So When I am using Batch Inferencing using a DataLoader applying the same transformation the code is not running.
However, when I am resizing all the images as 600.600 the batch processing runs successfully.
I am having Two Doubts,
First why Pytorch is capable of inputting dynamically sized inputs in Deep Learning Model and Why dynamic sized input is failing in Batch Processing.
| PyTorch has what is called a Dynamic Computational Graph (other explanation).
It allows the graph of the neural network to dynamically adapt to its input size, from one input to the next, during training or inference.
This is what you observe in your first example: providing an image as a Tensor of size [1, 3, 384, 320] to your model, then another one as a Tensor of size [1, 3, 384, 1024], and so forth, is completely fine, as, for each input, your model will dynamically adapt.
However, if your input is a actually a collection of inputs (a batch), it is another story. A batch, for PyTorch, will be transformed to a single Tensor input with one extra dimension. For example, if you provide a list of n images, each of the size [1, 3, 384, 320], PyTorch will stack them, so that your model has a single Tensor input, of the shape [n, 1, 3, 384, 320].
This "stacking" can only happen between images of the same shape. To provide a more "intuitive" explanation than previous answers, this stacking operation cannot be done between images of different shapes, because the network cannot "guess" how the different images should "align" with one another in a batch, if they are not all the same size.
No matter if it happens during training or testing, if you create a batch out of images of varying size, PyTorch will refuse your input.
Several solutions are usually in use: reshaping as you did, adding padding (often small or null values on the border of your images) to extend your smaller images to the size of the biggest one, and so forth.
| https://stackoverflow.com/questions/62719641/ |
Meaning of the outlined code written in C? | I am currently building an understanding around PyTorch and I have come across few codes written in C language. Since I am not that familiar with C conventions, could anyone elaborate what does this code mean?
typedef float float4 __attribute__((ext_vector_type(4)));
typedef float float8 __attribute__((ext_vector_type(8)));
#define LoadFloat8(PTR) *((const float8 *)(PTR))
The code is taken from here
| GNU GCC Vector extensions
the instruction set contains SIMD vector instructions which operate on multiple values contained in one large register at the same time.
for using these extensions we need to provide the necessary data types (like your example). This should be done using an appropriate typedef, for example:
typedef int v4si __attribute__ ((vector_size (16)));
The int type specifies the base type, while the attribute specifies the vector size for the variable, measured in bytes. the declaration above causes the compiler to set the mode for the v4si type to be 16 bytes wide and divided into int sized units. For a 32-bit int this means a vector of 4 units of 4 bytes, and the corresponding mode of foo is V4SI.
int the first typedef in your example it is a way to let the compiler know you only care about the value of the first 4 elements of a 4 element SIMD register. So compiler can do optimizations that leave different garbage in the high elements/Bytes when manipulating this data type.
keep reading in the link below:
Using Vector Instructions through Built-in Functions
| https://stackoverflow.com/questions/62722944/ |
Installed pytorch through conda, but cannot import in Windows 10 | When I issue an Anaconda prompt conda search pytorch
then I get pytorch installed even issuing conda list command gives me:
pytorch 1.5.1 py3.7_cuda102_cudnn7_0 pytorch
But when I start python on command prompt and then issue import pytorch i get ModuleNotFoundError: No module named 'pytorch'.
Even I tried to do the same after issuing
conda create -n pytorch_env -c pytorch pytorch torchvision
conda activate pytorch_env
conda install -c pytorch pytorch torchvision
as written in Installing PyTorch via Conda but of no use. BTW does it require a restart of the machine after installing Anaconda? Also, let me know how I can use PyTorch in Jupyter notebooks.
| Verify the installation with import torch not pytorch. Example code below, source.
from __future__ import print_function
import torch
x = torch.rand(5, 3)
print(x)
If above throws same issue in Jupyter Notebooks and if you already have GPU enabled, try restarting the Jupyter notebook server as sometimes it requires restarting, user reported.
when I tried to import this package from Jupyter notebook, I got following error message: ModuleNotFoundError: No module named 'torch'. Then, I tried installing Jupyter notebook application from Anaconda navigator for my environment(torch).
Restarted my Jupyter notebook and ran import torch and this time it worked
Otherwise, you need CPU only version of PyTorch.
conda install pytorch torchvision cpuonly -c pytorch
| https://stackoverflow.com/questions/62724307/ |
What is the param `last_epoch` on Pytorch Optimizer's Schedulers is for? | Regarding Pytorch Optimizer's Schedulers, what actually means the last_epoch argument?
It says
last_epoch (int) – The index of last epoch. Default: -1.
But it doesn't really explains much for those, like me, are just learning about these schedules.
I read most of that documentation, if not all, and I could understand what it does and why.
| The last_epoch parameter is used when resuming training and you want to start the scheduler where it left off earlier. Its value is increased every time you call .step() of scheduler. The default value of -1 indicates that the scheduler is started from the beginning.
From the docs:
Since step() should be invoked after each batch instead of after each epoch, this number represents the total number of batches computed, not the total number of epochs computed. When last_epoch=-1, the schedule is started from the beginning.
For example,
>>> import torch
>>> cc = torch.nn.Conv2d(10,10,3)
>>> myoptimizer = torch.optim.Adam(cc.parameters(), lr=0.1)
>>> myscheduler = torch.optim.lr_scheduler.StepLR(myoptimizer,step_size=1, gamma=0.1)
>>> myscheduler.last_epoch, myscheduler.get_lr()
(0, [0.1])
>>> myscheduler.step()
>>> myscheduler.last_epoch, myscheduler.get_lr()
(1, [0.001])
>>> myscheduler.step()
>>> myscheduler.last_epoch, myscheduler.get_lr()
(2, [0.0001])
Now, if you decide to stop the training in the middle, then resume it, you can provide last_epoch parameter to schedular so that it start from where it was left off, not from the beginning again.
>>> mynewscheduler = torch.optim.lr_scheduler.StepLR(myoptimizer,step_size=1, gamma=0.1, last_epoch=myscheduler.last_epoch)
>>> mynewscheduler.last_epoch, mynewscheduler.get_lr()
(3, [1.0000000000000004e-05])
| https://stackoverflow.com/questions/62724824/ |
PyTorch can't see GPU (torch.cuda.is_availble() returns False) | I have a problem where
import torch
print(torch.cuda_is_available())
will print False, and I can't use the GPU available. I've tried it on conda environment, where I've installed the PyTorch version corresponding to the NVIDIA driver I have. I've also tried it in docker container, where I've done the same. I've tried both of these options on a remote server, but they both failed. I know that I've installed the correct driver versions because I've checked the version with nvcc --version before installing PyTorch, and I've checked the GPU connection with nvidia-smi which displays the GPUs on the machines correctly.
Also, I've checked this post and tried exporting CUDA_VISIBLE_DEVICES, but had no luck.
On the server I have NVIDIA V100 GPUs with CUDA version 10.0 (for conda environment) and version 10.2 on a docker container I've built. Any help or push in the right direction would be greatly appreciated. Thanks!
| For anyone else having this problem, it turned out my server manager has not updated the drivers for the server.
I switched to a different server, installed anaconda and things started working like it should, i.e., torch.cuda.is_available() returns True after setting up a fresh environment.
| https://stackoverflow.com/questions/62728485/ |
How is a minibatch processed by the GPU in PyTorch? | I am trying to understand how PyTorch actually performs a forward pass over a minibatch. When a minibatch is processed by a network, is each example in the minibatch (e.g. each image) sent forwards individually, one after the other? Or are all examples in the minibatch sent forwards at the same time?
When an example is sent forwards through a network, the additional memory requirement is the activations at each layer. And as long as the network does not take up the entire GPU, then it seems that multiple instantiations of these activations could be stored at the same time. Each instantiation could then be used to store the activations for one example in the minibatch. And therefore, multiple examples could be sent through the network simultaneously. However, I'm unsure whether this is actually done in practice.
I have done some simple experiments, and the time for a forward pass is roughly proportional to the minibatch size. This suggests that the examples are sent through one after the other. If so, then why is it that people say that training is faster when the minibatch size is larger? It seems that the processing time for an entire epoch would not be dependent on the minibatch size.
|
I am trying to understand how PyTorch actually performs a forward pass over a minibatch. When a minibatch is processed by a network, is each example in the minibatch (e.g. each image) sent forwards individually, one after the other? Or are all examples in the minibatch sent forwards at the same time?
All at the same time. To do so, it relies on batch processing, broadcasting, element-wise vectorization for non-linear operations (basically, a highly optimized for-loop, sometimes in parrallel) and matrix linear algebra. The later is much more efficient than a for-loop, since it can leverage dedicated hardware component designed for parallel linear algebra (this is true for both cpu and gpu, but gpu are especially well suited for this).
Each instantiation could then be used to store the activations for one example in the minibatch. And therefore, multiple examples could be sent through the network simultaneously. However, I'm unsure whether this is actually done in practice.
This is not how it works, torch is keeping track of "operations", each of them having a backward used computing the gradient of the inputs wrt to the outputs. It is designed to support batch processing and vectorization, such that processing a bunch of samples is done at once as in single backward pass.
I have done some simple experiments, and the time for a forward pass is roughly proportional to the minibatch size.
This is not true. It may be because you are already eating up 100% of the available resources (cpu or gpu), or because you are not doing the profiling properly (which is not so easy to do). If you post an example, one you try to help you on this point.
| https://stackoverflow.com/questions/62735719/ |
Using torchtext for inference | I wonder what is the right way to use torchtext for inference.
Let's assume I've trained the model and dump all Fields with built vocabularies. It seems the next step is to use torchtext.data.Example to load one single example. Somehow I should numeralize it by using loaded Fields and create an Iterator.
I would appreciate any simple examples of using torchtext for inference.
| For a trained model and vocabulary (which is part of the text field , you don't have to save the whole class) :
def read_vocab(path):
#read vocabulary pkl
import pickle
pkl_file = open(path, 'rb')
vocab = pickle.load(pkl_file)
pkl_file.close()
return vocab
def load_model_and_vocab():
import torch
import os.path
my_path = os.path.abspath(os.path.dirname(__file__))
vocab_path = os.path.join(my_path, vocab_file)
weights_path = os.path.join(my_path, WEIGHTS)
vocab = read_vocab(vocab_path)
model = classifier(vocab_size=len(vocab))
model.load_state_dict(torch.load(weights_path))
model.eval()
return model, vocab
def predict(model, vocab, sentence):
tokenized = [w.text.lower() for w in nlp(sentence)] # tokenize the sentence
indexed = [vocab.stoi[t] for t in tokenized] # convert to integer sequence
length = [len(indexed)] # compute no. of words
tensor = torch.LongTensor(indexed).to('cpu') # convert to tensor
tensor = tensor.unsqueeze(1).T # reshape in form of batch,no. of words
length_tensor = torch.LongTensor(length) # convert to tensor
prediction = model(tensor, length_tensor) # prediction
return round(1-prediction.item())
"classifier" is the class I defined for my model.
For saving the vocabulary pkl :
def save_vocab(vocab):
import pickle
output = open('vocab.pkl', 'wb')
pickle.dump(vocab, output)
output.close()
And for saving the model after training you can use :
torch.save(model.state_dict(), 'saved_weights.pt')
Tell me if it worked for you!
| https://stackoverflow.com/questions/62744998/ |
ImportError: cannot import name 'hf_bucket_url' in HuggingFace Transformers | So I installed the latest version of transformers on Google Colab
!pip install transformers
When trying to invoke the conversion file using
!python /usr/local/lib/python3.6/dist-packages/transformers/convert_pytorch_checkpoint_to_tf2.py .py --help
Or trying to use
from transformers.file_utils import hf_bucket_url. // works
from transformers.convert_pytorch_checkpoint_to_tf2 import *. // fails
convert_pytorch_checkpoint_to_tf("gpt2", pytorch_file, config_file, tf_file).
I get this error
ImportError Traceback (most recent call last)
<ipython-input-3-dadaf83ecea0> in <module>()
1 from transformers.file_utils import hf_bucket_url
----> 2 from transformers.convert_pytorch_checkpoint_to_tf2 import *
3
4 convert_pytorch_checkpoint_to_tf("gpt2", pytorch_file, config_file, tf_file)
/usr/local/lib/python3.6/dist-packages/transformers/convert_pytorch_checkpoint_to_tf2.py in <module>()
20 import os
21
---> 22 from transformers import (
23 ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
24 BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
ImportError: cannot import name 'hf_bucket_url'
What's going on?
| It turns out to be a bug. This PR solves the issue by importing the function hf_bucket_url properly.
| https://stackoverflow.com/questions/62746180/ |
Python print file name from a Data class | I'm trying to print a filename from a class. The class is defined in here in the below code. The code runs without any issues but it doesn't print the filename, my guess is that i have an issue with calling the class.
I am trying to call the class in another file to print the file name into a CSV during training, and using this code to do this:
filename=CellsDataset(args.data_dir,transform=ToTensor(),return_filenames=True)
print(filename)
| A CellsDataSet contains a list of filenames in its files attribute, so you can print all of them like this:
filename=CellsDataset(args.data_dir,transform=ToTensor(),return_filenames=True)
print(filename.files)
| https://stackoverflow.com/questions/62757663/ |
How to get a specific sample from pytorch DataLoader? | In Pytorch, is there any way of loading a specific single sample using the torch.utils.data.DataLoader class? I'd like to do some testing with it.
The tutorial uses
trainloader = torch.utils.data.DataLoader(...)
images, labels = next(iter(trainloader))
to fetch a random batch of samples. Is there are way, using DataLoader, to get a specific sample?
Cheers
|
Turn off the shuffle in DataLoader
Use batch_size to calculate the batch in which the desired sample you are looking for falls in
Iterate to the desired batch
Code
import torch
import numpy as np
import itertools
X= np.arange(100)
batch_size = 2
dataloader = torch.utils.data.DataLoader(X, batch_size=batch_size, shuffle=False)
sample_at = 5
k = int(np.floor(sample_at/batch_size))
my_sample = next(itertools.islice(dataloader, k, None))
print (my_sample)
Output:
tensor([4, 5])
| https://stackoverflow.com/questions/62759281/ |
Parallelization strategies for deep learning | What strategies and forms of parallelization are feasible and available for training and serving a neural network?:
inside a machine across cores (e.g. GPU / TPU / CPU)
across machines on a network or a rack
I'm also looking for evidence for how they may also be used in e.g. TensorFlow, PyTorch or MXNet.
Training
To my knowledge, when training large neural networks on large datasets, one could at least have:
Different cores or machines operate on different parts of the graph ("graph splitting"). E.g. backpropagation through the graph itself can be parallelized e.g. by having different layers hosted on different machines since (I think?) the autodiff graph is always a DAG.
Different cores or machines operate on different samples of data ("data splitting"). In SGD, the computation of gradients across batches or samples can also be parallelized (e.g. the gradients can be combined after computing them independently on different batches). I believe this is also called gradient accumulation (?).
When is each strategy better for what type of problem or neural network? Which modes are supported by modern libraries? and can one combine all four (2x2) strategies?
On top of that, I have read about:
Asynchronous training
Synchronous training
but I don't know what exactly that refers to, e.g. is it the computation of gradients on different data batches or the computation of gradients on different subgraphs? Or perhaps it refers to something else altogether?
Serving
If the network is huge, prediction / inference may also be slow, and the model may not fit on a single machine in memory at serving time. Are there any known multi-core and multi-node prediction solutions that work that can handle such models?
| As the question is quite broad, I'll try to shed a little different light and touch on different topics than what was shown in
@Daniel's in-depth answer.
Training
Data parallelization vs model parallelization
As mentioned by @Daniel data parallelism is used way more often and is easier to do correctly. Major caveat of model parallelism is the need to wait for part of neural network and synchronization between them.
Say you have a simple feedforward 5 layer neural network spread across 5 different GPUs, each layer for one device. In this case, during each forward pass each device has to wait for computations from the previous layers. In this simplistic case, copying data between devices and synchronization would take a lot longer and won't bring benefits.
On the other hand, there are models better suited for model parallelization like Inception networks, see picture below:
Here you can see 4 independent paths from previous layer which could go in parallel and only 2 synchronization points (Filter concatenation and Previous Layer).
Questions
E.g. backpropagation through the graph itself can be parallelized e.g.
by having different layers hosted on different machines since (I
think?) the autodiff graph is always a DAG.
It's not that easy. Gradients are calculated based on the loss value (usually) and you need to know gradients of deeper layers to calculate gradients for the more shallow ones. As above, if you have independent paths it's easier and may help, but it's way easier on a single device.
I believe this is also called gradient accumulation (?)
No, it's actually reduction across multiple devices. You can see some of that in PyTorch tutorial. Gradient accumulation is when you run your forward pass (either on single or multiple devices) N times and backpropagate (the gradient is kept in the graph and the values are added during each pass) and optimizer only makes a single step to change neural network's weights (and clears the gradient). In this case, loss is usually divided by the number of steps without optimizer. This is used for more reliable gradient estimation, usually when you are unable to use large batches.
Reduction across devices looks like this:
This is all-reduce in data parallelization, each device calculates the values which are send to all other devices and backpropagated there.
When is each strategy better for what type of problem or neural
network?
Described above, data parallel is almost always fine if you have enough of data and the samples are big (up to 8k samples or more can be done at once without very big struggle).
Which modes are supported by modern libraries?
tensorflow and pytorch both support either, most modern and maintained libraries have those functionalities implemented one way or another
can one combine all four (2x2) strategies
Yes, you can parallelize both model and data across and within machines.
synchronous vs asynchronous
asynchronous
Described by @Daniel in brief, but it's worth mentioning updates are not totally separate. That would make little sense, as we would essentially train N different models based on their batches.
Instead, there is a global parameter space, where each replica is supposed to share calculated updates asynchronously (so forward pass, backward, calculate update with optimizer and share this update to global params).
This approach has one problem though: there is no guarantee that when one worker calculated forward pass another worker updated the parameters, so the update is calculated with respect to old set of params and this is called stale gradients. Due to this, convergence might be hurt.
Other approach is to calculate N steps and updates for each worker and synchronize them afterwards, though it's not used as often.
This part was based on great blogpost and you should definitely read it if interested (there is more about staleness and some solutions).
synchronous
Mostly described previously, there are different approaches but PyTorch gathers output from network and backpropagates on them (torch.nn.parallel.DistributedDataParallel)[https://pytorch.org/docs/stable/nn.html#torch.nn.parallel.DistributedDataParallel]. BTW. You should solely this (no torch.nn.DataParallel) as it overcomes Python's GIL problem.
Takeaways
Data parallelization is always almost used when going for speed up as you "only" have to replicate neural network on each device (either over the network or within single machine), run part of batch on each during the forward pass, concatenate them into a single batch (synchronization) on one device and backpropagate on said.
There are multiple ways to do data parallelization, already introduced by @Daniel
Model parallelization is done when the model is too large to fit on single machine (OpenAI's GPT-3 would be an extreme case) or when the architecture is suited for this task, but both are rarely the case AFAIK.
The more and the longer parallel paths the model has (synchronization points), the better it might be suited for model parallelization
It's important to start workers at similar times with similar loads in order not to way for synchronization processes in synchronous approach or not to get stale gradients in asynchronous (though in the latter case it's not enough).
Serving
Small models
As you are after large models I won't delve into options for smaller ones, just a brief mention.
If you want to serve multiple users over the network you need some way to scale your architecture (usually cloud like GCP or AWS). You could do that using Kubernetes and it's PODs or pre-allocate some servers to handle requests, but that approach would be inefficient (small number of users and running servers would generate pointless costs, while large numbers of users may halt the infrastructure and take too long to process resuests).
Other way is to use autoscaling based on serverless approach. Resources will be provided based on each request so it has large scaling abilities + you don't pay when the traffic is low. You can see Azure Functions as they are on the path to improve it for ML/DL tasks, or torchlambda for PyTorch (disclaimer, I'm the author) for smaller models.
Large models
As mentioned previously, you could use Kubernetes with your custom code or ready to use tools.
In the first case, you can spread the model just the same as for training, but only do forward pass. In this way even giant models can be put up on the network (once again, GPT-3 with 175B parameters), but requires a lot of work.
In the second, @Daniel provided two possibilities. Others worth mentioning could be (read respective docs as those have a lot of functionalities):
KubeFlow - multiple frameworks, based on Kubernetes (so auto-scaling, multi-node), training, serving and what not, connects with other things like MLFlow below
AWS SageMaker - training and serving with Python API, supported by Amazon
MLFlow - multiple frameworks, for experiment handling and serving
BentoML - multiple frameworks, training and serving
For PyTorch, you could read more here, while tensorflow has a lot of serving functionality out of the box via Tensorflow EXtended (TFX).
Questions from OP's comment
Are there any forms of parallelism that are better within a machine vs
across machines
The best for of parallelism would probably be within one giant computer as to minimize transfer between devices.
Additionally, there are different backends (at least in PyTorch) one can choose from (mpi, gloo, nccl) and not all of them support direct sending, receiving, reducing etc. data between devices (some may support CPU to CPU, others GPU to GPU). If there is no direct link between devices, those have to be first copied to another device and copied again to target device (e.g. GPU on other machine -> CPU on host -> GPU on host). See pytorch info.
The more data and the bigger network, the more profitable it should be to parallelize computations. If whole dataset can be fit on a single device there is no need for parallelization. Additionally, one should take into account things like internet transfer speed, network reliability etc. Those costs may outweigh benefits.
In general, go for data parallelization if you have lots of of data (say ImageNet with 1.000.000 images) or big samples (say images 2000x2000). If possible, within a single machine as to minimize between-machines transfer. Distribute model only if there is no way around it (e.g. it doesn't fit on GPU). Don't otherwise (there is little to no point to parallelize when training MNIST as the whole dataset will easily fit in RAM and the read will be fastest from it).
why bother build custom ML-specific hardware such as TPUs?
CPUs are not the best suited for highly parallel computations (e.g. matrices multiplication) + CPU may be occupied with many other tasks (like data loading), hence it makes sense to use GPU.
As GPU was created with graphics in mind (so algebraic transformation), it can take some of CPU duties and can be specialized (many more cores when compared to CPU but simpler ones, see V100 for example).
Now, TPUs are tailored specificially for tensor computations (so deep learning mainly) and originated in Google, still WIP when compared to GPUs. Those are suited for certain types of models (mainly convolutional neural networks) and can bring speedups in this case. Additionally one should use the largest batches with this device (see here), best to be divisible by 128. You can compare that to NVidia's Tensor Cores technology (GPU) where you are fine with batches (or layer sizes) divisible by 16 or 8 (float16 precision and int8 respectively) for good utilization (although the more the better and depends on number of cores, exact graphic card and many other stuff, see some guidelines here).
On the other hand, TPUs support still isn't the best, although two major frameworks support it (tensorflow officially, while PyTorch with torch_xla package).
In general, GPU is a good default choice in deep learning right now, TPUs for convolution heavy architectures, though might give some headache tbh. Also (once again thanks @Daniel), TPUs are more power effective, hence should be cheaper when comparing single floating point operation cost.
| https://stackoverflow.com/questions/62759940/ |
Index multidimensional torch tensor by another multidimensional tensor | I have a tensor x in pytorch let's say of shape (5,3,2,6) and another tensor idx of shape (5,3,2,1) which contain indices for every element in first tensor. I want a slicing of the first tensor with the indices of the second tensor. I tried x= x[idx] but I get a weird dimensionality when I really want it to be of shape (5,3,2) or (5,3,2,1).
I'll try to give an easier example:
Let's say
x=torch.Tensor([[10,20,30],
[8,4,43]])
idx = torch.Tensor([[0],
[2]])
I want something like
y = x[idx]
such that 'y' outputs [[10],[43]] or something like.
The indices represent the position of the wanted elements the last dimension. for the example above where x.shape = (2,3) the last dimension are the columns, then the indices in 'idx' is the column. I want this but for more than 2 dimensions
| From what I understand from the comments, you need idx to be index in the last dimension and each index in idx corresponds to similar index in x (except for the last dimension). In that case (this is the numpy version, you can convert it to torch):
ind = np.indices(idx.shape)
ind[-1] = idx
x[tuple(ind)]
output:
[[10]
[43]]
| https://stackoverflow.com/questions/62762769/ |
How can I fix the “TypeError: 'Tensor' object is not callable” error in Pytorch? | I am trying to compute a linear function an image's pixels, followed by log softmax (it's for a classification task). I am not sure how to do this without getting errors. Here is the relevant code:
...
torch.nn.functional.nll_loss(output, target) # error happens here
...
def __init__(self):
super(NetLin, self).__init__()
self.in_out = torch.nn.Linear(28, 2)
def forward(self, input):
out_sum = self.in_out(input)
output = torch.nn.LogSoftmax(out_sum)
return output
and the full error message I get is:
Traceback (most recent call last):
File "copy.py", line 98, in <module>
main()
File "copy.py", line 94, in main
train(args, net, device, train_loader, optimizer, epoch)
File "copy.py", line 21, in train
loss = torch.nn.functional.nll_loss(output, target)
File "/usr/local/lib/python3.7/site-packages/torch/nn/functional.py", line 2107, in nll_loss
dim = input.dim()
TypeError: 'Tensor' object is not callable
I have tried a few different solutions to this based on other answers online but they just result in different error messages. Clearly I am doing something fundamentally wrong here but I haven't used Pytorch before so I'm not sure what it is. Thank you
Edit:
My code is now:
def train(args, model, device, train_loader, optimizer, epoch):
if args.net == 'lin':
model = NetLin()
model.train()
loss = nn.NLLLoss()
for batch_idx, (data, target) in enumerate(train_loader):
data.requires_grad = True
data, target = data.to(device), target.to(device)
optimizer.zero_grad()
output = loss(model(input), target)
F.nll_loss(output, target)
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
class NetLin(nn.Module):
def __init__(self):
super(NetLin, self).__init__()
self.in_out = torch.nn.Linear(28 * 28, 2)
def forward(self, input):
input = input.view(-1, 28 * 28)
out_sum = self.in_out(input)
output = torch.nn.LogSoftmax(out_sum, dim=1)
return output
and my error message is now:
Traceback (most recent call last):
File "copy.py", line 102, in <module>
main()
File "copy.py", line 98, in main
train(args, net, device, train_loader, optimizer, epoch)
File "copy.py", line 24, in train
output = loss(model(input), target)
File "/usr/local/lib/python3.7/site-packages/torch/nn/modules/module.py", line 550, in __call__
result = self.forward(*input, **kwargs)
File "/Users/.../copy.py", line 15, in forward
input = input.view(-1, 28 * 28)
AttributeError: 'builtin_function_or_method' object has no attribute 'view'
As you can kind of see the data and target are read in from a file (they are from KMNIST actually) so I can't control their format exactly, but I do know the image sizes are all [1,28,28], i.e. a 28*28 greyscale image. Also the batch size is 64 in case that matters.
| Did you remember to set your model to training mode in your train loop with model.train()? Also, nll_loss takes in 2 tensors, but the first entry (the input tensor) needs to have requires_grad=True before it goes through the model, which is also why you need to set model.train() before training.
So you would have something like this:
model = NetLin()
model.train()
loss = nn.NLLLoss()
input = torch.randn(7, 4, requires_grad=True) # your input image (tensor)
target = torch.tensor([1, 0]) # image label for image belonging to first class
output = loss(model(input), target)
I am also a bit concerned about your self.in_out = torch.nn.Linear(28, 2). This says that your linear layer is expecting 28 features, implying that your input images are either 7x4, 14x2 or 28x1, which doesn't seem right in my opinion? Aren't you using images of size 28x28 (very typical size in this context)? In which case, you would have your linear layer modified as self.in_out = torch.nn.Linear(28*28, 2), and your forward pass will have to be modified as follows:
def forward(self, input):
input = input.view(-1, 28*28)
out_sum = self.in_out(input)
output = torch.nn.LogSoftmax(out_sum)
return output
| https://stackoverflow.com/questions/62768081/ |
model.parameters() not updating in Linear Regression with Pytorch | I'm a newbie in Deep Learning with Pytorch. I am using the Housing Prices dataset from Kaggle here. I tried sampling with first 50 rows. But the model.parameters() is not updating as I perform the training. Can anyone help?
import torch
import numpy as np
from torch.utils.data import TensorDataset
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.functional as F
inputs = np.array(label_X_train[:50])
targets = np.array(train_y[:50])
# Tensors
inputs = torch.from_numpy(inputs)
targets = torch.from_numpy(targets)
targets = targets.view(-1, 1)
train_ds = TensorDataset(inputs, targets)
batch_size = 5
train_dl = DataLoader(train_ds, batch_size, shuffle=True)
model = nn.Linear(10, 1)
# Define Loss func
loss_fn = F.mse_loss
# Optimizer
opt = torch.optim.SGD(model.parameters(), lr = 1e-5)
num_epochs = 100
model.train()
for epoch in range(num_epochs):
# Train with batches of data
for xb, yb in train_dl:
# 1. Generate predictions
pred = model(xb.float())
# 2. Calculate loss
loss = loss_fn(pred, yb.float())
# 3. Compute gradients
loss.backward()
# 4. Update parameters using gradients
opt.step()
# 5. Reset the gradients to zero
opt.zero_grad()
if (epoch+1) % 10 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch +
1, num_epochs,
loss.item()))
| The weight does update, but you weren't capturing it correctly. model.weight.data is a torch tensor, but the name of the variable is just a reference, so setting w = model.weight.data does not create a copy but another reference to the object. Hence changing model.weight.data would change w too.
So by setting w = model.weight.data and w_new = model.weight data in different part of the loops means you're assigning two reference to the same object making their value equal at all time.
In order to assess that the model weight are changing, either print(model.weight.data) before and after the loop (since you got one linear layer of 10 parameters it's still okay to do that) or simply set w = model.weight.data.clone(). In that case your output will be:
tensor([[False, False, False, False, False, False, False, False, False, False]])
Here's an example that shows you that your weights are changing:
import torch
import numpy as np
from torch.utils.data import TensorDataset
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.nn.functional as F
inputs = np.random.rand(50, 10)
targets = np.random.randint(0, 2, 50)
# Tensors
inputs = torch.from_numpy(inputs)
targets = torch.from_numpy(targets)
targets = targets.view(-1, 1)
train_ds = TensorDataset(inputs, targets.squeeze())
batch_size = 5
train_dl = DataLoader(train_ds, batch_size, shuffle=True)
model = nn.Linear(10, 1)
# Define Loss func
loss_fn = F.mse_loss
# Optimizer
opt = torch.optim.SGD(model.parameters(), lr = 1e-1)
num_epochs = 100
model.train()
w = model.weight.data.clone()
for epoch in range(num_epochs):
# Train with batches of data
for xb, yb in train_dl:
# 1. Generate predictions
pred = model(xb.float())
# 2. Calculate loss
loss = loss_fn(pred, yb.float())
# 3. Compute gradients
loss.backward()
# 4. Update parameters using gradients
opt.step()
# 5. Reset the gradients to zero
opt.zero_grad()
if (epoch+1) % 10 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch +
1, num_epochs,
loss.item()))
print(w == model.weight.data)
| https://stackoverflow.com/questions/62775976/ |
Expected object of device type cuda but got device type cpu for argument #2 'mat2' in call to _th_mm | I recently have access to a GPU and have tried to run my code but there is an error. I've read about adding .cuda() to the layers could help but I have ran similar code without the "qml" part and it worked just fine without changing the layer (with cuda I mean). For the sake of brevity, I only added the class for the neural network and the entire loop of the code. The missing part of the code is for other aspects. But if there is a need for the rest of the code, I would be happy to include everything.
Code:
class DQN(nn.Module):
def __init__(self, img_height, img_width):
super().__init__()
self.flatten = nn.Flatten()
self.fc1 = nn.Linear(in_features=img_height * img_width * 3, out_features=12)
self.fc2 = nn.Linear(in_features=12, out_features=8)
# self.fc3 = nn.Linear(in_features=10, out_features=8)
self.clayer_in = torch.nn.Linear(in_features=8, out_features=wires)
self.clayer_out = torch.nn.Linear(wires, out_dim)
dev = qml.device('strawberryfields.fock', wires=wires, cutoff_dim=3)
self.layer_qnode = qml.QNode(layer, dev)
weights = qml.init.cvqnn_layers_all(n_quantum_layers, wires)
weight_shapes = {"w{}".format(i): w.shape for i, w in enumerate(weights)}
self.qlayer = qml.qnn.TorchLayer(self.layer_qnode, weight_shapes)
def forward(self, t):
t = self.flatten(t)
t = self.fc1(t)
t = self.fc2(t)
# t = self.fc3(t)
t = self.clayer_in(t)
t = self.qlayer(t)
t = self.clayer_out(t)
t = t.sigmoid()
return t
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
#print(device)
em = CartPoleEnvManager(device)
strategy = EpsilonGreedyStrategy(eps_start, eps_end, eps_decay)
agent = Agent(strategy, em.num_actions_available(), device)
memory = ReplayMemory(memory_size)
#learning_rate = LearningRate(lr_start,lr_end,lr_decay)
#learn = lr(learning_rate)
policy_net = DQN(em.get_screen_height(), em.get_screen_width()).to(device)
target_net = DQN(em.get_screen_height(), em.get_screen_width()).to(device)
target_net.load_state_dict(policy_net.state_dict())
target_net.eval() #tells pytorch that target_net is only used for inference, not training
optimizer = optim.Adam(params=policy_net.parameters(), lr=0.01)
i = 0
episode_durations = []
for episode in range(num_episodes): #iterate over each episode
program_starts = time.time()
em.reset()
state = em.get_state()
for timestep in count():
action = agent.select_action(state, policy_net)
reward = em.take_action(action)
next_state = em.get_state()
memory.push(Experience(state, action, next_state, reward))
state = next_state
#i+=1
#print(i)
if memory.can_provide_sample(batch_size):
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=100, gamma=0.9)
experiences = memory.sample(batch_size)
states, actions, rewards, next_states = extract_tensors(experiences)
current_q_values = QValues.get_current(policy_net, states, actions)
next_q_values = QValues.get_next(target_net, next_states) #will get the max qvalues of the next state, q values of next state are used via next state
target_q_values = (next_q_values * gamma) + rewards
loss = F.mse_loss(current_q_values, target_q_values.unsqueeze(1))
optimizer.zero_grad() # sets the gradiesnt of all weights n biases in policy_net to zero
loss.backward() #computes gradient of loss with respect to all weights n biases in the policy net
optimizer.step() # updates the weights n biases with the gradients that were computed form loss.backwards
scheduler.step()
if em.done:
episode_durations.append(timestep)
plot(episode_durations, 100)
break
if episode % target_update == 0:
target_net.load_state_dict(policy_net.state_dict())
now = time.time()
print("Episode hat {0} Sekunden gedauert".format(now - program_starts))
em.close()
And the error:
Traceback (most recent call last):
File "qdqn.py", line 328, in <module>
loss.backward() #computes gradient of loss with respect to all weights n biases in the policy net
File "/home/ubuntu/anaconda3/envs/gymm/lib/python3.8/site-packages/torch/tensor.py", line 198, in backward
torch.autograd.backward(self, gradient, retain_graph, create_graph)
File "/home/ubuntu/anaconda3/envs/gymm/lib/python3.8/site-packages/torch/autograd/__init__.py", line 98, in backward
Variable._execution_engine.run_backward(
RuntimeError: Expected object of device type cuda but got device type cpu for argument #2 'mat2' in call to _th_mm
| The solution is that the python package "pennylane" doesn't yet have the resources built out to work on GPUs. Since Pennylane is a relatively new package, this is something they plan to build out in the future.
| https://stackoverflow.com/questions/62780158/ |
Pytorch: Differentiable counting | I need to count the number of elements in a tensor that satisfy a condition, such as counting the number of people with age == 60, or people with age >= 50. Is there a differentiable approximation to the counting function?
| Use torch.Tensor.sum or torch.sum on boolean tensor returned by age >= 50
age = torch.arange(75)
(age >= 50).sum()
tensor(25)
| https://stackoverflow.com/questions/62783651/ |
PyTorch TypeError: 'ToTensor' object is not iterable | I'm trying to print an image name at each iteration. However, I'm getting an error TypeError: 'ToTensor' object is not iterable. Please could some advise where I am going wring please? Many Thanks
from torchvision import datasets
import torch.utils.data
from torch.utils.data import DataLoader
from torchvision import transforms
from dataset2 import CellsDataset
from torchvision import datasets
import torch
import torchvision
import torchvision.transforms as transforms
class ImageFolderWithPaths(datasets.ImageFolder):
"""Custom dataset that includes image file paths. Extends
torchvision.datasets.ImageFolder
"""
# override the __getitem__ method. this is the method that dataloader calls
def __getitem__(self, index):
# this is what ImageFolder normally returns
original_tuple = super(ImageFolderWithPaths, self).__getitem__(index)
# the image file path
path = self.imgs[index][0]
# make a new tuple that includes original and the path
tuple_with_path = (original_tuple + (path,))
return tuple_with_path
# EXAMPLE USAGE:
# instantiate the dataset and dataloader
data_dir = "/Users/nubstech/Documents/GitHub/CellCountingDirectCount/Eddata/"
dataset = ImageFolderWithPaths(data_dir) # our custom dataset
#dataloader = DataLoader(dataset)
transform = transforms.Compose([
# you can add other transformations in this list
transforms.ToTensor()
])
dataset = DataLoader(data_dir, transforms.Compose(transforms.ToTensor()))
dataloader = torch.utils.DataLoader(dataset)
# iterate over data
for inputs, labels, paths in dataloader:
# use the above variables freely
print(inputs, labels, paths)
Traceback Message:
Traceback (most recent call last):
File "file_location2.py", line 37, in <module>
dataset = DataLoader(data_dir, transforms.Compose(transforms.ToTensor()))
File "/Users/nubstech/opt/anaconda3/envs/Cells_Counting/lib/python3.7/site-packages/torch/utils/data/dataloader.py", line 219, in __init__
batch_sampler = BatchSampler(sampler, batch_size, drop_last)
File "/Users/nubstech/opt/anaconda3/envs/Cells_Counting/lib/python3.7/site-packages/torch/utils/data/sampler.py", line 190, in __init__
"but got batch_size={}".format(batch_size))
File "/Users/nubstech/opt/anaconda3/envs/Cells_Counting/lib/python3.7/site-packages/torchvision/transforms/transforms.py", line 66, in __repr__
for t in self.transforms:
TypeError: 'ToTensor' object is not iterable
| It's because transforms.Compose() needs to be a list (probably some other iterables are accepted too). The problem is here:
dataset = DataLoader(data_dir, transforms.Compose(transforms.ToTensor()))
Try:
transforms = transforms.Compose([transforms.ToTensor()])
This will create a callable in which you can pass your data.
| https://stackoverflow.com/questions/62783857/ |
volatile was removed and now has no effect. Use with torch.no_grad(): instead | I have got this error, can you help me please?
This is my error in utils.py file
content/gdrive/My Drive/DeepFakeDetection/utils.py:21: UserWarning:
volatile was removed and now has no effect. Use with torch.no_grad():
instead. return Variable(x, volatile=volatile)
And this is my code in utils.py file
def to_var(x, volatile=False):
if torch.cuda.is_available():
x = x.cuda()
return Variable(x, volatile=volatile)
Thank you
| I changed it to this:
def to_var(x, volatile=False):
>
> with torch.no_grad():
>
> if torch.cuda.is_available():
> x = x.cuda()
> return x
| https://stackoverflow.com/questions/62784423/ |
PyTorch running out of memory: DefaultCPUAllocator can't allocate memory | I'm trying to optimize some weighs (weigts) in Pytorch but I keep getting this error:
RuntimeError: [enforce fail at CPUAllocator.cpp:64] . DefaultCPUAllocator: can't allocate memory: you tried to allocate 8000000000000 bytes. Error code 12 (Cannot allocate memory).
Namely, things blow up when I run (weights * col).sum() / weights.sum(). Weights is a tensor of size (1000000,1) and col is also a tensor of size (1000000, 1). Both tensors are decently sized, but it seems odd that I'm using up all the memory in my computer (8GB) for these operations.
| It could be that your weights and col tensors are not aligned (i.e. one of them is transposed so it is (1,1000000) instead of (1000000,1). Then when you do (weights * col) the shapes are broadcast together and it makes a tensor that is (1000000,1000000) which is probably where you are getting the extreme memory usage (as the resulting tensor is 1000000 times bigger than your original tensor).
| https://stackoverflow.com/questions/62786264/ |
GPU out of memory on evaluation : Pytorch | The model trains fine when I only train and don't validate, however it runs out of memory during evaluation, but I don't understand why this might be a problem especially since I am using torch.no_grad() any ideas?
def test(epoch,net,testloader,optimizer):
net.eval()
test_loss = 0
correct = 0
total = 0
idx = 0
features_all = []
for batch_idx, (inputs, targets) in enumerate(testloader):
with torch.no_grad():
idx = batch_idx
# inputs, targets = inputs.cpu(), targets.cpu()
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
inputs, targets = Variable(inputs), Variable(targets)
save_features, out, ce_loss = net(inputs,targets)
test_loss += ce_loss.item()
_, predicted = torch.max(out.data, 1)
total += targets.size(0)
correct += predicted.eq(targets.data).cpu().sum().item()
features_all.append((save_features, predicted, targets.data))
test_acc = 100.*correct/total
test_loss = test_loss/(idx+1)
logging.info('test, test_acc = %.4f,test_loss = %.4f' % (test_acc,test_loss))
print('test, test_acc = %.4f,test_loss = %.4f' % (test_acc,test_loss))
return features_all, test_acc
| features_all.append((save_features, predicted, targets.data))
This line is saving references to tensors in GPU memory and so the CUDA memory won't be released when loop goes to next iteration (which eventually leads to the GPU running out of memory). Move the tensors to CPU (using .cpu()) while saving them.
| https://stackoverflow.com/questions/62787874/ |
Non-intersection of two n-dimentional pytorch tensors | Thanks everyone in advance for your help! What I'm trying to do in PyTorch is to compute non-intersection ( lets call it torch.nonintersection) for tensors of many dimenstions (without for loops because I want it to be effectively performed on GPU). So here is the example how it should work:
a = torch.tensor([[ 0., 0.], [ 0., 1.], [ 0., 2.], [ 1., 0.], [ 1., 1.], [ 1., 2.], [ 1., 3.],
[ 2., 0.], [ 2., 1.], [ 2., 2.]])
b = torch.tensor([[ 2., 0.], [ 2., 1.], [ 2., 2.], [ 1., 0.], [ 1., 1.], [ 1., 2.], [ 1., 3.]])
torch.spec_unique(a,b) = torch.tensor([ 0., 0.], [ 0., 1.], [ 0., 2.])
I have analogs with for loops, but they take too much time right now. Any Ideas how it can be done? Much appreciated!
| Shape of a and b is different in your case (a is (10, 2), while b is (7, 2)), so you have to "cut" the bigger tensor to the size of the smaller one. Function below handles it with simple if (it won't slow down your computations):
def non_intersection(a, b):
if a.shape[0] > b.shape[0]:
return torch.nonzero(a[: b.shape[0]] != b, as_tuple=False)
return torch.nonzero(b[: a.shape[0]] != a, as_tuple=False)
This would return:
tensor([[0, 0],
[1, 0],
[2, 0]])
So the columns are in opposite order. If you wish to get columns just like in your example you can do this on non_intersection output:
torch.index_select(non_intersection(a, b), 1, torch.tensor([1, 0])))
| https://stackoverflow.com/questions/62790535/ |
How do i iterate over pytorch 2d tensors? | X = np.array([
[-2,4,-1],
[4,1,-1],
[1, 6, -1],
[2, 4, -1],
[6, 2, -1],
])
for epoch in range(1,epochs):
for i, x in enumerate(X):
X = torch.tensor([
[-2,4,-1],
[4,1,-1],
[1, 6, -1],
[2, 4, -1],
[6, 2, -1],
])
The looping was fine when it was an numpy array. But i want to work with pytorch tensors so what's alternative to enumerate or How can i loop through the above tensor in the 2nd line?
| enumerate expects an iterable, so it works just fine with pytorch tensors too:
X = torch.tensor([
[-2,4,-1],
[4,1,-1],
[1, 6, -1],
[2, 4, -1],
[6, 2, -1],
])
for i, x in enumerate(X):
print(x)
tensor([-2, 4, -1])
tensor([ 4, 1, -1])
tensor([ 1, 6, -1])
tensor([ 2, 4, -1])
tensor([ 6, 2, -1])
If you want to iterate over the underlying arrays:
for i, x in enumerate(X.numpy()):
print(x)
[-2 4 -1]
[ 4 1 -1]
[ 1 6 -1]
[ 2 4 -1]
[ 6 2 -1]
Do note however that pytorch's underlying data structure are numpy arrays, so you probably want to avoid looping over the tensor as you're doing, and should be looking at vectorising any operations either via pytorch or numpy.
| https://stackoverflow.com/questions/62791942/ |
What does it mean for the shape of an image tensor to be (64, 64)? Does that mean there are no channels? | I was exploring the images of the dataset : Tiny Imagenet and I found that most of the image tensors have shapes (64, 64, 3) i.e. images of height and width 64 and 64 respectively and three channels for Red, Green and Blue. But some of the image tensors in the dataset have shape (64, 64).
Does it mean that there are no channels? How is it possible?
EDIT - I downloaded this image with tensor shape (64, 64):
EDIT - Is it possible that it has one channel of some other colour space like Lab? (here b refers to the colours from blue to yellow).
| Usually, it is equivalent to (64, 64, 1) but most libraries collapse the last axis. It means you have only one channel, probably a grayscale image. Is it possible that your dataset is mixed between RGB and grayscale images?
| https://stackoverflow.com/questions/62795645/ |
How to save a model in PyTorch? | Say we have a model that we can validate like this and that Model inherits torch.nn.Module
def validate(logger, config, valid_loader, model, criterion, epoch, main_proc):
meters = AverageMeterGroup()
model.eval()
with torch.no_grad():
for step, (x, y) in enumerate(valid_loader):
x, y = x.cuda(non_blocking=True), y.cuda(non_blocking=True)
logits, _ = model(x)
loss = criterion(logits, y)
prec1, prec5 = utils.accuracy(logits, y, topk=(1, 5))
metrics = {"prec1": prec1, "prec5": prec5, "loss": loss}
metrics = utils.reduce_metrics(metrics, config.distributed)
meters.update(metrics)
if main_proc and (step % config.log_frequency == 0 or step + 1 == len(valid_loader)):
logger.info("Epoch [%d/%d] Step [%d/%d] %s", epoch + 1, config.epochs, step + 1, len(valid_loader), meters)
if main_proc:
logger.info("Train: [%d/%d] Final Prec@1 %.4f Prec@5 %.4f", epoch + 1, config.epochs, meters.prec1.avg, meters.prec5.avg)
return meters.prec1.avg, meters.prec5.avg
How to change validation procedure in order to save model after validation into file system so that it would be runnable on other data?
| with torch.no_grad():
for step, (x, y) in enumerate(valid_loader):
x, y = x.cuda(non_blocking=True), y.cuda(non_blocking=True)
logits, _ = model(x)
loss = criterion(logits, y)
prec1, prec5 = utils.accuracy(logits, y, topk=(1, 5))
metrics = {"prec1": prec1, "prec5": prec5, "loss": loss}
metrics = utils.reduce_metrics(metrics, config.distributed)
meters.update(metrics)
if main_proc and (step % config.log_frequency == 0 or step + 1 == len(valid_loader)):
logger.info("Epoch [%d/%d] Step [%d/%d] %s", epoch + 1, config.epochs, step + 1, len(valid_loader), meters)
torch.save(model,'model'+str(epoch)+'.pt')
if main_proc:
logger.info("Train: [%d/%d] Final Prec@1 %.4f Prec@5 %.4f", epoch + 1, config.epochs, meters.prec1.avg, meters.prec5.avg)
return meters.prec1.avg, meters.prec5.avg
| https://stackoverflow.com/questions/62796445/ |
Is there a PyTorch with CUDA Unified GPU-CPU Memory fork? | So Training a DNN model can be a pain when a batch of one image takes 15GB. Speed is not so important for me, yet to fit bigger batches (and models is). So I wonder if there is a PyTorch with CUDA Unified Memory fork or something like that to fit giant models (having 16gb per GPU RAM, yet 250 on CPU side it seems quite resonable)?
| If you do not care about the time it takes, but need large batches, you can use a more slow approach. Say you need to have a batch of 128 samples but your gpu memory fits only 8 samples. You can create smaller batches of 8 samples and then average their gradients.
For each small batch of 8 samples that you evaluate, you keep the .grad of each parameter in your cpu memory. You keep a list of grads for each of your models parameters. After you have gathered the grads for 16 batches of 8 samples (128 samples in total) you can average the gradients of each parameter and put the result back into the .grad attribute of each parameter.
You can then call the .step() of your optimizer. This should yield exactly the same results as if you were using a large batch of 128 samples.
| https://stackoverflow.com/questions/62799552/ |
PyTorch Lightning move tensor to correct device in validation_epoch_end | I would like to create a new tensor in a validation_epoch_end method of a LightningModule. From the official docs (page 48) it is stated that we should avoid direct .cuda() or .to(device) calls:
There are no .cuda() or .to() calls. . . Lightning does these for you.
and we are encouraged to use type_as method to transfer to the correct device.
new_x = new_x.type_as(x.type())
However, in a step validation_epoch_end I do not have any tensor to copy device from(by type_as method) in a clean way.
My question is what should I do if I want to create a new tensor in this method and transfer it to the device where is the model?
The only thing I can think of is to find a tensor in the outputs dictionary but it feels kinda messy:
avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean()
output = self(self.__test_input.type_as(avg_loss))
Is there any clean way to achieve that?
| did you check part 3.4 (page 34) in the doc you linked ?
LightningModules know what device they are on! construct tensors on the device directly to avoid CPU->Device transfer
t = tensor.rand(2, 2).cuda()# bad
(self is lightningModule)t = tensor.rand(2,2, device=self.device)# good
I had a similar issue to create tensors this helped me. I hope it will help you too.
| https://stackoverflow.com/questions/62800189/ |
How to use with torch.cuda.device() conditionally | I have some code encapsulated in a:
with torch.cuda.device(self.device):
# do a bunch of stuff
And in my __init__ I have:
self.device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu')
But I'm a little confused about how to deal with a situation where the device is cpu. Because torch.cuda.device is already explicitly for cuda. Should I just write a decorator for the function? Seems a bit overkill
| According to the documentation for torch.cuda.device
device (torch.device or int) – device index to select. It’s a no-op if this argument is a negative integer or None.
Based on that we could use something like
with torch.cuda.device(self.device if self.device.type == 'cuda' else None):
# do a bunch of stuff
which would simply be a no-op when self.device isn't a CUDA device.
| https://stackoverflow.com/questions/62801503/ |
save to csv - numpy.ndarray' object has no attribute 'append' | I'm trying to append the filenames of the images during training into a csv file, but getting an error. I can print the values okay but cannot append to csv file for some reason. Here is the full code:
File "train_filename.py", line 140, in <module>
names_preds.append() + '\n'
AttributeError: 'numpy.ndarray' object has no attribute 'append'
with open('preds_base_model_teste1016.csv','a') as fd:
#dict_writer = csv.writer(fd)
#dict_writer.writerow('Target' + '\n')
#dict_writer.writerow( ','.join(map(str, preds.detach().tolist())) + '\n')
#dict_writer.writerow('Prediction' + '\n')
#dict_writer.writerow( ','.join(map(str, targets.detach().tolist())) + '\n')
#fd.write('Target' + '\n')
fd.write(','.join(map(str, preds.detach().tolist())) + '\n')
#fd.write('Prediction' + '\n')
fd.write( ','.join(map(str, targets.detach().tolist())) + '\n')
#fd.write('Image_Name' + '\n')
np.append(paths)
#fd.write([filename])
| Use concatenate instead of append as described in the docs.
It does look like you are trying to add nothing to the array, however.
You should use it like this:
names_preds.concatenate(some_value) where the value inside concatenate is what you want to add to the array.
To save a numpy array to a csv file, there is an easier way:
numpy.savetxt("foo.csv", names_preds, delimiter=",")
See details in this answer.
Replace your line:
np.append(paths)
with
with open('preds_base_model_teste1016.csv','a') as fd:
np.savetxt(fd, names_preds, delimiter=",")
That will append all of the paths to the file you already specified.
Update:
Per your question in the comment, to put multiple arrays together so you end up with columns, you could try:
with open('preds_base_model_teste1016.csv','a') as fd:
np.savetxt(fd, list(zip(a,b,c)), delimiter=",")
where a, b, and c are the arrays you want as columns.
| https://stackoverflow.com/questions/62802342/ |
How can I install Auto-PyTorch on Windows 10 from requirements.txt? | I have been trying to install Auto-PyTorch, an automatic Neural Network tuning system (more info about installation here: https://github.com/automl/Auto-PyTorch), in a Windows 10 system. The installation steps are as follow:
$ cd install/path
$ git clone https://github.com/automl/Auto-PyTorch.git
$ cd Auto-PyTorch
$ cat requirements.txt | xargs -n 1 -L 1 pip install
$ python setup.py install
However, I can't get around the following line of code:
cat requirements.txt | xargs -n 1 -L 1 pip install
Once I get there, the following Windows PowerShell error is raised:
xargs : The term 'xargs' is not recognized as the name of a cmdlet, function, script file, or
operable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:86
+ ... read.CurrentUICulture = 'en-US'; cat requirements.txt | xargs -n 1 -L ...
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (xargs:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Note that I passed the following line of code so that the error is thrown in English (I am Spanish):
[Threading.Thread]::CurrentThread.CurrentUICulture = 'en-US'; cat requirements.txt | xargs -n 1 -L 1 pip install
I'm not an expert on PowerShell, so I would greatly appreciate your help.
Best regards!
| Since you're running on Windows PowerShell, only command-line utilities natively available on Windows can be assumed to be available - and xargs, a Unix utility, is not among them.
(While git also isn't natively available, it looks like you've already installed it).
Here's a translation of your code into native PowerShell code (note that cd is a built-in alias for Set-Location, and, on Windows only, cat is a built-in alias for Get-Content; % is a built-in alias for the ForEach-Object cmdlet):
Set-Location install/path
git clone https://github.com/automl/Auto-PyTorch.git
Set-Location Auto-PyTorch
Get-Content requirements.txt | % { pip install $_ }
python setup.py install
| https://stackoverflow.com/questions/62804230/ |
pytorch KLDivLoss loss is negative | my target is training a span prediction model
which can predict the position in the BERT output sequence
my input's shape is (batch_size, max_sequence_len(512),embedding_size(768))
output's shape will be (batch_size , max_sequence_len , 1) and the third dim is stand for kind a probability , then I will reshape output to (batch_size,max_sequence_len)
my label's shape is (batch_size , max_sequence_len), and in the max_sequence_len(512), only one position will be 1 and the others will be zero
and I've already check this
(batch_size is 2)
start_pos_labels.sum(dim=1)
output >>
tensor([1.0000, 1.0000], device='cuda:0', dtype=torch.float64)
start_pred.sum(dim=1)
tensor([1., 1.], device='cuda:0', dtype=torch.float64, grad_fn=<SumBackward1>)
but when I use nn.KLDivLoss() , output still be negative, I really dont know why
can somebody help me? thanks!
Here is my code
Model Code
class posClassfication_new(nn.Module):
def __init__(self):
super(posClassfication_new, self).__init__()
self.start_task = nn.Sequential(
nn.Linear(768, 1),
# nn.ReLU(),
# nn.Linear(256, 128),
# nn.ReLU(),
# nn.Linear(128, 1)
)
self.end_task = nn.Sequential(
nn.Linear(768, 1),
# nn.ReLU(),
# nn.Linear(256, 128),
# nn.ReLU(),
# nn.Linear(128, 1)
)
#
def forward(self, start_x,end_x):
start_x = start_x.double()
end_x = end_x.double()
start_out = self.start_task(start_x)
end_out = self.end_task(end_x)
return start_out,end_out
training code
BATCH_SIZE = 8
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("device:", device)
class PosTrainDataset(Dataset):
def __init__(self, x, start_y,end_y):
self.x = x
self.start_y = start_y
self.end_y = end_y
def __getitem__(self,idx):
x = self.x[idx]
start_y = self.start_y[idx]
end_y = self.end_y[idx]
return x, start_y, end_y
def __len__(self):
return len(self.x)
trainset = PosTrainDataset(pos_train_x , start_pos_labels_train , end_pos_labels_train)
trainloader = DataLoader(trainset, batch_size=BATCH_SIZE)
pos_model = posClassfication_new()
pos_model = pos_model.to(device)
pos_model = pos_model.double()
pos_model.train()
pos_loss = nn.KLDivLoss()
# pos_loss = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(pos_model.parameters(), lr=1e-5)
EPOCHS = 5
for epoch in range(EPOCHS):
running_loss = 0.0
for data in trainloader:
x, start_pos_labels, end_pos_labels = [t.to(device) for t in data]
mini_batch = x.size()[0]
optimizer.zero_grad()
start_pred , end_pred = pos_model(x,x)
start_pred = start_pred.reshape((mini_batch,512))
end_pred = end_pred.reshape((mini_batch,512))
start_pred = torch.nn.functional.softmax(start_pred,dim=1)
end_pred = torch.nn.functional.softmax(end_pred,dim=1)
start_pos_labels = start_pos_labels + 0.0001
start_pos_labels = torch.nn.functional.softmax(start_pos_labels,dim=1)
end_pos_labels = end_pos_labels + 0.0001
end_pos_labels = torch.nn.functional.softmax(end_pos_labels,dim=1)
# start_pos_labels = torch.argmax(start_pos_labels,dim=1)
# end_pos_labels = torch.argmax(end_pos_labels,dim=1)
start_loss = pos_loss(start_pred,start_pos_labels)
end_loss = pos_loss(end_pred,end_pos_labels)
loss = start_loss + end_loss
loss.backward()
optimizer.step()
running_loss += loss.item()
torch.save(pos_model,'pos_model_single_task.pkl')
print('[epoch %d] loss: %.3f' %(epoch + 1, running_loss))
| nn.KLDivLoss expects the input to be log-probabilties.
From the documentation:
As with NLLLoss, the input given is expected to contain log-probabilities and is not restricted to a 2D Tensor. The targets are given as probabilities (i.e. without taking the logarithm).
You can apply nn.functional.log_softmax to your predictions to get log-probabilities.
start_pred = torch.nn.functional.log_softmax(start_pred,dim=1)
end_pred = torch.nn.functional.log_softmax(end_pred,dim=1)
| https://stackoverflow.com/questions/62806681/ |
Extract tensor from string | Is it possible to extract directly the tensor included in this string tensor([-1.6975e+00, 1.7556e-02, -2.4441e+00, -2.3994e+00, -6.2069e-01])? I'm looking for some tensorflow or pytorch function that can do it, like the ast.literal_eval function does for dictionaries and lists.
If not, could you provide a pythonic method, please?
I'm thinking about something like this:
tensor_list = "tensor([-1.6975e+00, 1.7556e-02, -2.4441e+00, -2.3994e+00, -6.2069e-01])"
str_list = tensor_list.replace("tensor(", "").replace(")", "")
l = ast.literal_eval(str_list)
torch.from_numpy(np.array(l))
But I'm not sure this is the best way.
| You can use eval:
import torch.tensor as tensor
eval(tensor_list)
>>> tensor([-1.6975, 0.0176, -2.4441, -2.3994, -0.6207])
| https://stackoverflow.com/questions/62814427/ |
How do I use torchaudio with torch_xla on google colab TPU? | I was using google colab (GPU enabled) to train my Automatic Speech Recognition Model based on pytorch and torchaudio. But when I tried to use google colab TPU I got the following error when training my model :
ImportError: /usr/local/lib/python3.6/dist-packages/_torch_sox.cpython-36m-x86_64-linux-gnu.so: undefined symbol: _ZN6caffe28TypeMeta21_typeMetaDataInstanceISt7complexIfEEEPKNS_6detail12TypeMetaDataEv site:stackoverflow.com
I'm almost sure it's a conflict between torchaudio and pytorch_xla versions
Here's the code that I use to install the librairies :
VERSION = "nightly" #@param ["1.5" , "20200325", "nightly"]
!curl https://raw.githubusercontent.com/pytorch/xla/master/contrib/scripts/env-setup.py -o pytorch-xla-env-setup.py
!pip install torchvision==0.6.1
!pip install torch==1.5.1
!pip install torchaudio==0.5.1
!python pytorch-xla-env-setup.py --version $VERSION
The solution proposed here https://stackoverflow.com/a/60929133/13847989 generated the following error :
ImportError: /usr/local/lib/python3.6/dist-packages/_torch_sox.cpython-36m-x86_64-linux-gnu.so: undefined symbol: THPVariableClass
What am I doing wrong ?
| Can you try installing torchaudio from source after running the setup script (https://github.com/pytorch/audio#from-source)? Sounds like its due to a version mismatch (nightly torch vs stable torchaudio).
| https://stackoverflow.com/questions/62815065/ |
How to access individual data points of MNIST data and check their size, shape etc from trainset object using torchvision's import dataset | the following code is
from torchvision import datasets, transforms
trainset = datasets.MNIST('./data/', download=True, train=True, transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))]))
I would like to visualize the first data point in the trainset variable above.
I want to have a look at the pixel values of the first data point by doing something like print(trainset[0]) or check the size by doing print(trainset[0].size) or check the shape by doing print(trainset[0].shape) etc.
| For shape:
trainset.data.shape
torch.Size([60000, 28, 28])
For the first example:
trainset.data[0]
tensor([[[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]]], dtype=torch.uint8)
| https://stackoverflow.com/questions/62819226/ |
OSError: [E050] Can't find model 'de'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data directory | So I am trying to make a seq to seq model for translating german to english using pytorch on online notebook like kaggle notebook and google colab
import torch
import torch.nn as nn
import torch.optim as optim
from torchtext.datasets import Multi30k
from torchtext.data import Field, BucketIterator
import numpy as np
import spacy
import random
from torch.utils.tensorboard import SummaryWriter # to print to tensorboard
Libraries imported, when i load dataset using the function with spacy, as below,
spacy_ger = spacy.load("de")
spacy_eng = spacy.load("en")
This error comes. :
OSError: [E050] Can't find model 'de'. It doesn't seem to be a shortcut link, a Python package or a valid path to a data directory.
Everywhere, an explanation is given for 'en', but not for 'de'. If anyone could help with this.
Specification:
Package : Version
Spacy : 2.3.1
pytorch-crf : 0.7.0
torch : 1.5.1
torchnlp : 0.0.0.1
torchtext : 0.4.0
torchvision : 0.6.1
jupyter-tensorboard : 0.2.0
tensorboard : 2.2.2
tensorboard-plugin-wit : 1.7.0
Thanks in advance for helping.
| so after whole one month, trying on other things and exploring issues and questions related to this topic, I found a way to do so,
import spacy.cli
spacy.cli.download("en_core_web_md")
With this method, you can use and import any spacy model, whether medium-sized or larger size datasets also, which always gives an error if you try to import the dataset using
spacy.load because it is not effective for loading datasets other then sm or smallest size datasets in Google colab or Kaggle notebook or any other online notebook.
| https://stackoverflow.com/questions/62822737/ |
How to handle transforms.FiveCrop change in tensor size | I am trying to add transforms.FiveCrop to my model. I understand that this method of data augmentation adds dimensions to my tensor but I am not sure how to handle it. The documentation notes:
This transform returns a tuple of images and there may be a mismatch in the number of inputs and targets your Dataset returns. See below for an example of how to deal with this.
Example
>>> transform = Compose([
>>> FiveCrop(size), # this is a list of PIL Images
>>> Lambda(lambda crops: torch.stack([ToTensor()(crop) for crop in crops])) # returns a 4D tensor
>>> ])
>>> #In your test loop you can do the following:
>>> input, target = batch # input is a 5d tensor, target is 2d
>>> bs, ncrops, c, h, w = input.size()
>>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
>>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops
...But I am not sure how to implement this.
Train loop:
for batch_idx, (data, target) in enumerate(train_loader):
print(f'Data: {data.shape}, Target: {target.shape}')
# Before Fivecrop: Data: torch.Size([32, 3, 224, 224]), Target: torch.Size([32])
# After Fivecrop: Data: torch.Size([32, 5, 3, 224, 224]), Target: torch.Size([32])
indx_target = target.clone()
data = data.to(train_config.device)
target = target.to(train_config.device)
optimizer.zero_grad()
output = model(data)
loss = F.cross_entropy(output, target)
loss.backward()
optimizer.step()
Can someone help explain how this is implemented in my train loop and what I am not understanding?
Thanks
| This makes sense now. Here is for anyone who needs assistance. The new code looks as such:
for batch_idx, (data, target) in enumerate(train_loader):
bs, ncrops, c, h, w = data.size()
print(f'Data: {data.view(-1, c, h, w).shape}, Target: {target.shape}')
indx_target = target.clone()
data = data.to(train_config.device)
target = target.to(train_config.device)
optimizer.zero_grad()
output = model(data.view(-1, c, h, w)) # fuse batch size and ncrops
output_avg = output.view(bs, ncrops, -1).mean(1) # average the output over fivecrops
loss = F.cross_entropy(output_avg, target)
loss.backward()
optimizer.step()
batch_loss = np.append(batch_loss, [loss.item()])
prob = F.softmax(output_avg, dim=1)
pred = prob.data.max(dim=1)[1]
correct = pred.cpu().eq(indx_target).sum()
accuracy = float(correct) / float(len(data))
batch_acc = np.append(batch_acc, [accuracy])
| https://stackoverflow.com/questions/62827282/ |
matplotlib - segmentation fault (core dumped) while trying to plot a grid | I'm trying to plot a grid but exists with the error message -
(feature_vis.py:27730): Gdk-WARNING **: 03:23:47.745: Native Windows wider or taller than 32767 pixels are not supported
Segmentation fault (core dumped)
model_weights = './Mutual-Channel-Loss-master/model_info_best.pth'
model_features = './Mutual-Channel-Loss-master/features_best_new.pth'
weights = torch.load(model_weights, map_location = torch.device('cpu'))
features = torch.load(model_features, map_location = torch.device('cpu'))
activations = features['features']
feature_map = activations[0][0][3]
# feature_maps = np.load(path, allow_pickle = True)
# test = feature_maps[0][0][0]
fig = plt.figure(figsize = (300, 500))
grid = ImageGrid(fig, 111, # similar to subplot(111)
nrows_ncols=(20, 30), # creates 2x2 grid of axes
axes_pad=0.1, # pad between axes in inch.
)
for ax, im in zip(grid, feature_map):
# Iterating over the grid returns the Axes.
im = im.to('cpu').numpy()
ax.imshow(im, cmap = 'gray')
plt.savefig('test.png', ppi = 300)
How should I fix / Debug this?
I am using python 3.6.9 and on ubuntu 18.04
| The unit used by the attribute figsize is the inch. So an image of size 300x500 with dpi=300 is insanely huge (45M pixels) and mpl cannot handle that. If you want a 300 by 500 (pixels) image you have to first convert it to inches. In this case it would be something like ~1x1.7.
| https://stackoverflow.com/questions/62829316/ |
No Parameters in Net class even after inheriting from nn.Module | For some reason, my Class Net has no parameters, even though i have imported everything correctly., its still showing that net has no parameters or attributes and even on printing net its just prints empty list. Can anyone tell me what's wrong ?
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def ___init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(784, 64)
self.fc2 = nn.Parameter(nn.Linear(64, 64))
self.fc3 = nn.Parameter(nn.Linear(64, 64))
self.fc4 = nn.Parameter(nn.Linear(64, 10))
def forward(self, x):
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = F.relu(self.fc3(x))
x = self.fc4(x)
return F.log_softmax(x, dim=1)
net = Net()
print(net)
print(list(net.parameters()))
Output:
Net()
[]
| In the code
def ___init__(self):
you're using three underscores before init, use two: __init__.
| https://stackoverflow.com/questions/62830524/ |
Cnn model using pytorch | I have images and labels. I divided them into test and train sets.
(xtrain,
ytrain,
xtest,
ytest).
x refers to images and y refers to label.
How to use these sets in the following train model
**# Train the model
total_step = len(train_loader)
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
images = images.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 (i+1) % 100 == 0:
print ('Epoch [{}/{}], Step [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, i+1, total_step, loss.item()))
# Test the model
model.eval() # eval mode (batchnorm uses moving mean/variance instead of mini-batch
mean/variance)**
| from torch.utils.data import Dataset, DataLoader
training_set = Dataset(xtrain, ytrain)
test_set = Dataset(xtest, ytest)
params = {'batch_size': 64,
'shuffle': True}
train_loader = DataLoader(training_set, **params)
| https://stackoverflow.com/questions/62833157/ |
PyTorch: 'ToTensor()' turns color image into 9 grayscale pictures | I have found that when I use 'ToTensor' to a images, one image becomes 9 displayed.I checked the official documents but couldn't find the reason. so why a picture become 9 pictures???questioon as the following figure.
a = plt.imread('test.jpg')
plt.imshow(a)
plt.show()
transform = transforms.Compose([transforms.ToTensor()])
b = transform(a)
b = b.view(375,500,3)
plt.imshow(b)
| When you use transforms.ToTensor(), by default it changes the input arrays from HWC to CHW order. For plotting, you'll need to push back the channels to the last dimension.
plt.imshow(b.permute(2, 0, 1))
| https://stackoverflow.com/questions/62833204/ |
Tensor(1.0).item() vs float(Tensor(1.0)) | If x is a torch.Tensor of dtype torch.float then are the operations x.item() and float(x) exactly the same?
| The operations x.item() and float(x) are not the same.
From the documentation of item(), it can be used to get the value of tensor as a Python number(only from tensors containing a single value). It basically returns the value of the tensor as it is. It does not make any modifications to the tensor.
Where as float() is for converting its input to a floating point number, when possible. Find the documentation here.
To see the difference, consider another Tensor y of dtype int64:
import torch
y = torch.tensor(2)
print(y, y.dtype)
>>> tensor(2) torch.int64
print('y.item(): {}, float(y): {}'.format(y.item(), float(y)))
>>> y.item(): 2, float(y): 2.0
print(type(y.item()), type(float(y)))
>>> <class 'int'> <class 'float'>
Note that float(y) does not convert the type in-place. You would need to assign it in case you need that change. Like:
z = float(y)
print('y.dtype: {}, type(z): {}'.format(y.dtype, type(z)))
>>> y.dtype: torch.int64, type(z): <class 'float'>
We can see that z is not a torch.Tensor. It is simply a floating point number.
The float() operation is not to be confused with self.float(). This operation performs the Tensor dtype conversion (not in-place, needs assignment).
print('y.float(): {},\n y.float().dtype: {},\n y: {},\n y.dtype'.format(y.float(), y.float().dtype, y, y.dtype))
y.float(): 2.0,
y.float().dtype: torch.float32,
y: 2,
y.dtype: torch.int64
| https://stackoverflow.com/questions/62833711/ |
How to convert a ByteTensor into an image tensor? | I am converting images into binary files via matlab and try to load the binary matlab vectors (1d) into python and convert them into ByteTensors:
img = np.fromfile(dir_train + image_name)
img = torch.ByteTensor(img)
This works fine. The ByteTensors are of the dimension 2. Afterwards I would like to convert them back into into images, like reshaping them, because the neural network (resnet18) needs 4-dimensional tensors. What is the best way to do that?
At the moment my network needs tensors of the dimension [64, 3, 7, 7], but the ByteTensors are [8, 1914].
| I solved it this way:
img = np.fromfile(dir_train + image_name, 'bool') # read in the binary file
img = img.reshape(1, 350, 350) # reshape binary file
img = torch.ByteTensor(img) # convert to ByteTensor
img = img.type(torch.FloatTensor) # convert to FloatTensor
I think there is no better way than typecasting the ByteTensor. On top of that I changed the first convolutional layer of my network architecture (resnet18) in order to make sure, the input expected input matches the convertet binary input.
resnet18.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
| https://stackoverflow.com/questions/62835258/ |
Subsets and Splits