instruction
stringlengths 13
150
| input
stringlengths 36
29.1k
| output
stringlengths 31
29.5k
| source
stringlengths 45
45
|
---|---|---|---|
Unable to build vocab for a torchtext text classification | I'm trying to prepare a custom dataset loaded from a csv file in order to use in a torchtext text binary classification problem. It's a basic dataset with news headlines and a market sentiment label assigned "positive" or "negative". I've been following some online tutorials on PyTorch to get this far but they've made some significant changes in the latest torchtext package so most of the stuff is out of date.
Below I've successfully parsed my csv file into a pandas dataframe with two columns - text headline and a label which is either 0 or 1 for positive/negative, split into a training and test dataset then wrapped them as a PyTorch dataset class:
train, test = train_test_split(eurusd_df, test_size=0.2)
class CustomTextDataset(Dataset):
def __init__(self, text, labels):
self.text = text
self.labels = labels
def __getitem__(self, idx):
label = self.labels.iloc[idx]
text = self.text.iloc[idx]
sample = {"Label": label, "Text": text}
return sample
def __len__(self):
return len(self.labels)
train_dataset = CustomTextDataset(train['Text'], train['Labels'])
test_dataset = CustomTextDataset(test['Text'], test['Labels'])
I'm now trying to build a vocabulary of tokens following this tutorial https://coderzcolumn.com/tutorials/artificial-intelligence/pytorch-simple-guide-to-text-classification and the official pytorch tutorial https://pytorch.org/tutorials/beginner/text_sentiment_ngrams_tutorial.html .
However using the below code
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
tokenizer = get_tokenizer('basic_english')
train_iter = train_dataset
def yield_tokens(data_iter):
for _, text in data_iter:
yield tokenizer(text)
vocab = build_vocab_from_iterator(yield_tokens(train_iter), specials=["<unk>"])
vocab.set_default_index(vocab["<unk>"])
yields a very small length of vocabulary, and applying the example vocab(['here', 'is', 'an', 'example']) on a text field taken from the original dataframe yields a list of 0s, implying the vocab is being built from the label field, containing only 0s and 1s, not the text field. Could anyone review and show me how to build the vocab targeting the text field?
| The very small length of vocabulary is because under the hood, build_vocab_from_iterator uses a Counter from the Collections standard library, and more specifically its update function. This function is used in a way that assumes that what you are passing to build_vocab_from_iterator is an iterable wrapping an iterable containing words/tokens.
This means that in its current state, because strings can be iterated upon, your code will create a vocab able to encode all letters, not words, comprising your dataset, hence the very small vocab size.
I do not know if that is intended by Python/Pytorch devs, but because of this you need to wrap your simple iterator in a list, for example like this :
vocab = build_vocab_from_iterator([yield_tokens(train_iter)], specials=["<unk>"])
Note : If your vocab gives only zeros, it is not because it is taking from the label field, it is just returning the integer corresponding to an unknown token, since all words that are not just a character will be unknown to it.
Hope this helps!
| https://stackoverflow.com/questions/73177807/ |
Mnist model performing very badly on custom data | I have used the resnet50 prebuilt and pretrained model from pytorch, on the MNIST dataset,
from torch import nn
from torchvision.models import ResNet50_Weights, resnet50
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.model = resnet50(weights=ResNet50_Weights.DEFAULT)
self.model.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
num_ftrs = self.model.fc.in_features
self.model.fc = nn.Linear(num_ftrs, 10)
def forward(self, x):
return self.model(x)
it performs very well and after training for 10 epochs it has achieved an incredible 99.895% accuracy on the 50,000 test images.
model.eval()
with torch.no_grad():
correct = 0
total = 0
for images, labels in train_loader:
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the {} train images: {} %'.format(50000, 100 * correct / total))
[out]: Accuracy of the network on the 50000 train images: 99.895 %
I have used pygame to easily create my own numbers to input to the model. I start off with a very basic program just placing circles while the left mouse button is held, then I save the generated image into a png format.
if event.type == pg.MOUSEMOTION:
if (drawing):
mouse_position = pg.mouse.get_pos()
pg.draw.circle(screen, color, mouse_position, w)
elif event.type == pg.MOUSEBUTTONUP:
mouse_position = (0, 0)
drawing = False
last_pos = None
elif event.type == pg.MOUSEBUTTONDOWN:
drawing = True
I convert the image to grayscale and scale it down to 28x28 and into a tensor using PIL and torch.PILToTensor().
image = Image.open("image.png").convert("L").resize((28,28),Image.Resampling.LANCZOS)
transform = Compose([
PILToTensor(),
Lambda(lambda image: image.view(-1, 1, 28, 28))
])
img_tensor = transform(image).to(torch.float)
Then I feed this image to the network. I get no errors or anything the model just predicts really badly. For example when I gave it this
image of a 2
this code outputed:
with torch.no_grad():
outputs = model(img_tensor)
print(outputs)
_, predicted = torch.max(outputs.data, 1)
print(predicted)
[out]: tensor([[ 20.6237, 0.4952, -15.5033, 8.5165, 1.0938, 2.8278, 2.0153,
3.2825, -6.2655, -0.6992]])
tensor([0])
The sureness is outputted as list with the sureness for each class 0, 1, 2, 3... so as you can see the sureness for "2" is actually negative, does anyone know why this could be and how I could solve it?
Thank you very much
| I have solved this, the problem was that when I converted the image to a tensor it had values from 0-255 instead of 0-1, that's why the model was behaving so unpredictably.
| https://stackoverflow.com/questions/73177931/ |
How can I use DataGenerator with my model training? | I am having a bit of trouble trying to use DataGenerator class with my model training during the model.fit() function. The reason I am using the DataGenerator is to help with dealing with my large amount of images and labels for my object detection task.
All of my images are split into train, test and validation sets. I have converted the images and my labels to a numpy array and then preprocessed accordingly for my RESNET50 model, which works fine.
val_images = np.array(val_images)
train_images = np.array(train_images)
However, when I try to use the DataGenerator function for my val and training images, it does not seem to work.
training_generator = DataGenerator(train_images, train_targets)
validation_generator = DataGenerator(val_images, val_targets)
I tried to use the model.fit() function but it does not work and ends up showing an error.
resnet_model = model.fit_generator(
training_generator,
epochs=4,
validation_data=validation_generator)
TypeError: expected str, bytes or os.PathLike object, not ndarray
Full traceback:
https://www.toptal.com/developers/hastebin/gusicucali.yaml
I am not sure if this is the right way to use the DataGenerator class as I am quite new with it. I have 6000+ images with labels (xmin,ymin,ymax,xmax) accordingly.
The reason why I am trying to use it is to help make my model training a bit more efficient since I do not have a GPU.
| I think you should aim at having a code similar to this below. I used ImageDataGenerator. If you have a look at the documentation it lets you pick lots of arguments to get a data augmentation of your images. I copied only a few.
val_images = np.array(val_images)
train_images = np.array(train_images)
dataGenerator = ImageDataGenerator(rotation_range=0,
zoom_range=0,
width_shift_range=0,
height_shift_range=0,
horizontal_flip=False,
fill_mode="nearest")
# train
model = model.fit_generator(dataGenerator.flow(train_images, train_targets, batch_size=BATCH_SIZE),
validation_data=(val_images, val_targets),
steps_per_epoch=len(train_images),
epochs=EPOCHS)
This should work. Also I think that recently fit_generator has been deprecated, but you could substitute it with fit without changing anything.
| https://stackoverflow.com/questions/73179850/ |
How to make pytorch lightning module have injected, nested models? | I have some nets, such as the following (augmented) resnet18:
num_classes = 10
resnet = models.resnet18(pretrained=True)
for param in resnet.parameters():
param.requires_grad = True
num_ftrs = resnet.fc.in_features
resnet.fc = nn.Linear(num_ftrs, num_classes)
And I want to use them inside a lightning module, and have it handle all optimizations, to_device, stages and so on. In other words, I want to register those modules for my lightning module.
I also want to be able to access their public members.
class MyLightning(LightningModule):
def __init__(self, resnet):
super().__init__()
self._resnet = resnet
self._criterion = lambda x: 1.0
def forward(self, x):
resnet_out = self._resnet(x)
loss = self._criterion(resnet_out)
return loss
my_lightning = MyLightning(resnet)
The above doesn't optimize any parameters.
Trying
def __init__(self, resnet)
...
_layers = list(resnet.children())[:-1]
self._resnet = nn.Sequential(*_layers)
Doesn't take resnet.fc into account. This also doesn't make sense to be the intended way of nesting models inside pytorch lightning.
How to nest models in pytorch lightning, and have them fully accessible and handled by the framework?
| The training loop and optimization process is handles by the Trainer class. You can do so by initializing a new instance:
>>> trainer = Trainer()
And wrapping your PyTorch Lightning module with it. This way you can perform fitting, tuning, validating, and testing on that instance provided a DataLoader or LightningDataModule:
>>> trainer.fit(my_lightning, train_dataloader, val_dataloader)
You will have to implement the following functions on your Lightning module (i.e. in your case MyLightning):
Name
Description
init
Define computations here
forward
Use for inference only (separate from training_step)
training_step
the complete training loop
validation_step
the complete validation loop
test_step
the complete test loop
predict_step
the complete prediction loop
configure_optimizers
define optimizers and LR schedulers
source LightningModule documentation page.
Keep in mind a LightningModule is a nn.Module, so whenever you define a nn.Module as attribute to a LightningModule in the __init__ function, this module will end being registered as a sub-module to the parent pytorch lightning module.
| https://stackoverflow.com/questions/73182429/ |
Loss key needs to be present Pytorch | I am following this repo:
https://github.com/NVIDIA/NeMo/tree/main/examples/nlp/entity_linking
Here is a small tutorial:
https://colab.research.google.com/github/NVIDIA/NeMo/blob/v1.0.2/tutorials/nlp/Entity_Linking_Medical.ipynb
Before starting this tutorial change branch to r1.10.0
When I train this model on entire UMLS dataset given the commands it gives the following error:
In automatic_optimization, when `training_step` returns a dict, the 'loss' key needs to be present
I checked the training steps method and it is fine:
def training_step(self, batch, batch_idx):
"""
Lightning calls this inside the training loop with the data from the training dataloader
passed in as `batch`.
"""
input_ids, token_type_ids, attention_mask, concept_ids = batch
logits = self.forward(input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask)
train_loss = self.loss(logits=logits, labels=concept_ids)
# No hard examples found in batch,
# shouldn't use this batch to update model weights
if train_loss == 0:
train_loss = None
lr = None
else:
lr = self._optimizer.param_groups[0]["lr"]
self.log("train_loss", train_loss)
self.log("lr", lr, prog_bar=True)
return {"loss": train_loss, "lr": lr}
Here is a full stacktrace:
[NeMo I 2022-07-29 18:29:27 multi_similarity_loss:91] Encountered zero loss in multisimloss, loss = 0.0. No hard examples found in the batch
Error executing job with overrides: ['project_dir=.']
Traceback (most recent call last):
File "self_alignment_pretraining.py", line 38, in main
trainer.fit(model)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 769, in fit
self._fit_impl, model, train_dataloaders, val_dataloaders, datamodule, ckpt_path
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 719, in _call_and_handle_interrupt
return self.strategy.launcher.launch(trainer_fn, *args, trainer=self, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/strategies/launchers/subprocess_script.py", line 93, in launch
return function(*args, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 809, in _fit_impl
results = self._run(model, ckpt_path=self.ckpt_path)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 1234, in _run
results = self._run_stage()
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 1321, in _run_stage
return self._run_train()
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 1351, in _run_train
self.fit_loop.run()
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/base.py", line 204, in run
self.advance(*args, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/fit_loop.py", line 268, in advance
self._outputs = self.epoch_loop.run(self._data_fetcher)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/base.py", line 204, in run
self.advance(*args, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/epoch/training_epoch_loop.py", line 208, in advance
batch_output = self.batch_loop.run(batch, batch_idx)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/base.py", line 204, in run
self.advance(*args, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/batch/training_batch_loop.py", line 88, in advance
outputs = self.optimizer_loop.run(split_batch, optimizers, batch_idx)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/base.py", line 204, in run
self.advance(*args, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/optimization/optimizer_loop.py", line 207, in advance
self.optimizer_idx,
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/optimization/optimizer_loop.py", line 256, in _run_optimization
self._optimizer_step(optimizer, opt_idx, batch_idx, closure)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/optimization/optimizer_loop.py", line 378, in _optimizer_step
using_lbfgs=is_lbfgs,
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/trainer/trainer.py", line 1593, in _call_lightning_module_hook
output = fn(*args, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/core/lightning.py", line 1644, in optimizer_step
optimizer.step(closure=optimizer_closure)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/core/optimizer.py", line 168, in step
step_output = self._strategy.optimizer_step(self._optimizer, self._optimizer_idx, closure, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/strategies/ddp.py", line 278, in optimizer_step
optimizer_output = super().optimizer_step(optimizer, opt_idx, closure, model, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/strategies/strategy.py", line 193, in optimizer_step
return self.precision_plugin.optimizer_step(model, optimizer, opt_idx, closure, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/plugins/precision/native_amp.py", line 85, in optimizer_step
closure_result = closure()
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/optimization/optimizer_loop.py", line 148, in __call__
self._result = self.closure(*args, **kwargs)
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/optimization/optimizer_loop.py", line 134, in closure
step_output = self._step_fn()
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/optimization/optimizer_loop.py", line 437, in _training_step
training_step_output, self.trainer.accumulate_grad_batches
File "/home/umair/miniconda3/envs/aemap/lib/python3.7/site-packages/pytorch_lightning/loops/optimization/optimizer_loop.py", line 75, in from_training_step_output
"In automatic_optimization, when `training_step` returns a dict, the 'loss' key needs to be present"
pytorch_lightning.utilities.exceptions.MisconfigurationException: In automatic_optimization, when `training_step` returns a dict, the 'loss' key needs to be present
Set the environment variable HYDRA_FULL_ERROR=1 for a complete stack trace.
| You get this error message about "loss key needs to be present" because in some training steps you return the dict {"loss": None}. This happens in your code here
if train_loss == 0:
train_loss = None
lr = None
where you set train_loss = None. Lightning does not like that, because it wants loss to be a tensor with a graph attached.
If you wish to skip the optimization step completely, just return None from the training_step method, like this:
if train_loss == 0:
return None
| https://stackoverflow.com/questions/73183689/ |
Rearrange a 5D tensor in PyTorch | I have a 5D tensor in the shape of (N,C,T,H,W). I want to rearrange it using PyTorch to the form of (N,T,HW,C). How can I do that?
| Naturally you can reshape the last two dimensions of your tensor by flattening your tensor from dim=-2, this will produce a shape of (N,C,T,HW):
>>> x.flatten(-2)
Then you can permute the dimensions around:
>>> x.flatten(-2).permute(0,2,3,1)
| https://stackoverflow.com/questions/73184848/ |
Shuffling two 2D tensors in PyTorch and maintaining same order correlation | Is it possible to shuffle two 2D tensors in PyTorch by their rows, but maintain the same order for both? I know you can shuffle a 2D tensor by rows with the following code:
a=a[torch.randperm(a.size()[0])]
To elaborate:
If I had 2 tensors
a = torch.tensor([[1, 1, 1, 1, 1],
[2, 2, 2, 2, 2],
[3, 3, 3, 3, 3]])
b = torch.tensor([[4, 4, 4, 4, 4],
[5, 5, 5, 5, 5],
[6, 6, 6, 6, 6]])
And ran them through some function/block of code to shuffle randomly but maintain correlation and produce something like the following
a = torch.tensor([[2, 2, 2, 2, 2],
[1, 1, 1, 1, 1],
[3, 3, 3, 3, 3]])
b = torch.tensor([[5, 5, 5, 5, 5],
[4, 4, 4, 4, 4],
[6, 6, 6, 6, 6]])
My current solution is converting to a list, using the random.shuffle() function like below.
a_list = a.tolist()
b_list = b.tolist()
temp_list = list(zip(a_list , b_list ))
random.shuffle(temp_list) # Shuffle
a_temp, b_temp = zip(*temp_list)
a_list, b_list = list(a_temp), list(b_temp)
# Convert back to tensors
a = torch.tensor(a_list)
b = torch.tensor(b_list)
This takes quite a while and was wondering if there is a better way.
| You mean
indices = torch.randperm(a.size()[0])
a=a[indices]
b=b[indices]
?
| https://stackoverflow.com/questions/73187905/ |
Applying torch.combinations on multidimensional tensor or tuple of tensors in PyTorch? | Using PyTorch, torch.combinations will only take a 1D tensor as input but I would like to apply it to each 1D tensor in a multidimensional tensor.
inp = torch.tensor([[1, 2, 3],
[2, 3, 4]])
torch.combinations((inp), r=2)
The result is an error saying I can't apply it to that shape but I want to apply it to [1, 2, 3] and [2, 3, 4] individually. I can't do it one by one because the idea is to apply this to large sets of data.
inp = torch.tensor([[1,2,3],[2,3,4]])
inp_tuple = torch.unbind(inp)
print(inp_tuple)
(tensor([1, 2, 3]), tensor([2, 3, 4]))
torch.combinations((inp_tuple), r=2)
I also tried unbinding the tensor and applying it to the tuple of tensors but it gives an error saying it can't be applied to a tuple.
Is there any way that I can get torch.combinations to automatically apply to each individual 1D tensor in a multidimensional tensor or each tensor in a tuple of tensors? If not are there any alternatives to achieve all combinations of each individual part of a multidimensional tensor?
| Function torch.combinations returns all possible combinations of size r of the elements contained in the 1D input vector. The reason why multi-dimensional inputs are not supported is probably that you have no guarantee that the different vectors in your input have the exact same number of unique elements. Obviously if one of the vectors has a duplicate element then you would end up with one set of combinations bigger than another which is simply not possible to represent with a homogenous PyTorch tensor.
So from there on, I will assume that the input tensor inp is a 2D tensor shaped (N, C) where each of its N vectors contains C unique elements. The example you gave would fit to this requirement since both vectors have three unique elements each: {1, 2, 3} and {2, 3, 4}.
>>> inp = torch.tensor([[1,2,3],[2,3,4]])
The idea is to apply torch.combinations on an arrangement tensor of length equal to that of our vectors. We can then use those as indices to gather values in our different vectors in our input tensor.
We can retrieve all combinations of an arrangement with the following:
>>> c = torch.combinations(torch.arange(inp.size(1)), r=2)
tensor([[0, 1],
[0, 2],
[1, 2]])
Then we need to reshape and expand both inp and c such that they match in number of dimensions:
>>> x = inp[:,None].expand(-1,len(c),-1)
tensor([[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]],
[[2, 3, 4],
[2, 3, 4],
[2, 3, 4]]])
>>> idx = c[None].expand(len(x), -1, -1)
tensor([[[0, 1],
[0, 2],
[1, 2]],
[[0, 1],
[0, 2],
[1, 2]]])
Finally we can apply torch.gather on x and idx on dim=2. This will return a 3D tensor out such that:
out[i][j][k] = x[i][j][index[i][j][k]]
Let's make our call on torch.gather:
>>> x.gather(dim=2, index=idx)
tensor([[[1, 2],
[1, 3],
[2, 3]],
[[2, 3],
[2, 4],
[3, 4]]])
Which is the desired result.
| https://stackoverflow.com/questions/73187923/ |
Inner workings of pytorch autograd.grad for inner derivatives | Consider the following code:
x = torch.tensor(2.0, requires_grad=True)
y = torch.square(x)
grad = autograd.grad(y, x)
x = x + grad[0]
y = torch.square(x)
grad2 = autograd.grad(y, x)
First, we have that β(x^2)=2x. In my understanding, grad2=β((x + β(x^2))^2)=β((x+2x)^2)=β((3x)^2)=9βx^2=18x . As expected, grad=4.0=2x, but grad2=12.0=6x, which I don't understand where it comes from. It feels as though the 3 comes from the expression I had, but it is not squared, and the 2 comes from the traditional derivative. Could somebody help me understand why this is happening? Furthermore, how far back does the computational graph that stores the gradients go?
Specifically, I am coming from a meta learning perspective, where one is interested in computing a quantity of the following form β L(theta - alpha * β L(theta))=(1 + β^2 L(theta)) βL(theta - alpha * β L(theta) (here the derivative is with respect to theta). Therefore, the computation, let's call it A, includes a second derivative. Computation is quite different than the following β_{theta - alpha β L(theta)}L(\theta - alpha * β L(theta))=β_beta L(beta), which I will call B.
Hopefully, it is clear how the snippet I had is related to what I described in the second paragraph. My overall question is: under what circumstances does pytorch realize computation A vs computation B when using autograd.grad? I'd appreciate any explanation that goes into technical details about how this particular case is handled by autograd.
PD. The original code I was following made me wonder this is here; in particular, lines 69 through 106, and subsequently line 193, which is when they use autograd.grad. For the code is even more unclear because they do a lot of model.clone() and so on.
If the question is unclear in any way, please let me know.
| I made a few changes:
I am not sure what torch.rand(2.0) is supposed to do. According to the text I simply set it to 2.
An intermediate variable z is added so that we can compute gradient w.r.t. to the original variable. Yours is overwritten.
Set create_graph=True to compute higher order gradients. See https://pytorch.org/docs/stable/generated/torch.autograd.grad.html
import torch
from torch import autograd
x = torch.ones(1, requires_grad=True)*2
y = torch.square(x)
grad = autograd.grad(y, x, create_graph=True)
z = x + grad[0]
y = torch.square(z)
grad2 = autograd.grad(y, x)
# yours is more like autograd.grad(y, z)
print(x)
print(grad)
print(grad2)
| https://stackoverflow.com/questions/73188479/ |
Visual Transformer - understand if a model is pre-trained or not | I am working on a binary image classifier, and I am now testing using a Visual Transformer for the task. As a reference, I am using the model reimplementation by lucidrains. In the code snippet used to declare the model (see here and below), is the model pretrained or do we do the training from scratch? Thanks!
import torch
from vit_pytorch import SimpleViT
v = SimpleViT(
image_size = 256,
patch_size = 32,
num_classes = 1000,
dim = 1024,
depth = 6,
heads = 16,
mlp_dim = 2048
)
| If you look into the implementation code, there is no weight loading involved.
| https://stackoverflow.com/questions/73189858/ |
When to use prepare_data vs setup in pytorch lightning? | Pytorch's docs on Dataloaders only say, in the code
def prepare_data(self):
# download
...
and
def setup(self, stage: Optional[str] = None):
# Assign train/val datasets for use in dataloaders
Please explain the intended separation between prepare_data and setup, what callbacks may occur between them, and why put something in one over the other.
| If you look at the pseudo for the Trainer.fit function provided in the documentation page of LightningModule at Β§ Hooks, you can read:
def fit(self):
if global_rank == 0:
# prepare data is called on GLOBAL_ZERO only
prepare_data() ## <-- prepare_data
configure_callbacks()
with parallel(devices):
# devices can be GPUs, TPUs, ...
train_on_device(model)
def train_on_device(model):
# called PER DEVICE
on_fit_start()
setup("fit") ## <-- setup
configure_optimizers()
# the sanity check runs here
on_train_start()
for epoch in epochs:
fit_loop()
on_train_end()
on_fit_end()
teardown("fit")
You can see prepare_data being called only for global_rank == 0, i.e. it is only called by a single processor. It turns out you can read from the documentation description of prepare_data:
LightningModule.prepare_data()
Use this to download and prepare data. Downloading and saving data with multiple processes (distributed settings) will result in corrupted data. Lightning ensures this method is called only within a single process, so you can safely add your downloading logic within.
Whereas setup is called on all processes as you can read from the pseudo-code above as well as its documentation description:
LightningModule.setup(stage=None)Called at the beginning of fit (train + validate), validate, test, or predict. This is a good hook when you need to build models dynamically or adjust something about them. This hook is called on every process when using DDP.
| https://stackoverflow.com/questions/73191999/ |
How to get total test accuracy for pytorch lightning? | How can the trainer.test method be used to get total accuracy over all batches?
I know I can implement model.test_step but that is for a single batch only. I need the accuracy over the whole data set. I can use torchmetrics.Accuracy to accumulate accuracy. But what is the proper way to combine that and get the total accuracy out? What is model.test_step supposed to return anyway since batchwise test scores are not very useful? I could hack it somehow, but I'm surprised that I couldn't find any example on the internet that demonstrates how to get accuracy with the pytorch-lightning native way.
| You can see here (https://pytorch-lightning.readthedocs.io/en/stable/extensions/logging.html#automatic-logging) that the on_epoch argument in log automatically accumulates and logs at the end of the epoch. The right way of doing this would be:
from torchmetrics import Accuracy
def validation_step(self, batch, batch_idx):
x, y = batch
preds = self.forward(x)
loss = self.criterion(preds, y)
accuracy = Accuracy()
acc = accuracy(preds, y)
self.log('accuracy', acc, on_epoch=True)
return loss
If you want a custom reduction function you can set it using the reduce_fx argument, the default is torch.mean(). log() can be called from any method in you LightningModule
| https://stackoverflow.com/questions/73192494/ |
AttributeError: 'list' object has no attribute 'size' | I'm trying to prepare some audio data for a Dataloader but I'm struggling with a few points. At the moment my data is organised into two lists inputs and target, which are both length 32, but have different dimensions for their elements; inputs[0].shape = (8, 3690288) (8 mono audio tracks) and target[0].shape = (2, 3690288) (a single stereo mix).
I've converted each array to a tensor by:
tensor_inputs = torch.Tensor(inputs)
tensor_target = torch.Tensor(target)
which seems to work: tensor_inputs.shape = torch.Size([32, 8, 3690288]). I've then tried to convert each of these to a melspectrogram:
melspectrogram = torchaudio.transforms.melspectrogram(
sr=44100,
n_fft=1024,
hop_length=512,
n_mels=64)
tensor_input_specs = []
for i in range(len(tensor_inputs)):
spec = mel_spectrogram(tensor_inputs[i])
tensor_input_specs.append(spec)
tensor_target_specs = []
for i in range(len(tensor_target)):
spec = mel_spectrogram(tensor_target[i])
tensor_target_specs.append(spec)
and then move these into a Dataloader by doing:
dataset = TensorDataset(tensor_input_specs,tensor_target_specs)
iter = DataLoader(dataset)
However I get the following error: AttributeError: 'list' object has no attribute 'size', which I imagine is due to the fact that I'm appending the spectrograms to a list, but I'm not sure how else to achieve this.
EDIT:
AttributeError Traceback (most recent call last)
C:\Users\BRUDAL~1\AppData\Local\Temp/ipykernel_24968/2240294361.py in <module>
14 tensor_target_specs.append(spec)
15
---> 16 dataset = TensorDataset(tensor_input_specs,tensor_target_specs)
17 iter = DataLoader(dataset) # create your dataloader
~\anaconda3\lib\site-packages\torch\utils\data\dataset.py in __init__(self, *tensors)
165
166 def __init__(self, *tensors: Tensor) -> None:
--> 167 assert all(tensors[0].size(0) == tensor.size(0) for tensor in tensors), "Size mismatch between tensors"
168 self.tensors = tensors
169
~\anaconda3\lib\site-packages\torch\utils\data\dataset.py in <genexpr>(.0)
165
166 def __init__(self, *tensors: Tensor) -> None:
--> 167 assert all(tensors[0].size(0) == tensor.size(0) for tensor in tensors), "Size mismatch between tensors"
168 self.tensors = tensors
169
AttributeError: 'list' object has no attribute 'size'
| The most straightforward method I've found is by stacking the list after the for loops, by using torch.stack:
tensor_input_specs = []
for i in range(len(tensor_inputs)):
spec = mel_spectrogram(tensor_inputs[i])
tensor_input_specs.append(spec)
tensor_input_specs = torch.stack(train_tensor_input_specs)
tensor_input_specs.shape
>>> torch.size([32, 8, 64, 7208])
| https://stackoverflow.com/questions/73192914/ |
'No module named 'engine' error in Pytorch tutorial | I am following a tutorial on the PyTorch website and I can't figure out what package this import uses:
from engine import train_one_epoch, evaluate
I get an error saying:
Traceback (most recent call last):
File "C:\Users\...\tv-training-code.py", line 13, in <module>
from engine import train_one_epoch, evaluate
ModuleNotFoundError: No module named 'engine'
For reference, I am using Conda to run the program and I have the latest PyTorch version installed. Any ideas for what package I need to install to make this work?
| There is an obvious omission to the subject tutorial, which has caused justified confusion to others, too; this question has been raised in the Pytorch forum as well - here is the accepted answer:
In references/detection/, we have a number of helper functions to simplify training and evaluating detection models. Here, we will use references/detection/engine.py, references/detection/utils.py and references/detection/transforms.py. Just copy them to your folder and use them here.
Essentially, the necessary steps are shown in the colab notebook accompanying the tutorial:
%%shell
# Download TorchVision repo to use some files from
# references/detection
git clone https://github.com/pytorch/vision.git
cd vision
git checkout v0.8.2
cp references/detection/utils.py ../
cp references/detection/transforms.py ../
cp references/detection/coco_eval.py ../
cp references/detection/engine.py ../
cp references/detection/coco_utils.py ../
which must be executed before you attempt to import anything from the engine module.
| https://stackoverflow.com/questions/73198329/ |
How to find features and targets for subset of data? | I'm trying to find the specific amount of features in a subset of a dataset. Below is an example code:
# import the required modules
import torch
import torchvision
from torchvision.datasets import CIFAR10
from collections import Counter
trainset = CIFAR10(root='./data', train=True, download=True, transform=torchvision.transforms.ToTensor())
indices = torch.arange(3000)
new_trainset_split = torch.utils.data.Subset(trainset, indices)
This outputs a 3000 datapoints, which is exactly what I want. However when I try the next line of code to see, how many types of each features there are (in this case, how many of the datapoints are 1's, 2's, 3's etc..), it gives me the error:
print(dict(Counter(new_trainset_split.targets)))
AttributeError: 'Subset' object has no attribute 'targets'
How do I find features and targets for subset of data?
| The reason why you are not getting access to targets is because data.Subset simply doesn't implement the attributes as the wrapped data.Dataset (in your case datasets.CIFAR10) implements.
However, an easy workaround is to simply filter your initial dataset's targets with indices directly:
>>> Counter(trainset.targets[i] for i in indices)
Counter({0: 299,
1: 287,
2: 322,
3: 285,
4: 311,
5: 279,
6: 312,
7: 297,
8: 308,
9: 300})
| https://stackoverflow.com/questions/73200934/ |
How can I add some error to linear layer in pytorch? | I want to add some errors to parameters like the following code.
import torch
import torch.nn as nn
layer = nn.Linear(10, 100)
plus_weight = torch.randn(100, 10)
layer.weight += plus_weight
But I got this error.
RuntimeError: a leaf Variable that requires grad is being used in an in-place operation.
How can I avoid this error? And why can't I change the layer parameter value directly?
| you can use .data to modify the value of leaf node
layer.weight.data += plus_weight
if you want initialize or update parameters, assigning to .data is the way to go.
But it is very dangerous to take a in-place operation to modify the value of a leaf node in the middle of a forward pass since it may broken the backward result.
For example
import torch
a = torch.randn(1,1,requires_grad=True)
print(a)
b = a**2
c = torch.sum(b**2)
a.data += 1
c.backward()
print(a.grad)
the output result will be
tensor([[0.9123]], requires_grad=True)
tensor([[6.3666]])
with the code above, we have c = b**2 = a**2γ Derivation of c with respect to a should should be 4*a**3. but since you update the value of a during middle of forward process, the b will be 0.9123**2 not (0.9123+1)**2. and the final result with a.grad will be 2*(0.9123**2)*2*1.9123
| https://stackoverflow.com/questions/73201404/ |
ValueError: out_channels must be divisible by groups | I want to implement these three layers in a single class, but I face this problem
ValueError: out_channels must be divisible by groups
I don't understand where is the mistake?!
THis is the code:
class Block(nn.Module):
def __init__(self, in_channels, out_channels, exp=1, stride=1, type=''):
super().__init__()
self.t = type
self.stride = stride
self.inc, self.outc = in_channels, out_channels
self.exp = exp
self.blockc = nn.Sequential(
nn.Conv2d(self.inc, self.inc* self.exp, kernel_size=1),
nn.ReLU(),
nn.Conv2d(self.inc * self.exp, self.outc, kernel_size=3, groups= self.inc * self.exp, stride= self.stride),
nn.ReLU(),
nn.Conv2d(self.outc, self.outc * self.exp, kernel_size=1),
nn.Linear(self.outc * self.exp, self.outc * self.exp))
def forward(self, x):
out = self.blockc(x)
if self.t == 'A':
out = torch.sum(out,x)
return out
and here is the layers consists of depthwise convolution and conv 1x1 also there is a param exp which means out_channels = exp* in_channles
| Here is a possible implementation, you will have to adjust the channels and padding for your needs:
class BType(Enum):
A = 0
B = 1
C = 2
class Block(nn.Module):
def __init__(self, c_in: int, c_out: int, btype: BType) -> nn.Module:
super().__init__()
self.btype = btype
if btype == BType.A:
assert c_in == c_out
self.c1 = nn.Sequential(
nn.Conv2d(c_in, c_in, kernel_size=1),
nn.ReLU())
self.c2 = nn.Sequential(
nn.Conv2d(c_in, c_in, kernel_size=3, groups=c_in,
stride=2 if btype == BType.C else 1,
padding=2 if btype == BType.C else 1),
nn.ReLU())
self.c3 = nn.Conv2d(c_in, c_out, kernel_size=1)
def forward(self, x: torch.Tensor) -> torch.Tensor:
out = self.c1(x)
out = self.c2(out)
out = self.c3(out)
if self.btype == BType.A:
out += x
return out
Here is a test with all three block types:
block A:
>>> block = Block(3, 3, BType.A)
>>> block(torch.rand(2,3,10,10)).shape
torch.Size([2, 3, 10, 10])
block B:
>>> block = Block(3, 10, BType.B)
>>> block(torch.rand(2,3,10,10)).shape
torch.Size([2, 10, 10, 10])
block C:
>>> block = Block(3, 10, BType.C)
>>> block(torch.rand(2,3,10,10)).shape
torch.Size([2, 10, 6, 6])
| https://stackoverflow.com/questions/73201738/ |
RuntimeError: Found dtype Char but expected Float | I am using PyTorch in my program(Binary Classification).
The output from my model and actual labels are
model outputs are: (tensor([[0.4512],
[0.2273],
[0.4710],
[0.2965]], grad_fn=<SigmoidBackward0>), torch.float32),
actuall labels are (tensor([[0],
[1],
[0],
[1]], dtype=torch.int8), torch.int8)
When I calculate the Binary Cross Entropy, it gives me the error
RuntimeError: Found dtype Char but expected Float
I have no idea how it is finding the Char dtype.
Even If calculate it manually, it gives me this error.
import torch
cri = torch.nn.BCELoss()
cri(torch.tensor([[0.4470],[0.5032],[0.3494],[0.5057]], dtype=torch.float), torch.tensor([[0],[1],[0],[0]], dtype=torch.int8))
My DataLoader is
# CREATING DATA LOADER
class MyDataset(torch.utils.data.Dataset):
def __init__(self, dataframe, subset='train'):
self.subset = subset
self.dataframe = dataframe
self.transforms = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.Grayscale(),
transforms.ToTensor(),
transforms.Normalize((0.5), (0.5))
])
def __len__(self):
return len(self.dataframe)
def __getitem__(self, index):
row = self.dataframe.iloc[index]
img = Image.open(os.path.join('/kaggle/input/mura-v11',row['path']))
if self.subset=='train':
# print(torch.tensor(0, dtype=torch.int8) if row['labels'] == 'negative' else torch.tensor(1, dtype=torch.int8))
return (self.transforms(img), torch.tensor(0, dtype=torch.int8) if row['labels'] == 'negative' else torch.tensor(1, dtype=torch.int8))
else:
tensor_img = torchvision.transforms.functional.to_tensor(img)
return (tensor_img, torch.tensor(0, dtype=torch.int8) if row['labels'] == 'negative' else torch.tensor(1, dtype=torch.int8))
my training loop is
def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
since = time.time()
best_model_wts = copy.deepcopy(model.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
print(f'Epoch {epoch}/{num_epochs - 1}')
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
# track history if only in train
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
print(f"model outputs are: {outputs, outputs.dtype}, \nmodel labels are {labels.view(labels.shape[0],1), labels.dtype}")
loss = criterion(outputs, labels.view(labels.shape[0], 1))
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
if phase == 'train':
scheduler.step()
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
# deep copy the model
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
print()
time_elapsed = time.time() - since
print(f'Training complete in {time_elapsed // 60:.0f}m {time_elapsed % 60:.0f}s')
print(f'Best val Acc: {best_acc:4f}')
# load best model weights
model.load_state_dict(best_model_wts)
return model
And my Model is
class MuraModel(torch.nn.Module):
def __init__(self):
"""
In the constructor we instantiate four parameters and assign them as
member parameters.
"""
super().__init__()
self.inp = torch.nn.Conv2d(1, 3, 3) # Change the num of channels to 3
self.backbone = models.resnet18(pretrained=True)
num_ftrs = self.backbone.fc.in_features
self.backbone.fc = nn.Linear(num_ftrs, 1)
self.act = nn.Sigmoid()
def forward(self, x):
"""
In the forward function we accept a Tensor of input data and we must return
a Tensor of output data. We can use Modules defined in the constructor as
well as arbitrary operators on Tensors.
"""
three_channel = self.inp(x)
back_out = self.backbone(three_channel)
return self.act(back_out)
# inp = nn.Conv2d(1, 3, 3)
# model_ft = models.resnet18(pretrained=True)(inp)
# num_ftrs = model_ft.fc.in_features
# model_ft.fc = nn.Linear(num_ftrs, 2)
# model_ft = model_ft.to(device)
criterion = nn.BCELoss()
model = MuraModel()
optimizer_ft = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# Decay LR by a factor of 0.1 every 7 epochs
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)
model = train_model(model, criterion, optimizer_ft, exp_lr_scheduler,
num_epochs=25)
How to overcome it.
EDIT
Trace back on train_model function:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
/tmp/ipykernel_17/2718774237.py in <module>
1 model = train_model(model, criterion, optimizer_ft, exp_lr_scheduler,
----> 2 num_epochs=25)
/tmp/ipykernel_17/2670448577.py in train_model(model, criterion, optimizer, scheduler, num_epochs)
33 _, preds = torch.max(outputs, 1)
34 print(f"model outputs are: {outputs, outputs.dtype}, \nmodel labels are {labels.view(labels.shape[0],1), labels.dtype}")
---> 35 loss = criterion(outputs, labels.view(labels.shape[0], 1))
36
37 # backward + optimize only if in training phase
/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
1108 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1109 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1110 return forward_call(*input, **kwargs)
1111 # Do not call functions when jit is used
1112 full_backward_hooks, non_full_backward_hooks = [], []
/opt/conda/lib/python3.7/site-packages/torch/nn/modules/loss.py in forward(self, input, target)
610
611 def forward(self, input: Tensor, target: Tensor) -> Tensor:
--> 612 return F.binary_cross_entropy(input, target, weight=self.weight, reduction=self.reduction)
613
614
/opt/conda/lib/python3.7/site-packages/torch/nn/functional.py in binary_cross_entropy(input, target, weight, size_average, reduce, reduction)
3063 weight = weight.expand(new_size)
3064
-> 3065 return torch._C._nn.binary_cross_entropy(input, target, weight, reduction_enum)
3066
3067
RuntimeError: Found dtype Char but expected Float
Trace back on calculating loss individually
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
/tmp/ipykernel_17/4156819471.py in <module>
1 import torch
2 cri = torch.nn.BCELoss()
----> 3 cri(torch.tensor([[0.4470],[0.5032],[0.3494],[0.5057]], dtype=torch.float), torch.tensor([[0],[1],[0],[0]], dtype=torch.int8))
/opt/conda/lib/python3.7/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
1108 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1109 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1110 return forward_call(*input, **kwargs)
1111 # Do not call functions when jit is used
1112 full_backward_hooks, non_full_backward_hooks = [], []
/opt/conda/lib/python3.7/site-packages/torch/nn/modules/loss.py in forward(self, input, target)
610
611 def forward(self, input: Tensor, target: Tensor) -> Tensor:
--> 612 return F.binary_cross_entropy(input, target, weight=self.weight, reduction=self.reduction)
613
614
/opt/conda/lib/python3.7/site-packages/torch/nn/functional.py in binary_cross_entropy(input, target, weight, size_average, reduce, reduction)
3063 weight = weight.expand(new_size)
3064
-> 3065 return torch._C._nn.binary_cross_entropy(input, target, weight, reduction_enum)
3066
3067
RuntimeError: Found dtype Char but expected Float
| BCELoss() expects float labels. Yours are int8 (aka char). Converting them to float in the last line of__getitem__()should fix the issue.
| https://stackoverflow.com/questions/73203286/ |
Reshape original X from LSTM with predictions | I have a tensor with my LSTM inputs X (in PyTorch) as well as the matching predictions Y_hat
I want to add the Y_hat as a column to the original X.
The problem is that LSTM a sliding window with seq_length. In case seq. length is 3 and I have 6 variables in X, and 2 variables in Y_hat, I have something like this:
First entry of Tensor:
X1:
[1 2 3 4 5 6]
[5 4 6 7 8 9]
[3 6 8 7 4 8]
Y_hat1
[0 1]
X2:
[5 4 6 7 8 9] (repeated from X1)
[3 6 8 7 4 8] (repeated from X1)
[4 8 7 9 8 4]
Y_hat1
[1 1]
and so on.
Is there an easy pythonesk command to reshape the X with Y so I can quickly get:
[3 6 8 7 4 8 0 1]
[4 8 7 9 8 4 1 1]
| Having defined X1, X2, Y_hat1, and Y_hat2:
X1 = torch.tensor([[1, 2, 3, 4, 5, 6],
[5, 4, 6, 7, 8, 9],
[3, 6, 8, 7, 4, 8]])
Y_hat1 = torch.tensor([0,1])
X2 = torch.tensor([[5, 4, 6, 7, 8, 9],
[3, 6, 8, 7, 4, 8],
[4, 8, 7, 9, 8, 4]])
Y_hat2 = torch.tensor([1,1])
As well as stacks of inputs (X) and targets (Y):
X = torch.stack([X1, X2])
Y = torch.stack([Y_hat1, Y_hat2])
You can the desired operation using concatenation and stacking operators:
>>> X = torch.stack([X1, X2])
>>> Y = torch.stack([Y_hat1, Y_hat2])
>>> torch.stack(tuple(torch.cat((x[-1], y)) for x, y in zip(X, Y)))
Which expanded corresponds to:
>>> torch.stack((
torch.cat((X1[-1], Y_hat1)),
torch.cat((X2[-1], Y_hat2))))
In a more vectorized fashion you can do:
>>> torch.hstack((X[:,-1], Y))
| https://stackoverflow.com/questions/73203610/ |
How to seamlesly load different ML models in python? | Let's say I have my original .pt weights and I export them to ONNX, OpenVINO and TFLite. Is there a way of loading these models without needing to write a custom class that checks its type of instance and loads it accordingly?
OpenVINO model loading example:
from openvino.runtime import Core
ie = Core()
classification_model_xml = "model/classification.xml"
model = ie.read_model(model=classification_model_xml)
compiled_model = ie.compile_model(model=model, device_name="CPU")
TFlite model loading example:
class TestModel(tf.Module):
def __init__(self):
super(TestModel, self).__init__()
@tf.function(input_signature=[tf.TensorSpec(shape=[1, 10], dtype=tf.float32)])
def add(self, x):
'''
Simple method that accepts single input 'x' and returns 'x' + 4.
'''
# Name the output 'result' for convenience.
return {'result' : x + 4}
SAVED_MODEL_PATH = 'content/saved_models/test_variable'
TFLITE_FILE_PATH = 'content/test_variable.tflite'
# Save the model
module = TestModel()
# You can omit the signatures argument and a default signature name will be
# created with name 'serving_default'.
tf.saved_model.save(
module, SAVED_MODEL_PATH,
signatures={'my_signature':module.add.get_concrete_function()})
# Convert the model using TFLiteConverter
converter = tf.lite.TFLiteConverter.from_saved_model(SAVED_MODEL_PATH)
tflite_model = converter.convert()
with open(TFLITE_FILE_PATH, 'wb') as f:
f.write(tflite_model)
# Load the TFLite model in TFLite Interpreter
interpreter = tf.lite.Interpreter(TFLITE_FILE_PATH)
# There is only 1 signature defined in the model,
# so it will return it by default.
# If there are multiple signatures then we can pass the name.
my_signature = interpreter.get_signature_runner()
# my_signature is callable with input as arguments.
output = my_signature(x=tf.constant([1.0], shape=(1,10), dtype=tf.float32))
# 'output' is dictionary with all outputs from the inference.
# In this case we have single output 'result'.
print(output['result'])
pt model loading example:
model = TheModelClass(*args, **kwargs)
model.load_state_dict(torch.load(PATH))
| The closest solution I could find for this, atm, is Ivy . However, you have to write your model using their framework agnostic operations and the set of available frameworks are quite limited: jnp, tf, np, mx, torch
I found a quite good adapter that I will base my own on, here
| https://stackoverflow.com/questions/73205508/ |
Identifying the loudest part of an audio track and cropping (Librosa or torchaudio) | I've built a U-Net model to perform audio mixing of multitrack audio, for which I've used 20s clips of the audio tracks (converted into spectrograms) as input in training the model. However the training process is incredibly long, so I think it would be better to take 2s clips from each track to train the model.
The data is organised as 8 stems (individual instrument tracks) as the inputs and a single mixture of the stems as the target (all have sr=44100). I want to find the most energetic 2s section of the mixture track and crop all tracks (input and mixture) this specific 2s part. I'm mainly using librosa in my data preparation but I'm unsure what functions to use to find the start point of the loudest (I understand this is ambiguous) 88200 sample segment (2s).
| If I am following the question well enough, the below code might be useful as a starting point. It takes in one sound file and locates where it is "loudest" (as you allude to in the question, defining what bit is loudest is not entirely straight-forward) using librosa.feature.rms and then cuts a two second slice out of the original sound file centered on that point:
import librosa
FILENAME = 'soundfile.wav' # change to path of your sound file
FRAME_LENGTH = 2048
HOP_LENGTH = 512
NUM_SECONDS_OF_SLICE = 2
sound, sr = librosa.load(FILENAME, sr=None)
clip_rms = librosa.feature.rms(y=sound,
frame_length=FRAME_LENGTH,
hop_length=HOP_LENGTH)
clip_rms = clip_rms.squeeze()
peak_rms_index = clip_rms.argmax()
peak_index = peak_rms_index * HOP_LENGTH + int(FRAME_LENGTH/2)
half_slice_width = int(NUM_SECONDS_OF_SLICE * sr / 2)
left_index = max(0, peak_index - half_slice_width)
right_index = peak_index + half_slice_width
sound_slice = sound[left_index:right_index]
| https://stackoverflow.com/questions/73208147/ |
Using Transposed convolution for upsampling in PyTorch | I have a 4D tensor of (2,1024,4,6). I want to use transposed convolution for upsampling spatial dimensions of such tensor by factor of two and reducing the channel numbers from 1024 to the 512. I want to have a 4D tensor like this (2,512,8,12). How can I do that? Also, is the transposed convolution a good idea for reducing the channel numbers? For example I used the following script but it is not working:
nn.ConvTranspose3d(in_channels=1024, out_channels=512, kernel_size=(1,2,2), stride=(1,3,2), padding=(0,1,1))
| It seems you should be using ConvTranspose2d instead of ConvTranspose3d since your input tensor is 4D, shaped NCHW.
There are different ways of getting to these results but one straightforward approach is to use a kernel size of 2 with a matching stride:
>>> conv = nn.ConvTranspose2d(1024, 512, kernel_size=2, stride=2)
Here is an inference example:
>>> conv(torch.rand(2, 1024, 4, 6)).shape
torch.Size([2, 512, 8, 12])
| https://stackoverflow.com/questions/73208923/ |
How does torch differentiate between batch and single values? | Hereβs my neural network.
from torch import nn
from torch.utils.data import DataLoader
class NeuralNetwork(nn.Module):
def __init__(self, state_size, action_size):
super(NeuralNetwork, self).__init__()
self.state_size = state_size
self.action_size = action_size
# self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(1, 30),
nn.ReLU(),
nn.Linear(30, 30),
nn.ReLU(),
nn.Linear(30, action_size)
)
def forward(self, x):
x = self.linear_relu_stack(x)
return x
As you can imagine, it can compute tensor inputs of the shape torch.Size([1]). However, when I try to feed it batch data, for instance, shape torch.Size([10]) it throws the following error -
RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x10 and 1x30)
For instance, this code works -
net = NeuralNetwork(10, 5)
x1 = torch.rand(1)
print(x1.shape)
out = net(x1)
But this fails -
x2 = torch.rand(10)
print(x2.shape)
out = net(x2)
| You just need to change your inputs a little bit. Your code is expecting the net() to have a second dimension of 1, so it can multiply by nn.linear(1,30). The inner dimensions must match for matrix multiplication to occur. I.e. 10x1 * 1x30:
x2 = torch.rand(10,1)
print(x2.shape)
out = net(x2)
torch.Size([10, 1])
Try this with any dimension x2 = torch.rand(100,1) etc. it still works.
| https://stackoverflow.com/questions/73213785/ |
Load estimator from model artifact in s3 bucket aws | I have used estimator for a pytorch model and have saved the artifacts in s3 bucket. using below code
estimator = PyTorch(
entry_point="train_deploy.py",
source_dir="code",
role=role,
framework_version="1.3.1",
py_version="py3",
instance_count=1, # this script only support distributed training for GPU instances.
instance_type="ml.m5.12xlarge",
output_path=output_path,
hyperparameters={
"epochs": 1,
"num_labels": 7,
"backend": "gloo",
},
disable_profiler=False, # disable debugger
)
estimator.fit({"training": inputs_train, "testing": inputs_test})
The model works well and there are no issues with it. However i would like to re use this model later for inference, how do i do that. i am looking for something like below
estimator = PyTorch.load(input_path = "<xyz>")
| I was able to solve this by the following steps
model_data=output_path
from sagemaker.pytorch.model import PyTorchModel
pytorch_model = PyTorchModel(model_data=model_data,
role=role,
framework_version="1.3.1",
source_dir="code",
py_version="py3",
entry_point="train_deploy.py")
predictor = pytorch_model.deploy(initial_instance_count=1, instance_type="ml.m4.2xlarge")
predictor.serializer = sagemaker.serializers.JSONSerializer()
predictor.deserializer = sagemaker.deserializers.JSONDeserializer()
result = predictor.predict("<text that needs to be predicted>")
print("predicted class: ", np.argmax(result, axis=1))
| https://stackoverflow.com/questions/73216926/ |
How do I make my custom loss function scalar? | I am coding a dqn from scratch and therefore have written my loss function. While calling backward on my loss function, I get the following error - RuntimeError: grad can be implicitly created only for scalar outputs
Here's my code -
import numpy as np
import gym
import matplotlib.pyplot as plt
import os
import torch
import random
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from collections import deque
import sys
env = gym.make("CliffWalking-v0")
# In[103]:
#Hyperparameters
episodes = 5000
eps = 1.0
learning_rate = 0.1
discount_factor = 0.99
tot_rewards = []
decay_val = 0.001
mem_size = 50000
batch_size = 2
gamma = 0.99
# In[104]:
class NeuralNetwork(nn.Module):
def __init__(self, state_size, action_size):
super(NeuralNetwork, self).__init__()
self.state_size = state_size
self.action_size = action_size
self.linear_relu_stack = nn.Sequential(
nn.Linear(1, 30),
nn.ReLU(),
nn.Linear(30, 30),
nn.ReLU(),
nn.Linear(30, action_size)
)
def forward(self, x):
x = self.linear_relu_stack(x)
return x
# In[105]:
model = NeuralNetwork(env.observation_space.n, env.action_space.n)
opt = torch.optim.Adam(params=model.parameters(), lr=learning_rate)
loss = nn.MSELoss()
replay_buffer = deque(maxlen=mem_size)
# In[106]:
state = torch.tensor(env.reset(), dtype=torch.float32)
state = state.unsqueeze(dim=0)
print(state.shape)
out = model(state)
# In[111]:
def compute_td_loss(batch_size):
state, next_state, reward, done, action = zip(*random.sample(replay_buffer, batch_size))
state = torch.from_numpy(np.array(state).reshape(-1, 1)).unsqueeze(dim = 0).type(torch.float32)
next_state = torch.from_numpy(np.array(next_state).reshape(-1, 1)).unsqueeze(dim = 0).type(torch.float32)
reward = torch.from_numpy(np.array(reward))
done = torch.from_numpy(np.array(done))
action = torch.from_numpy(np.array(action)).type(torch.int64)
q_values = model(state)
next_q_values = model(next_state)
q_vals = q_values.squeeze().gather(dim=-1, index=action.reshape(-1,1)).reshape(1, -1)
max_next_q_values = torch.max(next_q_values,2)[0].detach()
print("q_vals = ", q_vals)
print("max_next_q_values = ", max_next_q_values)
loss = 0.5*(reward + gamma*max_next_q_values - q_vals)**2
print("reward = ", reward)
print("loss = ", loss)
opt.zero_grad()
loss.backward()
opt.step()
return loss
# In[112]:
for i in range(episodes):
state = env.reset()
done = False
steps = 0
eps_rew = 0
while not done and steps<50:
if np.random.uniform(0,1)<eps:
action = env.action_space.sample()
else:
state = torch.tensor(state, dtype=torch.float32)
state = state.unsqueeze(dim=0)
action = np.argmax(model(state).detach().numpy())
next_state, reward, done, info = env.step(action)
replay_buffer.append((state, next_state, reward, done, action))
if len(replay_buffer)>batch_size:
loss = compute_td_loss(batch_size)
sys.exit()
eps = eps/(1 + 0.001)
eps_rew += reward
if done:
break
state = next_state
tot_rewards.append(eps_rew)
Here's the error that I get -
RuntimeError Traceback (most recent call last)
<ipython-input-112-015fd74c95d9> in <module>
14 replay_buffer.append((state, next_state, reward, done, action))
15 if len(replay_buffer)>batch_size:
---> 16 loss = compute_td_loss(batch_size)
17 sys.exit()
18 eps = eps/(1 + 0.001)
<ipython-input-111-3e1e02c32b4f> in compute_td_loss(batch_size)
16 print("loss = ", loss)
17 opt.zero_grad()
---> 18 loss.backward()
19 opt.step()
20 return loss
c:\users\thoma\anaconda3\envs\custom_atari_env\lib\site-packages\torch\_tensor.py in backward(self, gradient, retain_graph, create_graph, inputs)
253 create_graph=create_graph,
254 inputs=inputs)
--> 255 torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)
256
257 def register_hook(self, hook):
c:\users\thoma\anaconda3\envs\custom_atari_env\lib\site-packages\torch\autograd\__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
141
142 grad_tensors_ = _tensor_or_tensors_to_tuple(grad_tensors, len(tensors))
--> 143 grad_tensors_ = _make_grads(tensors, grad_tensors_)
144 if retain_graph is None:
145 retain_graph = create_graph
c:\users\thoma\anaconda3\envs\custom_atari_env\lib\site-packages\torch\autograd\__init__.py in _make_grads(outputs, grads)
48 if out.requires_grad:
49 if out.numel() != 1:
---> 50 raise RuntimeError("grad can be implicitly created only for scalar outputs")
51 new_grads.append(torch.ones_like(out, memory_format=torch.preserve_format))
52 else:
RuntimeError: grad can be implicitly created only for scalar outputs
| Given that your batch_size = 2 and looking at your code your loss will likely be of size batch_size x 1. Given that what you are likely trying to do is to compute the gradient of expected Q loss you can use monte carlo estimator where instead of computing an expectation we use a mean over a finite sample (here - your batch). Consequently what you are missing is taking a mean of your loss before calling backwards.
| https://stackoverflow.com/questions/73224528/ |
RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed) | I am trying to get to grips with Pytorch and I wanted to try to reproduce this code:
https://github.com/andy-psai/MountainCar_ActorCritic/blob/master/RL%20Blog%20FINAL%20MEDIUM%20code%2002_12_19.ipynb
in Pytorch.
I am having a problem in that this error is being returned:
RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward.
A similar question said to use zero_grad() again after the optimizer step, but this hasn't resolved the issue.
I've included the entire code below so hopefully it should be reproduceable.
Any advice would be much appreciated.
import gym
import os
import os.path as osp
import time
import math
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.distributions import Normal
env = gym.envs.make("MountainCarContinuous-v0")
# Value function
class Value(nn.Module):
def __init__(self, dim_states):
super(Value, self).__init__()
self.net = nn.Sequential(
nn.Linear(dim_states, 400),
nn.ReLU(),
nn.Linear(400,400),
nn.ReLU(),
nn.Linear(400, 1)
)
self.optimizer = optim.Adam(self.parameters(), lr = 1e-3)
self.criterion = nn.MSELoss()
def forward(self, state):
return self.net(torch.from_numpy(state).float())
def compute_return(self, output, target):
self.optimizer.zero_grad()
loss = self.criterion(output, target)
loss.backward()
self.optimizer.step()
self.optimizer.zero_grad()
# Policy network
class Policy(nn.Module):
def __init__(self, dim_states, env):
super(Policy, self).__init__()
self.hidden1 = nn.Linear(dim_states, 40)
self.hidden2 = nn.Linear(40, 40)
self.mu = nn.Linear(40, 1)
self.sigma = nn.Linear(40,1)
self.env = env
self.optimizer = optim.Adam(self.parameters(), lr = 2e-5)
def forward(self, state):
state = torch.from_numpy(state).float()
x = F.relu(self.hidden1(state))
x = F.relu(self.hidden2(x))
mu = self.mu(x)
sigma = F.softmax(self.sigma(x), dim=-1)
action_dist = Normal(mu, sigma)
action_var = action_dist.rsample()
action_var = torch.clip(action_var,
self.env.action_space.low[0],
self.env.action_space.high[0])
return action_var, action_dist
def compute_return(self, action, dist, td_error):
self.optimizer.zero_grad()
loss_actor = -dist.log_prob(action)*td_error
loss_actor.backward()
self.optimizer.step()
self.optimizer.zero_grad()
# Normalise the state space
import sklearn
import sklearn.preprocessing
state_space_samples = np.array(
[env.observation_space.sample() for x in range(10000)])
scaler = sklearn.preprocessing.StandardScaler()
scaler.fit(state_space_samples)
# Normaliser
def scale_state(state):
scaled = scaler.transform([state])
return scaled
##################################
# Parameters
lr_actor = 0.00002
lr_critic = 0.001
actor = Policy(2, env)
critic = Value(2)
# Training loop params
gamma = 0.99
num_episodes = 300
episode_history = []
for episode in range(num_episodes):
# Receive initial state from E
state = env.reset()
reward_total = 0
steps = 0
done = False
while not done:
action, dist = actor(state)
# print(np.squeeze(action))
next_state, reward, done, _ = env.step(
np.array([action.item()]))
if episode % 50 == 0:
env.render()
steps += 1
reward_total += reward
# TD Target
target = reward + gamma * np.squeeze(critic(next_state), axis=0)
td_error = target - np.squeeze(critic(state), axis=0)
# Update actor
actor.compute_return(action, dist, td_error)
# Update critic
critic.compute_return(np.squeeze(critic(state), axis=0), target)
episode_history.append(reward_total)
print(f"Episode: {episode}, N Steps: {steps}, Cumulative reward {reward_total}")
if np.mean(episode_history[-100:]) > 90 and len(episode_history) > 101:
print("Solved")
print(f"Mean cumulative reward over 100 episodes {np.mean(episode_history[-100:])}")
| Problem lies in this snippet. When you create target variable, there is a forward pass through critic which generates a computation graph and critic(next_state) is the leaf node of that graph making target a part of the graph (you can check this by printing target which will show you grad_fn=<AddBackward0>). Finally, when you call critic.compute_return(critic_out, target), a new computation graph is generated and passing target(which is a part of the previous computation graph) causes a Runtime error.
Solution is to call detach() on critic(next_state), this will free target variable and it will no longer be a part of the computation graph(again check by printing target).
target = reward + gamma * np.squeeze(critic(next_state).detach(), axis=0)
td_error = target - np.squeeze(critic(state), axis=0)
# Update actor
actor.compute_return(action, dist, td_error)
# Update critic
critic_out = np.squeeze(critic(state), axis=0)
print(critic_out)
critic.compute_return(critic_out, target)
| https://stackoverflow.com/questions/73225230/ |
Most efficient way to use Column major when reshape a 1D array in PyTorch | import torch
p = torch.arange(0, 12, requires_grad=False, dtype=torch.int32)
pr = torch.reshape(p, (4, 3))
what I want is
pr = [0 4 8
1 5 9
2 6 10
3 7 11]
but it actually becomes
pr = [0 1 2
3 4 5
6 7 8
9 10 11]
I search online it said permute can do it, but it will make a copy of your array, what is the most efficient way to reshape it in PyTorch?
| You are close but to get what you want you have to rearrange it a little bit.
import torch
p = torch.arange(0, 12, requires_grad=False, dtype=torch.int32)
pr = torch.reshape(p, (3, 4)).t()
pr
Out[49]:
tensor([[ 0, 4, 8],
[ 1, 5, 9],
[ 2, 6, 10],
[ 3, 7, 11]], dtype=torch.int32)
| https://stackoverflow.com/questions/73226015/ |
How to convert a generator to a Pytorch Dataloader? | I have a generator that creates synthetic data. How can I convert this into a PyTorch dataloader?
| You can wrap your generator with a data.IterableDataset:
class IterDataset(data.IterableDataset):
def __init__(self, generator):
self.generator = generator
def __iter__(self):
return self.generator()
Naturally, you can then wrap this dataset with a data.DataLoader.
Here is a minimal example showing its use:
>>> gen = lambda: [(yield x) for x in range(10)]
>>> dataset = IterDataset(gen)
>>> for i in data.DataLoader(dataset, batch_size=2):
... print(i)
tensor([0, 1])
tensor([2, 3])
tensor([4, 5])
tensor([6, 7])
tensor([8, 9])
| https://stackoverflow.com/questions/73228139/ |
How to set specific values for the weight and bias in a neural net? | I want to initialize the values of the weight and bias of the linear layers in my PyTorch neural network. Below is some code for my neural net:
class NeuralNet(nn.Module):
def __init__(self, weights, bias):
super(NeuralNet, self).__init__()
self.weights = weights
self.bias = bias
self.nn = nn.Sequential(
nn.Linear(3, 3),
nn.ReLU(),
nn.Linear(3, 3),
nn.ReLU(),
nn.Linear(3, 3),
nn.ReLU(),
nn.Linear(3, 1),
nn.ReLU(),
)
def forward(self, a, b, c):
a = torch.flatten(a) # shape: (n,)
b = torch.flatten(b) # shape: (n, 1)
c = torch.flatten(c) # shape: (n,)
y = torch.stack((a, b, c), 1)
y1 = self.nn(y)
return y1
weights = torch.rand(5)
bias = torch.rand(5)
net = NeuralNet(weights, bias)
Based on my understanding, aach layer in the neural net is currently related to 5 parameters (weights, bias, a, b, and c). Let's say I want to assign a list of values of the weights and biases that I know are pretty close to the actual values to the corresponding layer in the neural net. How do I go about doing that?
To clarify:
The PyTorch documentation says that nn.Linear contains two variables weight (~Linear.weight) and bias (~Linear.bias). I want to be able to assign values to each of these two values for every layer inside my neural net. Is there a way to point to each linear layer inside of nn.Sequential and set a value for the weights and bias?
| First, when assigning a weight value to a linear layer, the matrix size must be the same. The weight matrix size of fc1, fc2, and fc3 is 3*3, and the weight matrix size of fc4 is 1*3.
Second, to change the weight value, use no grad to prevent the weight from changing during training.
Third, when accessing sequential layers, you need to use square brackets. In the code below, the 0th element of self.l is nn.linear, the 1st element is nn.relu, the 2nd element is nn.linear, and so on.
Finally, you need to change the weight value using torch.nn.Parameter.
Code:
import torch
import torch.nn as nn
import torch.nn.functional as F
class NeuralNet(nn.Module):
def __init__(self):
super(NeuralNet, self).__init__()
self.l = nn.Sequential(
nn.Linear(3, 3),
nn.ReLU(),
nn.Linear(3, 3),
nn.ReLU(),
nn.Linear(3, 3),
nn.ReLU(),
nn.Linear(3, 1)
)
def forward(self, a, b, c):
a = torch.flatten(a)
b = torch.flatten(b)
c = torch.flatten(c)
y = torch.stack((a, b, c), 1)
y = self.l(y)
return y
net = NeuralNet()
with torch.no_grad():
print(net.l[0].weight)
net.l[0].weight = nn.Parameter(torch.randn(3,3))
net.l[0].bias = nn.Parameter(torch.randn(3))
print(net.l[0].weight)
Result:
Parameter containing:
tensor([[ 0.0684, -0.2947, 0.0059],
[-0.0430, -0.0716, -0.1406],
[-0.4114, -0.3912, -0.5121]], requires_grad=True)
Parameter containing:
tensor([[-0.5050, -0.1787, -0.5368],
[ 0.6825, -0.5514, 2.1333],
[-1.5563, 2.4367, -0.6201]], requires_grad=True)
| https://stackoverflow.com/questions/73228490/ |
AMD ROCm with Pytorch on Navi10 (RX 5700 / RX 5700 XT) | I am one of those miserable creatures who own a AMD GPU(RX 5700, Navi10). I want to use up-to-date PyTorch libraries to do some Deep Learning on my local machine and stop using cloud instances.
I saw all over the internet that AMD is promising Navi10 support in the next 2-4 months(posts that were written 1-2 years back) however, I do not think they released an "official" support.
I installed ROCm on local machine and it actually detects my GPU and everything seems nice, here is rocminfo output.
rocminfo output
I installed the necessary PyTorch ROCm version but when I try to run a code, I get the following error.
Error mesage
"hipErrorNoBinaryForGpu: Unable to find code object for all current devices!"
I suppose this is because ROCm still does not have a support for gfx1010 or I am lost at this point.
I would be happy if someone can provide a way to make ROCm work(preferable without compiling whole package for gfx1010 again) OR provide way to use an AMD GPU just like a CUDA user.
| Add 'HSA_OVERRIDE_GFX_VERSION=10.3.0' before 'python'
for example, in teminal, input:
HSA_OVERRIDE_GFX_VERSION=10.3.0 python launch.py
I used 5700xt to run stable-diffusion for months, it works.
| https://stackoverflow.com/questions/73229163/ |
How can I train a model with untrained feature extraction layers? (PyTorch) | I was wondering how can I keep my batch norm layers active using an untrained feature extraction network.
Would this be considered feature extraction with an "untrained" network?:
class DenseNetConv(torch.nn.Module):
def __init__(self):
super(DenseNetConv,self).__init__()
original_model = models.densenet161(pretrained=False)
self.features = torch.nn.Sequential(*list(original_model.children())[:-1])
self.avgpool = nn.AdaptiveAvgPool2d(1)
for param in self.parameters():
param.requires_grad = False
def forward(self, x):
x = self.features(x)
x = F.relu(x, inplace=True)
x = F.avg_pool2d(x, kernel_size=7).view(x.size(0), -1)
return x
The above should return a tensor of [batch size, 2208], however, I want to make sure that by stating pretrained=False that I am basically extracting features from an untrained network.
I then use the following to define the classifier layers:
class MyDenseNetDens(torch.nn.Module):
def __init__(self, nb_out=2):
super().__init__()
self.dens1 = torch.nn.Linear(in_features=2208, out_features=512)
self.dens2 = torch.nn.Linear(in_features=512, out_features=128)
self.dens3 = torch.nn.Linear(in_features=128, out_features=nb_out)
def forward(self, x):
x = self.dens1(x)
x = torch.nn.functional.selu(x)
x = F.dropout(x, p=0.25, training=self.training)
x = self.dens2(x)
x = torch.nn.functional.selu(x)
x = F.dropout(x, p=0.25, training=self.training)
x = self.dens3(x)
return x
and finally join them together here:
class MyDenseNet(torch.nn.Module):
def __init__(self):
super().__init__()
self.mrnc = MyDenseNetConv()
self.mrnd = MyDenseNetDens()
def forward(self, x):
x = self.mrnc(x)
x = self.mrnd(x)
return x
densenet = MyDenseNet()
densenet.to(device)
densenet.train()
If I allow this to train, for example by applying densenet.train() will this be sufficient in allowing batch normalisation statistics to be generated for each mini-batch as well as allow for the running means and standard deviations to be learnt and applied during inference, while keeping the convolutional layers untrained?
| Unfortunately, it will update the running stat anyway since the default batchnorm in your self.mrnc still initialized with the running mean and the running variance. All you need to do is shut them down:
class MyDenseNetConv(torch.nn.Module): # I renamed it to be correct to your code
def __init__(self):
super(MyDenseNetConv,self).__init__()
original_model = models.densenet161(pretrained=False)
for n, v in original_model.named_modules(): # this part is to remove the tracking stat option
if 'norm' in n:
v.track_running_stats=False
v.running_mean = None
v.running_var = None
v.num_batches_tracked = None
self.features = torch.nn.Sequential(*list(original_model.children())[:-1])
self.avgpool = nn.AdaptiveAvgPool2d(1)
for param in self.parameters():
param.requires_grad = False
def forward(self, x):
x = self.features(x)
x = F.relu(x, inplace=True)
x = F.avg_pool2d(x, kernel_size=7).view(x.size(0), -1)
return x
| https://stackoverflow.com/questions/73229481/ |
How to get the gradients from loss to target layer output for Grad-CAM computation with pytorch | I want to implement the code to get Grad-CAM map with pytorch(1.10.0). Most of implementation specify the target class to extract the gradients (This is a natural approach). But instead of this, I want to use gradients from loss to target layer output.
The following code is an example of a keras implementation of what I want to do. How can I implement it with pytorch?
loss = K.mean(K.square(y_pred - y_true), axis=-1)
output_conv = model.get_layer(layer_name).output
gradients = K.gradients(loss, output_conv)[0]
output, grads = K.function([model.input], [output_conv, gradients])([input_image])
| You can register the hook for both the forward and backward of a model while inferencing. I wrote an easy example with ResNet50:
import torch
from torchvision import models
activation = {}
def get_forward(name):
def hook(model, input, output):
activation[name] = output.detach()
return hook
def get_backward(name):
def hook(model, input, output):
activation[name] = output[0].detach()
return hook
model = models.resnet50(pretrained=False)
model.layer4[2].register_forward_hook(get_forward('forward'))
model.layer4[2].register_backward_hook(get_backward('backward'))
x = torch.randn(10, 3, 224, 224)
out = model(x)
loss = out.mean()
loss.backward()
output, grads = activation['forward'], activation['backward']
print(output.shape)
print(grads.shape)
>>> torch.Size([10, 2048, 7, 7])
>>> torch.Size([10, 2048, 7, 7])
The function should work well with CNNs, be careful with the Linear layer where the hook doesn't work as expected because of this bug which is simplified by this answer
| https://stackoverflow.com/questions/73230902/ |
Sort a multi-dimensional tensor using another tensor | I'm trying to sort C (see image) using R to get Sorted_C.
c = torch.tensor([[[0, 1, 0, 0, 0], [1, 0, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 0, 0, 1]], [[0, 0, 1, 1, 0], [1, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 0, 1, 0]]])
r = torch.tensor([[[0, 0, 0, 7.2, 0], [0, 25.4, 0, 0, 0], [0, 0, 43.6, 0, 0], [61.8, 0, 0, 0, 0], [0, 0, 0, 0, 80]], [[0, 0, 0, 0, 98.2], [116.4, 0, 0, 0, 0], [0, 134.6, 0, 0, 0], [0, 0, 152.8, 0, 0], [0, 0, 0, 169.2, 0]]])
# this is what I need
sorted_c = torch.tensor([[[0, 1, 0, 0, 0], [0, 0, 1, 1, 0], [1, 0, 0, 0, 0], [0, 0, 0, 0, 1]], [[0, 0, 0, 1, 1], [0, 1, 1, 0, 0], [0, 0, 0, 1, 0], [0, 0, 1, 0, 1]]])
How do I do this efficiently?
correction: expected ordering for P6 to P10 should be: P10 -> P6 -> P7 -> P8 -> P9
| Minor note: it seems your example r doesn't quite match the values in your drawing. Also, it seems the result for p6 through p10 should be p10 < p6 < p7 < p8 < p9.
When you hear "advanced indexing", you should think torch.gather. That is: the resulting tensor comes from the indexing of c column-wise with some kind of tensor we will extract from r.
First we can sum and sort r to get the indices of the columns:
>>> idx = r.sum(1).argsort(1)
tensor([[3, 1, 2, 0, 4],
[4, 0, 1, 2, 3]])
Then we can apply torch.Tensor.gather indexing c column-wise using the column indices contained in idx i.e. dim=2 is the one varying based on values in idx. Explicitly the resulting tensor out is constructed such that:
out[i][j][k] = c[i][j][idx[i][j][k]]
Keep in mind both the index tensor (idx) and the value tensor (c) must have same dimension sizes except for the one that we're indexing on, here dim=2. Therefore, we need to expand idx such that it has the shape of c. We can do so with None-indexing and using expand or expand_as:
>>> idx[:,None].expand_as(c)
tensor([[[3, 1, 2, 0, 4],
[3, 1, 2, 0, 4],
[3, 1, 2, 0, 4],
[3, 1, 2, 0, 4]],
[[4, 0, 1, 2, 3],
[4, 0, 1, 2, 3],
[4, 0, 1, 2, 3],
[4, 0, 1, 2, 3]]])
Notice the duplicated values row-wise (fiy: they're not copies, expand is makes a view not a copy!)
Finally, we can gather the values in c to get the desired result:
>>> c.gather(2, idx[:,None].expand_as(c))
tensor([[[0, 1, 0, 0, 0],
[0, 0, 1, 1, 0],
[1, 0, 0, 0, 0],
[0, 0, 0, 0, 1]],
[[0, 0, 0, 1, 1],
[0, 1, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 1, 0, 1]]])
| https://stackoverflow.com/questions/73232323/ |
Huggingface Trainer load_best_model f1 score vs. loss and overfitting | I have trained a roberta-large and specified load_best_model_at_end=True and metric_for_best_model=f1. During training, I can see overfitting after the 6th epoch, which is the sweetspot. In Epoch 8, which is the next one to evaluate due to gradient accumulation, we can see that train loss decreases and eval_loss increases. Thus, overfitting starts. The transformers trainer in the end loads the model from epoch 8, checkpoint -14928, as the f1 score is a bit highea. I was wondering, in theory, wouldn't be the model from epoch 6 be better suited, as it did not overfit? Or does one really go for the f1 metric here even though the model did overfit? (the eval loss decreased in epochs <6 constantly).
The test_loss from the second checkpoint, which is then loaded as the "best", is 0.128. Is it possible to lower that using the first checkpoint which should be the better model anyway?
checkpoint-11196:
{'loss': 0.0638, 'learning_rate': 8.666799323450404e-06, 'epoch': 6.0}
{'eval_loss': 0.09599845856428146, 'eval_accuracy': 0.9749235986101227, 'eval_precision': 0.9648319293367138, 'eval_recall': 0.9858766505097777, 'eval_f1': 0.9752407721241682, 'eval_runtime': 282.2294, 'eval_samples_per_second': 84.637, 'eval_steps_per_second': 2.647, 'epoch': 6.0}
VS.
checkpoint-14928:
{'loss': 0.0312, 'learning_rate': 7.4291115311909265e-06, 'epoch': 8.0}
{'eval_loss': 0.12377820163965225, 'eval_accuracy': 0.976305103194206, 'eval_precision': 0.9719324391455539, 'eval_recall': 0.9810295838208257, 'eval_f1': 0.9764598236566295, 'eval_runtime': 276.7619, 'eval_samples_per_second': 86.309, 'eval_steps_per_second': 2.699, 'epoch': 8.0}
| You could just comment the metric_for_best_model='f1' part out and see for yourself, loss is the default setting. Or, utilize from_pretrained('path/to/checkpoint') to compare two checkpoints back to back. F-score is threshold sensitive, so it's entirely possible for a lower loss checkpoint to be better in the end (assuming you do optimize the threshold).
| https://stackoverflow.com/questions/73232595/ |
I want to deploy a pytorch segmentation model in a C++ application .. C++ equivalent preprocessing | I want to deploy a pytorch segmentation model in a C++ application. I knew that I have to convert the model to a Torch Script and use libtorch.
However, what is C++ equivalent to the following pre-preprocessing (It's Ok to convert opencv, but I don't know how to convert the others)?
import torch.nn.functional as F
train_tfms = transforms.Compose([transforms.ToTensor(), transforms.Normalize(channel_means, channel_stds)])
input_width, input_height = input_size[0], input_size[1]
img_1 = cv.resize(img, (input_width, input_height), cv.INTER_AREA)
X = train_tfms(Image.fromarray(img_1))
X = Variable(X.unsqueeze(0)).cuda() # [N, 1, H, W]
mask = model(X)
mask = F.sigmoid(mask[0, 0]).data.cpu().numpy()
mask = cv.resize(mask, (img_width, img_height), cv.INTER_AREA)
| To create the transformed dataset, you will need to call MapDataset<DatasetType, TransformType> map(DatasetType dataset,TransformType transform) (see doc).
You will likely have to implement your 2 transforms yourself, just look at how they implemented theirs and imitate that.
The libtorch tutorial will guide you through datasets and dataloaders
You can call the sigmoid function with torch::nn::functionql::sigmoid I believe
| https://stackoverflow.com/questions/73235815/ |
What does out_channels in Conv2d represent? | import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = torch.flatten(x, 1) # flatten all dimensions except batch
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
I am taking a look at PyTorch Blitz and in the conv1 layer we can see the input_channels=3 because it's the first image so it just has its 3 RGB channels and out_channels=6.
Does that mean the number of filters I have are 6? In which case it'd mean the total number of feature maps I would get are 6*3==18? But if that is the case why in conv2 am I plugging in input_channels=6, shouldn't I be plugging in 18 because that was the output from the previous Convolutional layer?
| No, you get the number of out_channels (that IS the number of feature maps). So, if you start of with 3 representations of your data - i.e., your input channels, you can chose how many representations you want after the convolutional operation, in this case you specified 6. Naturally, in the next layer, you'll have 6 as input as a result.
It sounds like you don't fully grasp how convolutional neural networks work internally, look at some explanations like here.
If you apply your case to the picture from that website, you'd have 6 different filters, leading to 6 output channels. The number you pick, is up to you!
| https://stackoverflow.com/questions/73237567/ |
PyTorch: Fully Connected Layer has no Parameters | I am very new at PyTorch so please excuse my ignorance. I am trying to create my own CNN using PyTorch. The problem is that my Fully Connected Layer (i.e. the LazyLinear function) is showing no learnable parameters and the network is obviously not learning anything.
import torch
from torch import nn
import pytorch_lightning as pl
from pytorch_lightning.core.decorators import auto_move_data
class ThreeConvLayer(pl.LightningModule):
def __init__(self, num_classes, num_images):
super(ThreeConvLayer, self).__init__()
self.convolutionlayer1 = nn.Conv2d(in_channels=1, out_channels=16, kernel_size=3, padding=1)
self.BatchNormalization1 = nn.BatchNorm2d(16)
self.ReLU1 = nn.ReLU()
self.maxpool1 = nn.MaxPool2d(kernel_size = 2, stride = 2)
self.convolutionlayer2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1)
self.BatchNormalization2 = nn.BatchNorm2d(32)
self.ReLU2 = nn.ReLU()
self.maxpool2 = nn.MaxPool2d(kernel_size = 2, stride=2)
self.convolutionlayer3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1)
self.BatchNormalization3 = nn.BatchNorm2d(64)
self.ReLU3 = nn.ReLU()
self.fc1 = nn.LazyLinear(num_classes)
self.softmax = nn.Softmax(dim=1)
self.loss = nn.CrossEntropyLoss()
def forward(self, x):
#print('shape x: ', x.shape)
out = self.convolutionlayer1(x)
out = self.BatchNormalization1(out)
out = self.ReLU1(out)
out = self.maxpool1(out)
# print('shape out1: ', out.shape)
out = self.convolutionlayer2(out)
out = self.BatchNormalization2(out)
out = self.ReLU2(out)
out = self.maxpool2(out)
#print('shape out2: ', out.shape)
out = self.convolutionlayer3(out)
out = self.BatchNormalization3(out)
out = self.ReLU3(out)
#print('shape out3: ', out.shape)
out = out.reshape(out.size(0), -1)
#print('out after reshpae: ', out.shape)
out = self.fc1(out)
out = self.softmax(out)
#print('final out: ', out.shape)
return out
def training_step(self, batch, batch_no):
# implement single training step
x, y = batch
y = y.long()
logits = self(x)
loss = self.loss(logits, y)
self.log('val_loss', loss)
return loss
def configure_optimizers(self):
# choose your optimizer
return torch.optim.RMSprop(self.parameters(), lr=0.05) #lr=0.005
Here is the PyTorch printout on learnable parameters:
| Name | Type | Params
----------------------------------------------------------
0 | convolutionlayer1 | Conv2d | 160
1 | BatchNormalization1 | BatchNorm2d | 32
2 | ReLU1 | ReLU | 0
3 | maxpool1 | MaxPool2d | 0
4 | convolutionlayer2 | Conv2d | 4.6 K
5 | BatchNormalization2 | BatchNorm2d | 64
6 | ReLU2 | ReLU | 0
7 | maxpool2 | MaxPool2d | 0
8 | convolutionlayer3 | Conv2d | 18.5 K
9 | BatchNormalization3 | BatchNorm2d | 128
10 | ReLU3 | ReLU | 0
11 | fc1 | LazyLinear | 0
12 | softmax | Softmax | 0
13 | loss | CrossEntropyLoss | 0
----------------------------------------------------------
Here you can see that the FullyConnected Layer has no parameters which is clearly wrong. What did I do wrong here?
| This is one limitation of lazy modules such as LazyLinear. If you read through the documentation of nn.modules.lazy.LazyModuleMixin, you will see:
Modules that lazily initialize parameters, or βlazy modulesβ, derive the shapes of their parameters from the first input(s) to their forward method. Until that first forward they contain torch.nn.UninitializedParameters that should not be accessed or used, and afterward they contain regular torch.nn.Parameters.
In other words, you need to first perform a dry run with random data before you can proceed with your calls. This is required because lazy modules infer the missing arguments (such as in_features for nn.Linear) after the first inference call, i.e. based on the shape of the first input it receives.
getting the number of parameters registered.
properly register them inside an optimizer.
| https://stackoverflow.com/questions/73239018/ |
How do the transposed convolutional layer forward and backward passes work? | Before I present my problem, I want to apologize for those of you that feel this is more of a math post than a programming post. Neural networks are both mathematic and programming heavy, and I felt my problem was in the programming side. I have created a CNN from scratch in c++ (that works). For this reason, I feel as though the functions I use to create a convolution and a full convolution are correct. Programmatically below, I am going to show how I do the basic forward and backward of a CNN with a convolutional layer being the forward:
Matrix<float> cnn_forward(Matrix<float> weight, Matrix<float> prev){
Matrix<float> output = prev.convolute(weight);
return output;
}
And the backward pass (I am not using a bias or activation function in this case):
cnn_back cnn_backward(Matrix<float> a_prev, Matrix<float> dz, Matrix<float> kernel){
Matrix<float> rotated = kernel.rotate_180();
Matrix<float> dx = dz.convolute_full(rotated);
Matrix<float> dw = a_prev.convolute(dz);
cnn_back output;
output.dw = std::move(dw);
output.dx = std::move(dx);
return output;
}
Everything that I have seen online says that the transposed convolutional layer is just the reverse of the convolutional layer. So, I have tried implementing the following as the forward and backward passes of a transposed convolutional layer.
//forward
Matrix<float> fcn_forward(Matrix<float> weight, Matrix<float> prev){
Matrix<float> output = prev.convolute_full(weight.rotate_180());
return output;
}
//backward
fcn_back fcn_backward(Matrix<float> a_prev, Matrix<float> dz, Matrix<float> kernel){
Matrix<float> dx = dz.convolute(kernel);
Matrix<float> dw = dz.convolute(a_prev);
fcn_back output;
output.dw = std::move(dw);
output.dx = std::move(dx);
return output;
}
//again, not using a bias or activation function
My goal is to basically implement torch.nn.ConvTranspose2d from pytorch with 2 dimensional matrices. I was hoping to parallel it to the basic convolution formula that I have above.
~EDIT~
This would be the translation into python using numpy arrays which is pretty much an exact replica of my c++ code.
def convolute(X, W, strides=(1,1)):
new_row = (int)((X.shape[0] - W.shape[0])/strides[0] +1)
new_col = (int)((X.shape[1] - W.shape[1])/strides[1] +1)
out = np.zeros((new_row, new_col), dtype=float)
x_last = 0
y_last = 0
for x in range(0, X.shape[0]-(W.shape[0] - 1), strides[0]):
for y in range(0, X.shape[1]-(W.shape[1] - 1), strides[1]):
amt = 0.0
for i in range(0, W.shape[0]):
for j in range(0, W.shape[1]):
amt += W[i][j] * X[x+i][y+j]
out[x_last][y_last] = amt
y_last += 1
x_last += 1
y_last = 0
return out
def convolute_full(X, W, strides=(1, 1)):
row_num = (X.shape[0] - 1) * strides[0] + W.shape[0]
col_num = (X.shape[1] - 1) * strides[1] + W.shape[1]
output = np.zeros([row_num, col_num])
for i in range(0, X.shape[0]):
i_prime = i * strides[0]
for j in range(0, X.shape[1]):
j_prime = j * strides[1]
for k_row in range(W.shape[0]):
for k_col in range(W.shape[1]):
output[i_prime+k_row, j_prime+k_col] += W[k_row, k_col] * X[i, j]
return output
def get_errors(predicted, label):
return label - predicted
def fcn_forward(weight, prev):
rotated = np.rot90(np.rot90(weight))
output = convolute_full(prev, rotated)
return output
def fcn_backward(a_prev, dz, kernel):
dx = convolute(dz, kernel)
dw = convolute(dz, a_prev)
dx = np.clip(dx, 10, -10)
return dx, dw
def forward(weights, X_init):
values = []
values.append(X_init)
predicted = fcn_forward(weights[0], X_init)
values.append(predicted)
predicted = fcn_forward(weights[1], predicted)
values.append(predicted)
return values
def backward(weights, values, label, learningRate=0.001):
dz = get_errors(values[-1], label)
dx, dw = fcn_backward(values[-2], dz, weights[-1])
weights[-1] = weights[-1] - learningRate*dw
dz = dx
dx, dw = fcn_backward(values[-3], dz, weights[-2])
weights[-2] = weights[-2] - learningRate*dw
return weights
def train_example():
epoch = int(input("enter epoch: "))
#creating a random input
inp = np.random.randn(10,10)
#creating the weight matricies
weights = [np.random.randn(3,3), np.random.randn(3,3)]
#creating the wanted output
label = np.random.randn(14,14)
for i in range(0, epoch):
values = forward(weights, inp)
if(i == 0 or i == 1):
errors = get_errors(values[-1], label)
print("errors:")
print(errors)
print("error sum: ", np.sum(errors))
weights = backward(weights, values, label)
print("current prediction:")
print(values[-1])
print("label: ")
print(label)
errors = get_errors(values[-1], label)
print("errors:")
print(errors)
print("error sum at end of training: ", np.sum(errors))
Basically, this does not work. The weights are not corrected in the correct way. The errors only continue to get larger (the opposite of the wanted result). What is the correct way to forward and backward propagate a transposed convolutional layer?
EDIT
This is the answer for anyone wondering how it relates to my code above, due to @Bob's answer:
def convolute(X, W, strides=(1,1)):
new_row = (int)((X.shape[0] - W.shape[0])/strides[0] +1)
new_col = (int)((X.shape[1] - W.shape[1])/strides[1] +1)
out = np.zeros((new_row, new_col), dtype=float)
x_last = 0
y_last = 0
for x in range(0, X.shape[0]-(W.shape[0] - 1), strides[0]):
for y in range(0, X.shape[1]-(W.shape[1] - 1), strides[1]):
amt = 0.0
for i in range(0, W.shape[0]):
for j in range(0, W.shape[1]):
amt += W[i][j] * X[x+i][y+j]
out[x_last][y_last] = amt
y_last += 1
x_last += 1
y_last = 0
return out
#this is the same result as scipy.signal.convolute2d
def convolute_full(X, W, strides=(1, 1)):
row_num = (X.shape[0] - 1) * strides[0] + W.shape[0]
col_num = (X.shape[1] - 1) * strides[1] + W.shape[1]
output = np.zeros([row_num, col_num])
for i in range(0, X.shape[0]):
i_prime = i * strides[0]
for j in range(0, X.shape[1]):
j_prime = j * strides[1]
for k_row in range(W.shape[0]):
for k_col in range(W.shape[1]):
output[i_prime+k_row, j_prime+k_col] += W[k_row, k_col] * X[i, j]
return output
def convolute_full_backward(X, dZ, dW, strides=(1, 1)):
for i in range(0, X.shape[0]):
i_prime = i * strides[0]
for j in range(0, X.shape[1]):
j_prime = j * strides[1]
for k_row in range(dW.shape[0]):
for k_col in range(dW.shape[1]):
dW[k_row, k_col] += dZ[i_prime+k_row, j_prime+k_col] * X[i, j]
return dW
def get_errors(predicted, label):
return label - predicted
def fcn_forward(W, X):
rotated = np.rot90(np.rot90(W))
output = convolute_full(X, rotated)
return output
def fcn_backward(X, dZ, kernel):
dw = np.zeros(kernel.shape)
dw = convolute_full_backward(X, dZ, dw)
dw = np.rot90(np.rot90(dw))
dx = convolute(dZ, np.rot90(np.rot90(kernel)))
np.clip(dx, 10, -10)
return dx, dw
def forward(weights, X):
values = []
values.append(X)
predicted = fcn_forward(weights[0], X)
values.append(predicted)
predicted = fcn_forward(weights[1], predicted)
values.append(predicted)
return values
def backward(weights, values, label, learningRate=0.001):
dz = get_errors(values[-1], label)
dx, dw = fcn_backward(values[-2], dz, weights[-1])
weights[-1] = weights[-1] + learningRate*dw
dz = dx
dx, dw = fcn_backward(values[-3], dz, weights[-2])
#new apply dw:
weights[-2] = weights[-2] + learningRate*dw
return weights
def train_example():
epoch = int(input("please enter epoch: "))
inp = np.random.randn(10,10)
weights = [np.random.randn(3,3), np.random.randn(3,3)]
label = np.random.randn(14,14)
for i in range(0, epoch):
values = forward(weights, inp)
errors = get_errors(values[-1], label)
print("error sum at {} is: {}".format(i, np.sum(errors)))
weights = backward(weights, values, label)
errors = get_errors(values[-1], label)
print("error sum at end of training: ", np.sum(errors))
| since your implementation has every scalar multiplication performed explicitly, the backward step can be done very clear. You keep all the loops unchanged, and when you see an update to your accumulator you compute the gradient for that.
import numpy as np
def convolute_full(X, W, strides=(1, 1)):
row_num = (X.shape[0] - 1) * strides[0] + W.shape[0]
col_num = (X.shape[1] - 1) * strides[1] + W.shape[1]
output = np.zeros([row_num, col_num])
for i in range(0, X.shape[0]):
i_prime = i * strides[0]
for j in range(0, X.shape[1]):
j_prime = j * strides[1]
for k_row in range(W.shape[0]):
for k_col in range(W.shape[1]):
output[i_prime+k_row, j_prime+k_col] += W[k_row, k_col] * X[i, j]
return output
def convolute_full_backward(X, dZ, dW, strides=(1, 1)):
row_num = (X.shape[0] - 1) * strides[0] + W.shape[0]
col_num = (X.shape[1] - 1) * strides[1] + W.shape[1]
output = np.zeros([row_num, col_num])
for i in range(0, X.shape[0]):
i_prime = i * strides[0]
for j in range(0, X.shape[1]):
j_prime = j * strides[1]
for k_row in range(W.shape[0]):
for k_col in range(W.shape[1]):
# Only this line changed compard to forward pass
dW[k_row, k_col] += dZ[i_prime+k_row, j_prime+k_col] * X[i, j]
def fcn_forward(X, W):
output = convolute_full(X, W[::-1,::-1])
return output
def fcn_backward(X, dZ, kernel_shape):
dW = np.zeros(kernel_shape)
convolute_full_backward(X, dZ, dW[::-1,::-1])
return dW
To validate I created a simple example with a linear loss function
X = np.random.randn(20, 20)
W = np.random.randn(5, 5)
Z = fcn_forward(X, W)
# pick a random loss with known gradient
dZ = np.random.randn(*Z.shape)
F = np.sum(Z * dZ)
dW = fcn_backward(X, dZ, W.shape)
# random perturbation
W_ = W + np.random.randn(*W.shape)
# expected change to the loss function
dF = np.sum(dW * (W_ - W))
Z_ = fcn_forward(X, W_)
F_ = np.sum(Z_ * dZ)
print('Predicted loss change: %f' % dF)
print('Actual loss change: %f' % (F_ - F))
Run and see.
| https://stackoverflow.com/questions/73239372/ |
Use torch.gather to select images from tensor | I have a tensor of images of size (3600, 32, 32, 3) and I have a multi hot tensor [0, 1, 1, 0, ...] of size (3600, 1). I am looking to basically selecting images that correspond to a 1 in the multi hot tensor. I am trying to understand how to use torch.gather:
tensorA.gather(0, tensorB)
Gives me issues with dims and I can't properly understand how to reshape them.
| When using torch.gather, the dimension of input and dimension of index must be the same. And the index is not a multi hot tensor, but the location of the desired value.
You can slice the tensor by using the index of the multi hot tensor. The fourth line finds the index with a value of 1 in the multi hot tensor. The fifth line slices the image based on the index.
Code:
tensorA = torch.randn(4, 32, 32, 3)
tensorB = torch.tensor([0,1,1,0])
tensorB_where = torch.where(tensorB == 1)[0]
result = tensorA[tensorB_where]
| https://stackoverflow.com/questions/73242380/ |
Multiple arithmetic operations on single tensor | For a 2D tensor with even and odd numbers, I would like to
do different arithmetic operation depending on if the number
in the tensor is even or odd. I've created the tensor and created
a corresponding true false (even or odd) tensor, but am not sure how to proceed.
import torch
list1 = [
[10, 25, 75, 10, 50],
[25, 30, 35, 40, 30],
[45, 50, 55, 60, 20],
[50, 20, 15, 20, 10],
[10, 25, 40, 50, 35]]
tensor2 = torch.tensor(list1)
tensor3=tensor2 % 2
print(tensor3)
print(torch.eq(tensor3, 0)) #even numbers
print(torch.eq(tensor3, 1)) #odd numbers
#do 3x+1 for odd numbers, ie the tensor where indexes are false for even
#do x/2 for even numbers, ie the tensor where indexes are true for even
| You're looking for torch.where
In your case the code would be:
list1 = [
[10, 25, 75, 10, 50],
[25, 30, 35, 40, 30],
[45, 50, 55, 60, 20],
[50, 20, 15, 20, 10],
[10, 25, 40, 50, 35]]
tensor2 = torch.tensor(list1, type = torch.float64)
res = torch.where(tensor2 % 2 == 0, tensor2 / 2, tensor2 * 3 + 1)
>>> res
tensor([[ 5., 76., 226., 5., 25.],
[ 76., 15., 106., 20., 15.],
[136., 25., 166., 30., 10.],
[ 25., 10., 46., 10., 5.],
[ 5., 76., 20., 25., 106.]], dtype=torch.float64)
| https://stackoverflow.com/questions/73243471/ |
Convert multirelational graphs to bipartite graphs with networkx | I have a multi-relational graph G (subject s and object o nodes connected with an edge having a predicate label p), made with networkx.DiGraph. Is there a way to easily and elegantly create its bipartite graph by replacing each labeled edge (s, p, o) with two unlabeled edges {(s,p),(p,o)}? This operation is also called Levi transformation (Levi, 1942) and is aimed to treat each entity and relation equally.
Current graph construction example:
amr_graph = networkx.DiGraph()
for node_id, node_string in amr.nodes.items():
amr_graph.add_node(node_id, name=node_string)
for subj, pred, obj in amr.edges:
amr_graph.add_edge(subj, obj, key=pred)
| Just create the new edges as you see fit:
import random
import networkx as nx
s=[random.randint(0,2) for i in range(10)]
o=[random.randint(3,5) for i in range(10)]
p=[random.randint(6,8) for i in range(10)]
G = nx.DiGraph()
H = nx.DiGraph()
F = nx.DiGraph()
#split while constructing the orgiginal graph
for subj, pred, obj in zip(s,p,o):
G.add_edge(subj, obj, key= pred)
H.add_edge(subj, pred, key = obj)
H.add_edge(pred, obj, key= subj)
#use existing graph to split edges
for subj, obj, d in G.edges(data=True):
pred = d['key']
F.add_edge(subj, pred, key = obj)
F.add_edge(pred, obj, key= subj)
| https://stackoverflow.com/questions/73245817/ |
"Extracting" the indices tensor from sparse torch tensor | Given a torch tensor A with sparse entries (say, for example, the adjacency matrix of a graph), we can construct a sparse tensor from A by using the function to_sparse().
For example:
A_sparse = A.to_sparse()
>>> tensor(indices=tensor([[ 0, 0, 0, ..., 2707, 2707, 2707],
[ 633, 1862, 2582, ..., 598, 1473, 2706]]),
values=tensor([1., 1., 1., ..., 1., 1., 1.]),
size=(2708, 2708), nnz=10556, layout=torch.sparse_coo)
But note that:
A_sparse.shape
>>> torch.Size([2708, 2708])
What I would like is to only obtain the indices tensor in the above "tuple", that is to say a tensor of shape (2,10556).
I have tried A_sparse[0]and A_sparce[indices] but neither method returns the expected result.
| Following skyzip's comment, it is sufficient to call A_sparse.indices()
| https://stackoverflow.com/questions/73247471/ |
RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback): initialization failed | Goal: Run a GPT-2 model instance.
I am using the latest Tensorflow and Hugging Face Transformers.
Tensorflow - 2.9.1
Transformers - 4.21.1
Notebook:
pip install tensorflow
pip install transformers
from transformers import pipeline, set_seed
generator = pipeline('text-generation', model='gpt2')
set_seed(42)
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
RuntimeError: module compiled against API version 0xe but this version of numpy is 0xd
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
ImportError: numpy.core.multiarray failed to import
The above exception was the direct cause of the following exception:
SystemError Traceback (most recent call last)
SystemError: <built-in method __contains__ of dict object at 0x7f5b58a64d00> returned a result with an error set
The above exception was the direct cause of the following exception:
ImportError Traceback (most recent call last)
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/utils/import_utils.py in _get_module(self, module_name)
1001 try:
-> 1002 return importlib.import_module("." + module_name, self.__name__)
1003 except Exception as e:
~/anaconda3/envs/python3/lib/python3.8/importlib/__init__.py in import_module(name, package)
126 level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)
128
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _gcd_import(name, package, level)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _find_and_load(name, import_)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _load_unlocked(spec)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap_external.py in exec_module(self, module)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/pipelines/__init__.py in <module>
36 from ..utils import HUGGINGFACE_CO_RESOLVE_ENDPOINT, http_get, is_tf_available, is_torch_available, logging
---> 37 from .audio_classification import AudioClassificationPipeline
38 from .automatic_speech_recognition import AutomaticSpeechRecognitionPipeline
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/pipelines/audio_classification.py in <module>
19 from ..utils import add_end_docstrings, is_torch_available, logging
---> 20 from .base import PIPELINE_INIT_ARGS, Pipeline
21
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/pipelines/base.py in <module>
33 from ..feature_extraction_utils import PreTrainedFeatureExtractor
---> 34 from ..modelcard import ModelCard
35 from ..models.auto.configuration_auto import AutoConfig
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/modelcard.py in <module>
43 )
---> 44 from .training_args import ParallelMode
45 from .utils import (
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/training_args.py in <module>
25 from .debug_utils import DebugOption
---> 26 from .trainer_utils import (
27 EvaluationStrategy,
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/trainer_utils.py in <module>
46 if is_tf_available():
---> 47 import tensorflow as tf
48
~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/__init__.py in <module>
36
---> 37 from tensorflow.python.tools import module_util as _module_util
38 from tensorflow.python.util.lazy_loader import LazyLoader as _LazyLoader
~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/python/__init__.py in <module>
36 from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
---> 37 from tensorflow.python.eager import context
38
~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/python/eager/context.py in <module>
34 from tensorflow.python import tf2
---> 35 from tensorflow.python.client import pywrap_tf_session
36 from tensorflow.python.eager import executor
~/anaconda3/envs/python3/lib/python3.8/site-packages/tensorflow/python/client/pywrap_tf_session.py in <module>
18 from tensorflow.python import pywrap_tensorflow
---> 19 from tensorflow.python.client._pywrap_tf_session import *
20 from tensorflow.python.client._pywrap_tf_session import _TF_SetTarget
ImportError: initialization failed
The above exception was the direct cause of the following exception:
RuntimeError Traceback (most recent call last)
/tmp/ipykernel_4924/2487422996.py in <cell line: 1>()
----> 1 from transformers import pipeline, set_seed
2
3 generator = pipeline('text-generation', model='gpt2')
4 set_seed(42)
~/anaconda3/envs/python3/lib/python3.8/importlib/_bootstrap.py in _handle_fromlist(module, fromlist, import_, recursive)
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/utils/import_utils.py in __getattr__(self, name)
990 value = self._get_module(name)
991 elif name in self._class_to_module.keys():
--> 992 module = self._get_module(self._class_to_module[name])
993 value = getattr(module, name)
994 else:
~/anaconda3/envs/python3/lib/python3.8/site-packages/transformers/utils/import_utils.py in _get_module(self, module_name)
1002 return importlib.import_module("." + module_name, self.__name__)
1003 except Exception as e:
-> 1004 raise RuntimeError(
1005 f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
1006 f" traceback):\n{e}"
RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback):
initialization failed
def query(payload, multiple, min_tokens, max_tokens):
nlp_setup()
list_dict = generator(payload, min_length=min_tokens, max_new_tokens=max_tokens, num_return_sequences=multiple)
return [d['generated_text'].split(payload)[1].strip() for d in list_dict
output = query("Banking customer's needs:", 3000, 50, 50)
RunTime, SystemError and ImportError all occur during import of transformers:
RuntimeError: Failed to import transformers.pipelines because of the following error (look up to see its traceback): initialization failed
| Changed Kernel: conda_tensorflow2_p38
| https://stackoverflow.com/questions/73247922/ |
Check if tensor is in list | I can do the following with a single int to retrieve a bool tensor:
import torch
a = torch.tensor([1,2,3])
a != 2
#tensor([ True, False, True])
Can I do the same with a list in plain pytorch? I.e.:
import torch
a = torch.tensor([1,2,3])
a not in [2,3]
#tensor([ True, False, False])
Thanks a lot for your time!
| I think you want torch.isin
out = ~torch.isin(a, torch.tensor([2, 3]))
# or
out = torch.isin(a, torch.tensor([2, 3]), invert=True)
print(out)
tensor([ True, False, False])
| https://stackoverflow.com/questions/73248034/ |
How do I tie embeddings between a `torch.nn.Embedding` and `torch.nn.EmbeddingBag`? | I'd like to tie the embedding layers between two parts of my neural network: one which embeds tokens where order matters (i.e., nn.Embedding) and one which embeds tokens where order doesn't matter (i.e., nn.EmbeddingBag). I ran into numerical stability issues when creating my own EmbeddingBag-like object and doing the reduction myself so I'd like to use the officially support nn.EmbeddingBag; however, it seems like my attempt to tie weights (below) doesn't work
#!/usr/bin/env python3
import torch
import torch.nn as nn
if __name__ == "__main__":
V, max_seq, padding_idx, emb_dim, B = 10, 100, 1, 512, 32
# Create an embedding layer and initialize an embeddingbag with those weights
emb_layer = nn.Embedding(V, emb_dim, padding_idx=padding_idx)
emb_bag = nn.EmbeddingBag.from_pretrained(emb_layer.weight, freeze=False, padding_idx=padding_idx)
tokens = torch.randint(0, V, (B, max_seq))
y = torch.randn((B, emb_dim))
loss = nn.MSELoss()
# backprop through the embedding bag
y_ = emb_bag(tokens)
l = loss(y_, y)
assert emb_bag.weight.grad is None
l.backward()
assert emb_bag.weight.grad is not None
# if we're tying weights, backpropping through the emb bag should
# yield the same gradients in the embedding layer, but... the following assertion fails
assert emb_layer.weight.grad is not None and \
torch.allclose(emb_bag.weight.grad, emb_layer.weight.grad)
Is there some way to tie the weights in both or do I need to be creative with how I emulate the embeddingbag behavior?
| from_pretrained() will copy the weights: emb_layer.weight is emb_bag.weight will be False.
You can just set the weight attribute directly:
emb_bag.weight = emb_layer.weight
| https://stackoverflow.com/questions/73249914/ |
PyTorch: CUDA is not available | I'm trying to run PyTorch on a NVIDIA Jetson Nano and my project requires me to use CUDA. I'm running on Ubuntu 18.04 and Python 3.10.6. I followed this guide to install CUDA 11.6. Then using the instructions on PyTorch.org I installed PyTorch using this command:
pip install torch==1.12.0 torchvision==0.13.0 --extra-index-url https://download.pytorch.org/whl/cu116
But then when I try to verify it, it's not available:
(env) $ python
Python 3.10.6 (main, Aug 2 2022, 15:11:03) [GCC 7.5.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> torch.cuda.is_available()
False
>>>
here's the CUDA version:
(env) $ nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2021 NVIDIA Corporation
Built on Fri_Dec_17_18:16:35_PST_2021
Cuda compilation tools, release 11.6, V11.6.55
Build cuda_11.6.r11.6/compiler.30794723_0
And here is some information from PyTorch. Notice how it says CUDA used to build PyTorch: Could not collect.
(env) $ python -m torch.utils.collect_env
PyTorch version: 1.12.0
Is debug build: False
CUDA used to build PyTorch: Could not collect
ROCM used to build PyTorch: N/A
OS: Ubuntu 18.04.6 LTS (aarch64)
GCC version: (Ubuntu/Linaro 7.5.0-3ubuntu1~18.04) 7.5.0
Clang version: Could not collect
CMake version: version 3.10.2
Libc version: glibc-2.27
Python version: 3.10.6 (main, Aug 2 2022, 15:11:03) [GCC 7.5.0] (64-bit runtime)
Python platform: Linux-4.9.253-tegra-aarch64-with-glibc2.27
Is CUDA available: False
CUDA runtime version: 11.6.55
GPU models and configuration: Could not collect
Nvidia driver version: Could not collect
cuDNN version: Probably one of the following:
/usr/lib/aarch64-linux-gnu/libcudnn.so.8.2.1
/usr/lib/aarch64-linux-gnu/libcudnn_adv_infer.so.8.2.1
/usr/lib/aarch64-linux-gnu/libcudnn_adv_train.so.8.2.1
/usr/lib/aarch64-linux-gnu/libcudnn_cnn_infer.so.8.2.1
/usr/lib/aarch64-linux-gnu/libcudnn_cnn_train.so.8.2.1
/usr/lib/aarch64-linux-gnu/libcudnn_ops_infer.so.8.2.1
/usr/lib/aarch64-linux-gnu/libcudnn_ops_train.so.8.2.1
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
Versions of relevant libraries:
[pip3] numpy==1.23.1
[pip3] torch==1.12.0
[pip3] torchvision==0.13.0
[conda] Could not collect
Any help is appreciated. Thanks.
| Downloading the compiled whl file from nvidia and installing it with pip did the trick (as suggested by @FlyingTeller).
wget https://nvidia.box.com/shared/static/p57jwntv436lfrd78inwl7iml6p13fzh.whl -O torch-1.8.0-cp36-cp36m-linux_aarch64.whl
pip install numpy torch-1.8.0-cp36-cp36m-linux_aarch64.whl
| https://stackoverflow.com/questions/73250147/ |
Convert from RGB to LAB using pytorch? Opencv's color conversion does not match their own formula | In order to speed up some of my past opencv/numpy powered operations, I am attempting to translate them to PyTorch, to run on GPU. One of the first of these steps it RGB to LAB conversion.
I referred to:
the opencv documentation on their own color conversion
the Wikipedia page on CIE Lab, which offers one version of the algorithm (consistent with opencv's version when accounting for some refactoring and different XYZ starting ranges)
this implementation from EdgeFool, which is already in PyTorch, but expects different value ranges and tensor shapes.
I have managed to produce this code:
import torch
def tensor_like(source_data, target_tensor):
return torch.tensor(
source_data,
device=target_tensor.device,
dtype=target_tensor.dtype,
)
RGB_TO_XYZ_FACTOR_MATRIX = [
[0.412453, 0.357580, 0.180423],
[0.212671, 0.715160, 0.072169],
[0.019334, 0.119193, 0.950227],
]
def cie_f(input_: torch.Tensor):
e = 6 / 29
return torch.where(
input_ > e ** 3,
input_ ** (1 / 3),
input_ / (3 * e ** 2) + 4 / 29,
)
def tensor_rgb_to_lab(input_: torch.Tensor):
# input_ is expected to be RGB 0-255, and of shape B, C, H, W
# Implemented based on formulas written here (may need to scroll down):
# https://docs.opencv.org/4.x/de/d25/imgproc_color_conversions.html
dtype = input_.dtype
if not torch.is_floating_point(input_):
input_ = input_.float()
input_ = input_.permute(0, 2, 3, 1)
rgb_colors = input_.reshape(-1, 3)
rgb_colors /= 255.0
# RGB -> XYZ
factor_matrix = tensor_like(RGB_TO_XYZ_FACTOR_MATRIX, rgb_colors)
xyz_colors = torch.mm(rgb_colors, factor_matrix.T)
# xyz_colors.mul_(255)
# XYZ -> LAB
xyz_colors *= tensor_like([1 / 0.950456, 1.0, 1 / 1.088754], xyz_colors)
f_xyz_colors = cie_f(xyz_colors)
fxyz_to_lab_factor_matrix = tensor_like([
[0.0, 500.0, 0.0],
[116.0, -500.0, 200.0],
[0.0, 0.0, -200.0],
], f_xyz_colors)
lab_colors = torch.mm(f_xyz_colors, fxyz_to_lab_factor_matrix)
lab_colors += tensor_like([-16, 128, 128], lab_colors)
lab_colors[:, 0] *= 255 / 100
lab_colors = lab_colors.view_as(input_).permute(0, 3, 1, 2)
lab_colors = lab_colors.round_().clamp_(0, 255).type(dtype)
return lab_colors
When comparing my output against cv2.cvtColor(image, cv2.COLOR_RGB2LAB), my code does produce the correct results with RGB colors like (000, 000, 000), (255, 255, 255), (000, 255, 255), (255, 000, 255), (255, 255, 000), (255, 000, 000), (000, 255, 000), (000, 000, 255), but it fails on many other cases (more than 99% of RGB colors, according to my test).
One such failing case is RGB(128, 128, 128), which open-cv says corresponds to Lab(137, 128, 128), but my code indicates Lab(194, 128, 128). This is an interesting failing case since only 1 value is wrong, and I can manually go through the different steps of the formula for L only in an attempt to isolate the problem:
g = np.array((0.412453+0.357580+0.180423, 0.212671+0.715160+0.072169,0.019334+0.119193+0.950227)) * 128/255
g[0]/=0.950456
g[2]/=1.088754
# g => array([0.50196078, 0.50196078, 0.50196078]). Makes sense since 128/255=0.50196078
l = 116*g[1]**(1/3)-16 # since 0.50196078>0.008856
# l => 76.18945600835188 This is already wrong according to online RGB converters
l *= 255/100
# l => 194.2831128212973 This contradicts opencv's value and correlates with mine
After quadruple-checking my code, I was starting to think opencv might have a bug/rounding error in their code, or that they were doing an extra step differently than they say on their documentation. So I have looked up some online RGB to Lab converters (1 and 2), and after re-adjusting the output L value to the 255 range, they agree with opencv. I guess this really points to a mistake on my part (unless the websites internally rely on opencv?).
Considering how the result comes out correct for RGB values of both 0 and 255 (or 0 and 1 when scaled to 0..1), I think that all of the ax+b operations must be correct, and the t**(1/3) must be the issue... could the industry be somehow using a different exponent, maybe due to performance benefit?
What am I missing here?
I am using opencv 4.4.0.46
| Instead of implementing this conversion yourself, you can use kornia's implementation: kornia.color.rgb_to_lab(image) seems to do exactly what you are trying to do in your tensor_rgb_to_lab function.
If you insist, you can checkout their implementation here.
| https://stackoverflow.com/questions/73256602/ |
pytorch, for the cross_entropy function, What if the input labels are all ignore_index? | for the nn.CrossEntropyLoss(), What if the input labels are all ignore_index ? I got a 'nan' loss, how to fix it ? thanks!
detail of my code is following:
code
notice that IGNORE_INDEX is -100
then, the loss_ent becomes 'nan', the input of func criterion() is following:
criterion's input
my python environment is following:
Python:3.7.11
torch:1.12.0+cu116
GPU:NVIDIA A100 80G
thank for your attention, Please let me know if there is anything else I need to provide.
| There seem to be two possibilities.
This is the code to help understand the ignore index. If you set all inputs to ignore index, criterion makes nan as output because there is no value to compute.
import torch
import torch.nn as nn
x = torch.randn(5, 10, requires_grad=True)
y = torch.ones(5).long() * (-100)
criterion = nn.CrossEntropyLoss(ignore_index=-100)
loss = criterion(x, y)
print(loss)
tensor(nan, grad_fn=<NllLossBackward0>)
However, if there is even one value to calculate, the loss is calculated properly.
import torch
import torch.nn as nn
x = torch.randn(5, 10, requires_grad=True)
y = torch.ones(5).long() * (-100)
y[0] = 1
criterion = nn.CrossEntropyLoss(ignore_index=-100)
loss = criterion(x, y)
print(loss)
tensor(1.2483, grad_fn=<NllLossBackward0>)
It seems the learning rate is too large that cause diverge.
As you can see in the figure below, if the learning rate is large, the gradient gradually increases and diverges.
How about reducing the learning rate of the parameters of the model with is_gold_ent as output?
Usually, when reducing the learning rate, reduce it by 1/3. For example 0.01, 0.003, 0.001,...
| https://stackoverflow.com/questions/73258289/ |
How to set minimum k elements in a dimension in pytorch tensor to a specific value? | For example, if I have tensor (shape [2, 3, 5])
[[[0.8823, 0.9150, 0.3829, 0.9593, 0.3904],
[0.6009, 0.2566, 0.7936, 0.9408, 0.1332],
[0.9346, 0.5936, 0.8694, 0.5677, 0.7411]],
[[0.4294, 0.8854, 0.5739, 0.2666, 0.6274],
[0.2696, 0.4414, 0.2969, 0.8317, 0.1053],
[0.2695, 0.3588, 0.1994, 0.5472, 0.0062]]]
and k = 2, I want to set minimum k elements in a dimension (e.g., dim=2) to a specific value (e.g., 5):
[[[0.8823, 0.9150, 5, 0.9593, 5],
[0.6009, 5, 0.7936, 0.9408, 5],
[0.9346, 5, 0.8694, 5, 0.7411]],
[[5, 0.8854, 0.5739, 5, 0.6274],
[5, 0.4414, 0.2969, 0.8317, 5],
[0.2695, 0.3588, 5, 0.5472, 5]]]
| You can use a combination of torch.topk and torch.Tensor.scatter_.
(Bacause torch.topk return max_top_k and you want min_top_k. We can use -1*all_num for getting min_top_k)
val, ind = torch.topk(-a, k=2)
a.scatter_(index=ind, dim=-1, value=5)
print(a)
tensor([[[0.8823, 0.9150, 5.0000, 0.9593, 5.0000],
[0.6009, 5.0000, 0.7936, 0.9408, 5.0000],
[0.9346, 5.0000, 0.8694, 5.0000, 0.7411]],
[[5.0000, 0.8854, 0.5739, 5.0000, 0.6274],
[5.0000, 0.4414, 0.2969, 0.8317, 5.0000],
[0.2695, 0.3588, 5.0000, 0.5472, 5.0000]]])
Input:
>>> a = torch.tensor([[[0.8823, 0.9150, 0.3829, 0.9593, 0.3904],
[0.6009, 0.2566, 0.7936, 0.9408, 0.1332],
[0.9346, 0.5936, 0.8694, 0.5677, 0.7411]],
[[0.4294, 0.8854, 0.5739, 0.2666, 0.6274],
[0.2696, 0.4414, 0.2969, 0.8317, 0.1053],
[0.2695, 0.3588, 0.1994, 0.5472, 0.0062]]])
>>> torch.topk(-a, k=2)
# values=tensor(
# [[[-0.3829, -0.3904],
# [-0.1332, -0.2566],
# [-0.5677, -0.5936]],
# [[-0.2666, -0.4294],
# [-0.1053, -0.2696],
# [-0.0062, -0.1994]]]),
# indices=tensor(
# [[[2, 4],
# [4, 1],
# [3, 1]],
# [[3, 0],
# [4, 0],
# [4, 2]]])
| https://stackoverflow.com/questions/73261504/ |
How to return torch model weights from endpoint Flask | I'm developing a project in PyTorch which requires returning the weights (state_dict) of a pytorch model as a Flask endpoint response. To better explain it, the simplest code could be:
@app.endpoint('/send_weights', methods=['GET', 'POST'])
def send_weights():
model_weights = model.state_dict() # It is a dict[str, torch.tensor]
return model_weights
However it is not as simple because the torch.tensor is not JSON serializable, so, I've tried to convert them to a list (JSON serializable object) and it works:
@app.endpoint('/send_weights', methods=['GET', 'POST'])
def send_weights():
model_weights = model.state_dict() # It is a dict[str, torch.tensor]
model_weights = {k:v.tolist() for k,v in model_weights.items()}
return model_weights
However this process is very slow and it doesn't meet my requirements. I was trying to convert the tensors to bytes but the code gives the same problem, bytes is not JSON serializable. So, I'm thinking that the json response won't be the solution.
I'm not an expert in Flask but I've read about the flask send_file method, however I not sure how to use it in this case (not even sure this would be a possible solution), I haven't got a mimetype for the dictionary.
Does anybody know a better way to do this?
| I've just found a solution. It is based on return the weights as a file using the send_file method from flask with the weights saved on a binary using torch.save and the mimetype 'application/octet-stream' as appears in this question.
The final endopint code will be:
@app.endpoint('/send_weights', methods=['GET', 'POST'])
def send_weights():
model_weights = model.state_dict()
to_send = io.BytesIO()
torch.save(model_weights, to_send, _use_new_zipfile_serialization=False)
to_send.seek(0)
return send_file(to_send, mimetype='application/octet-stream')
And, to load it in the other side:
weights = torch.load(io.BytesIO(response.content))
Hope it will help somebody.
| https://stackoverflow.com/questions/73266620/ |
Multiple input model with PyTorch - input and output features | Good afternoon!
Iβm building a multiple-input model with 2 types of inputs:
Images (torch.Size([1, 3, 224, 224])) and landmark features (torch.Size([1, 96])).
Hereβs the model itself:
class MixedNetwork(nn.Module):
def __init__(self):
super(MixedNetwork, self).__init__()
image_modules = list(models.resnet50().children())[:-1]
self.image_features = nn.Sequential(*image_modules)
self.landmark_features = nn.Sequential(
nn.Linear(in_features=96, out_features=192,bias=False),
nn.ReLU(inplace=True),
nn.Dropout(p=0.25),
nn.Linear(in_features=192,out_features=1000,bias=False),
nn.ReLU(inplace=True),
nn.Dropout(p=0.25))
self.combined_features = nn.Sequential(
nn.Linear(1000, 512),
nn.ReLU(),
nn.Linear(512, 32),
nn.ReLU(),
nn.Linear(32,1))
def forward(self, image, landmarks):
a = self.image_features(image)
print(a.shape)
b = self.landmark_features(landmarks)
x = torch.cat((a.view(a.size(0), -1), b.view(b.size(0), -1)), dim=1)
x = self.combined_features(x)
x = F.sigmoid(x)
return x
Iβm getting confused when it comes to defining input-output features for Linear layers and combined layers. The last FC layer of resnet50 Linear(in_features=2048, out_features=1000). Does it mean that the last output of self.landmark_features layers also has to be 1000 and the first linear layer of self.combined_features should also be 1000?
Is it correct to assume that if the landmark input size is [1, 96] then the in_features for the first layer of self.landmark_features has to be 96?
With the current dimensions Iβm getting the error message:
RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x3048 and 1000x512)
(why 3048 and not 2048?)
| This code makes image shape(1, 3, 224, 224) to (1, 2048)
a = self.image_features(image)
a = a.view(a.size(0), -1)
And this code makes landmark features shape(1, 96) to (1,1000)
b = self.landmark_features(landmarks)
a = b.view(b.size(0), -1)
And torch cat makes concatenate a, b vectors. So, self.combined_features(x) in x's shape is (1, 3048)
So, the code should be changed to the following:
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision.models as models
import torch.nn.functional as F
class MixedNetwork(nn.Module):
def __init__(self):
super(MixedNetwork, self).__init__()
image_modules = list(models.resnet50().children())[:-1]
self.image_features = nn.Sequential(*image_modules)
self.landmark_features = nn.Sequential(
nn.Linear(in_features=96, out_features=192,bias=False),
nn.ReLU(inplace=True),
nn.Dropout(p=0.25),
nn.Linear(in_features=192,out_features=1000,bias=False),
nn.ReLU(inplace=True),
nn.Dropout(p=0.25))
self.combined_features = nn.Sequential(
# change this input nodes
nn.Linear(3048, 512),
nn.ReLU(),
nn.Linear(512, 32),
nn.ReLU(),
nn.Linear(32,1))
def forward(self, image, landmarks):
a = self.image_features(image)
b = self.landmark_features(landmarks)
x = torch.cat((a.view(a.size(0), -1), b.view(b.size(0), -1)), dim=1)
x = self.combined_features(x)
x = torch.sigmoid(x)
return x
model = MixedNetwork()
batch_size = 1
# random input
image = torch.randn(batch_size, 3, 224, 224)
land = torch.randn(batch_size, 96)
output = model(image, land)
print(output)
| https://stackoverflow.com/questions/73266661/ |
How to train model with multiple GPUs in pytorchοΌ | My server has two GPUs, How can I use two GPUs for training at the same time to maximize their computing power? Is my code below correct? Does it allow my model to be properly trained?
class MyModel(nn.Module):
def __init__(self):
super(MyModel, self).__init__()
self.bert = pretrained_model
# for param in self.bert.parameters():
# param.requires_grad = True
self.linear = nn.Linear(2048, 4)
#def forward(self, input_ids, token_type_ids, attention_mask):
def forward(self, input_ids, attention_mask):
batch = input_ids.size(0)
#output = self.bert(input_ids, token_type_ids, attention_mask).pooler_output
output = self.bert(input_ids, attention_mask).last_hidden_state
print('last_hidden_state',output.shape) # torch.Size([1, 768])
#output = output.view(batch, -1) #
output = output[:,-1,:]#(batch_size, hidden_size*2)(batch_size,1024)
output = self.linear(output)
return output
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if torch.cuda.device_count() > 1:
print("Use", torch.cuda.device_count(), 'gpus')
model = MyModel()
model = nn.DataParallel(model)
model = model.to(device)
| There are two different ways to train on multiple GPUs:
Data Parallelism = splitting a large batch that can't fit into a single GPU memory into multiple GPUs, so every GPU will process a small batch that can fit into its GPU
Model Parallelism = splitting the layers within the model into different devices is a bit tricky to manage and deal with.
Please refer to this post for more information
To do Data Parallelism in pure PyTorch, please refer to this example that I created a while back to the latest changes of PyTorch (as of today, 1.12).
To utilize other libraries to do multi-GPU training without engineering many things, I would suggest using PyTorch Lightning as it has a straightforward API and good documentation to learn how to do multi-GPU training using Data Parallelism.
Update: 2022/10/25
Here is a video explaining in much details about different types of distributed training: https://youtu.be/BPYOsDCZbno?t=1011
| https://stackoverflow.com/questions/73267607/ |
How do I convert a torch tensor to an image to be returned by FastAPI? | I have a torch tensor which I need to convert to a byte object so that I can pass it to starlette's StreamingResponse which will return a reconstructed image from the byte object. I am trying to convert the tensor and return it like so:
def some_unimportant_function(params):
return_image = io.BytesIO()
torch.save(some_img, return_image)
return_image.seek(0)
return_img = return_image.read()
return StreamingResponse(content=return_img, media_type="image/jpeg")
The below works fine on regular byte objects and my API returns the reconstructed image:
def some_unimportant_function(params):
image = Image.open(io.BytesIO(some_image))
return_image = io.BytesIO()
image.save(return_image, "JPEG")
return_image.seek(0)
return StreamingResponse(content=return_image, media_type="image/jpeg")
Using PIL library for this
what am I doing wrong here?
| Converting PyTorch Tensor to the PIL Image object using torchvision.transforms.ToPILImage() module and then treating it as PIL Image as your second function would work. Here is an example.
def some_unimportant_function(params):
tensor = # read the tensor from disk or whatever
image = torchvision.transforms.ToPILImage()(tensor.unsqueeze(0))
return_image = io.BytesIO()
image.save(return_image, "JPEG")
return_image.seek(0)
return StreamingResponse(content=return_image, media_type="image/jpeg")
| https://stackoverflow.com/questions/73270890/ |
Why is `nn.Unfold` not giving me the same results as `.unfold` | Why is this giving me two completely different answers? And how can I get the same result as in approach 1, using approach 2?
import torch
from torch import nn
kernel_size = 7
stride = 1
# approach 1
data = torch.rand(4, 64, 174, 120)
data1 = data.unfold(3, kernel_size * 2 + 1, stride)
print(data1.shape)
# approach 2
data = torch.rand(4, 64, 174, 120)
unfold = nn.Unfold(3, kernel_size * 2 + 1, stride)
data2 = unfold(data)
print(data2.shape)
Output:
torch.Size([4, 64, 174, 106, 15])
torch.Size([4, 576, 13432])
EDIT ------------------------------------------
I tried your approach @Shai. The shapes are the same, but the content is not. Any idea why?
import torch
from torch import nn
kernel_size = 7
stride = 1
# approach 1
data = torch.rand(4, 64, 174, 120)
data1 = data.unfold(3, kernel_size * 2 + 1, stride)
print(data1.shape)
# approach 2
data = torch.rand(4, 64, 174, 120)
b, c, h, w = data.shape
unfold = nn.Unfold(kernel_size=(1, 2*kernel_size + 1), dilation=1, stride=1, padding=0)
data2 = unfold(data.reshape(-1, 1, 1, w)).permute(0, 2, 1).reshape(b, c, h, -1, 2*kernel_size + 1)
print(data2.shape)
print(torch.equal(data1, data2))
Output:
torch.Size([4, 64, 174, 106, 15])
torch.Size([4, 64, 174, 106, 15])
False
| torch.unfold "unfolds" along a certain dimension. In your example it takes 4x64x174 samples of dim 120 and extract all overlapping 15-windows, resulting with data1 of shape 4x64x174x106x15.
In contrast, nn.Unfold works on bxcx... tensors and extract spatial patches. In your example, nn.Unfold got kernel_size=3, dilation=kernel_size*2+1 and padding=1. Hence, it extracted 13,432 3x3 patches of 64 channels (3364=576), resulting with data2 of shape 4x576x13432.
To get the same output of torch.unfold from nn.Unfold you need to reshape and permute:
b, c, h, w = data.shape
unfold = nn.Unfold(kernel_size=(1, 2*kernel_size + 1), dilation=1, stride=1, padding=0)
data2 = unfold(data.reshape(-1, 1, 1, w)).permute(0, 2, 1).reshape(b, c, h, -1, 2*kernel_size + 1)
Please read carefully the doc of nn.Unfold as it works in a fundamentally different manner to torch.unfold. For more information about nn.Unfold and nn.Fold please see this thread.
| https://stackoverflow.com/questions/73276139/ |
how to pad a text after build the vocab in pytorch | I used torchtext vocab to convert the text to index, but which function should I use to make all the index list be the same length before I send them to the net?
For example I have 2 texts:
I am a good man
I would like a coffee please
After vocab:
[1, 3, 2, 5, 7]
[1, 9, 6, 2, 4, 8]
And what I want is:
[1, 3, 2, 5, 7, 0]
[1, 9, 6, 2, 4, 8]
| It is easy to understand by looking at the following example.
Code:
import torch
v = [
[0,2],
[0,1,2],
[3,3,3,3]
]
torch.nn.utils.rnn.pad_sequence([torch.tensor(p) for p in v], batch_first=True)
Result:
tensor([[0, 2, 0, 0],
[0, 1, 2, 0],
[3, 3, 3, 3]])
| https://stackoverflow.com/questions/73277262/ |
Mapping 3D tensor according to a rank tensor | I have a tensor called rank which is of shape 2x3 as follows:
tensor([[ 0, 1, 2],
[ 2, 0, 1])
I want to construct a 2X3x3 matrix where the inner matrix is populated initially to all zeros using torch.zeros(2,3,3). I want to update the last dimension to value 1 for last dimension indices corresponding to the values in rank tensor. using indices given in rank.
Final output :
tensor([
tensor([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]],
tensor([[[0, 0, 1],
[1, 0, 0],
[0, 1, 0]]
])
The value 1 is populated according to the rank given in the rank tensor. How can I do this in in pytorch and python.
| Given:
i=torch.tensor([[ 0, 1, 2],
[ 2, 0, 1]])
x=torch.tensor([[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]],
[[0, 0, 1],
[1, 0, 0],
[0, 1, 0]]])
You can perform this operation using torch.scatter_:
>>> torch.zeros(2,3,3).scatter_(2, i[:,:,None].expand_as(x), value=1)
| https://stackoverflow.com/questions/73278182/ |
omp_set_nested routine deprecated, please use omp_set_max_active_levels instead | I started getting the following warning repeatedly when running my PyTorch Lightning deep learning scripts, at execution start and then all through the training:
"OMP: Info #276: omp_set_nested routine deprecated, please use omp_set_max_active_levels instead."
I get them when executing the main.py script; my scripts are publicly available here.
Symptoms:
I don't think it has anything to do with PyTorch Lightning, maybe even PyTorch.
It appeared overnight, so I don't know what could cause it.
It runs fine without those warnings on my PC.
I get the warnings when I run from my M1 Mac.
I use VSCode for both, each up to date.
I use separate miniconda environments.
| Thanks for taking the time to reply!
I managed to sort myself out in the end.
I spotted the numba package in my miniconda env, which is a Python compiler and that seemed to be the root of the problem.
It was version 0.55.2 but the last version to date is 0.56.0. Trying to upgrade it via conda or pip didn't work for some reason (the 0.55.2 version couldn't be replaced).
I recreated my env step by step, and noticed this package comes with torch-audiomentations, a package for audio data augmentation for deep learning, under torch, that I use.
Re-installing it had numba version 0.56.0 installed properly, and the warnings disappeared.
| https://stackoverflow.com/questions/73278739/ |
How to create a dataset containing one datapoint and its augmentations? | I have an imagenet dataset. I want to extract only one image of the dataset and apply random augmentations on this single data point. So basically the transform I define is as following:
sample_transform = transforms.Compose([
transforms.RandomResizedCrop(img_size, scale=(0.2, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=_IMAGENET_RGB_MEANS, std=_IMAGENET_RGB_STDS),
])
And assume that my one sample is as follows:
from torch.utils.data import Subset
def extract_sample(data, idx):
return Subset(data, [idx])
single_sample = extract_sample(data, idx = 0)
Not I want to create a dataset by applying sample_transform, 64 times on single_sample (in order to get 64 different augmentations of single_sample). How can I do that?
Thanks in advance for your help!
| I'd utilize torch.utils.data.RandomSampler with replacement:
import torch
from torchvision import transforms
from torchvision.datasets import ImageFolder
from torch.utils.data import Subset, DataLoader, RandomSampler
import matplotlib.pyplot as plt
from PIL import Image
sample_transform = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.2, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(0.5, 0.5),
])
data = ImageFolder('/media/storage/datasets/t', transform=sample_transform)
def extract_sample(data, idx):
return Subset(data, [idx])
single_sample = extract_sample(data, idx = 0)
sampler = RandomSampler(single_sample, num_samples=64, replacement=True)
loader = DataLoader(single_sample, sampler=sampler)
for img, target in loader:
plt.imshow(img.squeeze().permute(1, 2, 0))
plt.show()
| https://stackoverflow.com/questions/73279363/ |
Learning multivariate normal covariance matrix using pytorch | I am trying to learn a multivariate normal covariance matrix (Sigma, β) using some observations.
The way I went at it is by using pytorch.distributions.MultivariateNormal:
import torch
from torch.distributions import MultivariateNormal
# I tried both the scale_tril parameter and the covariance parameter.
mvn = MultivariateNormal(loc=torch.tensor([0.0, 0.0], requires_grad=False).view(1,2),
scale_tril=torch.tensor([[1.0 , 0.0], [0.0, 1.0]],
requires_grad=True).view(-1, 2, 2))
loss = -mvn.log_prob(torch.ones((1, 2))).mean()
loss.backward()
print(mvn.loc.grad)
I get None. I tried fiddling with the dimensions of the both the loc and the scale_tril parameters. Nothing appears to work. Any ideas?
I can obviously implement this myself, but I have a strong preference using existing tools.
Bests,
Eyal.
| You are not calling .grad on your leaf nodes (on .view rather than tensor itself), also you have requires_grad=False on a mean, lets make things more explicit
import torch
from torch.distributions import MultivariateNormal
mean = torch.tensor([0.0, 0.0], requires_grad=True)
cov = torch.tensor([[1.0 , 0.0], [0.0, 1.0]], requires_grad=True)
mvn = MultivariateNormal(loc=mean.view(1,2),
scale_tril=cov.view(-1, 2, 2))
loss = -mvn.log_prob(torch.ones((1, 2))).mean()
loss.backward()
print(mean.grad)
print(cov.grad)
| https://stackoverflow.com/questions/73279649/ |
How to correctly define weights and biases in a PyTorch neural network to get output of correct shape? | I'm attempting to pass some data of shape [70,1], [70,1,1], and [70,1] into a neural network of linear layers for which I have assigned weights and biases. I am expecting an output of shape [70,1], but I am constantly getting the following error:
RuntimeError Traceback (most recent call last)
Input In [78], in <cell line: 1>()
----> 1 output = net(s, h, ep)
File ~/opt/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py:1130, in Module._call_impl(self, *input, **kwargs)
1126 # If we don't have any hooks, we want to skip the rest of the logic in
1127 # this function, and just call forward.
1128 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1129 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1130 return forward_call(*input, **kwargs)
1131 # Do not call functions when jit is used
1132 full_backward_hooks, non_full_backward_hooks = [], []
Input In [68], in NeuralNetHardeningModel.forward(self, s, h, ep)
101 y = torch.stack((s_eval, h_eval, ep_eval), 1)
103 print(y.shape, 'y')
--> 105 y1 = self.nn(y)
107 print(y1.shape, 'y1')
109 return y1
File ~/opt/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py:1130, in Module._call_impl(self, *input, **kwargs)
1126 # If we don't have any hooks, we want to skip the rest of the logic in
1127 # this function, and just call forward.
1128 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1129 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1130 return forward_call(*input, **kwargs)
1131 # Do not call functions when jit is used
1132 full_backward_hooks, non_full_backward_hooks = [], []
File ~/opt/anaconda3/lib/python3.9/site-packages/torch/nn/modules/container.py:139, in Sequential.forward(self, input)
137 def forward(self, input):
138 for module in self:
--> 139 input = module(input)
140 return input
File ~/opt/anaconda3/lib/python3.9/site-packages/torch/nn/modules/module.py:1130, in Module._call_impl(self, *input, **kwargs)
1126 # If we don't have any hooks, we want to skip the rest of the logic in
1127 # this function, and just call forward.
1128 if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
1129 or _global_forward_hooks or _global_forward_pre_hooks):
-> 1130 return forward_call(*input, **kwargs)
1131 # Do not call functions when jit is used
1132 full_backward_hooks, non_full_backward_hooks = [], []
File ~/opt/anaconda3/lib/python3.9/site-packages/torch/nn/modules/linear.py:114, in Linear.forward(self, input)
113 def forward(self, input: Tensor) -> Tensor:
--> 114 return F.linear(input, self.weight, self.bias)
RuntimeError: mat2 must be a matrix, got 1-D tensor
After some inspection, I could not figure out how to solve the error, but I suspect it might have something to do with the way I assign the weights to each layer in the neural net.
Here is the code that I use to define my PyTorch neural network:
# define the NN
def __init__(self, weight, bias, weight_last, bias_last):
# weight.shape = [3,3,3]
# bias.shape = [3,3]
# weight_last = [3], last layer
# bias_last = [1], last layer
super(NeuralNetHardeningModel, self).__init__()
self.weight = weight
self.bias = bias
self.weight_last = weight_last
self.bias_last = bias_last
self.nn = nn.Sequential(
nn.Linear(3, 3),
nn.ReLU(),
nn.Linear(3, 3),
nn.ReLU(),
nn.Linear(3, 3),
nn.ReLU(),
nn.Linear(3, 1)
)
if len(weight.shape) == 3:
with torch.no_grad():
self.nn[0].weight = nn.Parameter(weight[0])
self.nn[0].bias = nn.Parameter(bias[0])
self.nn[2].weight = nn.Parameter(weight[1])
self.nn[2].bias = nn.Parameter(bias[1])
self.nn[4].weight = nn.Parameter(weight[2])
self.nn[4].bias = nn.Parameter(bias[2])
self.nn[6].weight = nn.Parameter(weight_last)
self.nn[6].bias = nn.Parameter(bias_last)
Here is the code that I use to define my forward pass for my PyTorch neural network:
# forward method for the NN
def forward(self, a, b, c):
for i in range(a.shape[0]):
a_eval = torch.flatten(a) # [70,1]
b_eval = torch.flatten(b) # [70,1,1]
c_eval = torch.flatten(c) # [70,1]
y = torch.stack((a_eval, b_eval, c_eval), 1)
y1 = self.nn(y)
return y1
| The shape of weight_last must be [1,3] instead of just [3] to prevent the matrix multiplication error.
| https://stackoverflow.com/questions/73284899/ |
Generating text/csv file for image path and mask path for semantic segmentation | I have a huge set of images(60k) and masks(60k) that need to be loaded into a PyTorch dataloader for semantic segmentation.
Directory Structure:
- Segmentation
-images
-color_left_trajectory_3000_00001.jpg
-color_left_trajectory_3000_00002.jpg
...
-masks
-color_segmentation_3000_00001.jpg
-color_segmentation_3000_00002.jpg
...
I want to know the most efficient way to load these into a dataloader in Pytorch. I was thinking of generating a csv file with the paths to images and masks. How will I go about generating the same? Any other suggestions are appreciated!
| I recommend that you make a custom subclass from the dataset class. In the init function, the paths to the images and masks are generated and then saved.
This is an example:
import torch
from torch.utils.data import Dataset, DataLoader
import os
from PIL import Image
class CustomData(Dataset):
def __init__(self,data_dir='Segmentation', data_transform=None,split= 'train'):
self.imgs = []
self.labels= []
self.transform = data_transform
self.data_dir = data_dir
#self.imgs_dir = os.path.join(data_dir, split, 'images')
#self.labels_dir = os.path.join(data_dir, split, 'labels')
self.imgs_dir = os.path.join(data_dir, 'images')
self.labels_dir = os.path.join(data_dir, 'labels')
for img_name in os.listdir(self.imgs_dir):
img_path = os.path.join(self.imgs_dir, img_name)
label_name = "color_segmentation_"+"_".join(img.split('.')[0].split('_')[-2:])+'.png'
label_path = os.path.join(self.labels_dir, label_name)
self.imgs.append(img_path)
self.labels.append(label_path)
def __len__(self):
return len(self.imgs)
def __getitem__(self, idx):
img = Image.open(self.imgs[idx])
label = Image.open(self.labels[idx])
if self.transform is not None:
img, label = self.transform(img, label)
return img, label
class ToTensor:
def __call__(self, image, target=None):
image = F.to_tensor(image)
if target is not None:
target = torch.as_tensor(np.array(target), dtype=torch.int64)
return image, target
if __name__ == '__main__':
data = CustomData(data_transform=ToTensor)
dataloader = DataLoader(data,batch_size=10)
| https://stackoverflow.com/questions/73286843/ |
python - TypeError: __init__() got an unexpected keyword argument 'checkpoint_callback' | I'm getting this error message:
TypeError Traceback (most recent call last)
<ipython-input-41-2892cdd4e738> in <module>()
5 max_epochs=N_EPOCHS,
6 gpus=1, #GPU
----> 7 progress_bar_refresh_rate=30
8 )
/usr/local/lib/python3.7/dist-packages/pytorch_lightning/utilities/argparse.py in insert_env_defaults(self, *args, **kwargs)
343
344 # all args were already moved to kwargs
--> 345 return fn(self, **kwargs)
346
347 return cast(_T, insert_env_defaults)
TypeError: __init__() got an unexpected keyword argument 'checkpoint_callback'
... when I run this chunk:
trainer = pl.Trainer(
logger=logger,
checkpoint_callback=checkpoint_callback,
callbacks=[early_stopping_callback],
max_epochs=N_EPOCHS,
gpus=1, #GPU
progress_bar_refresh_rate=30
)
The 'checkpoint_callback' is defined like this:
checkpoint_callback = ModelCheckpoint(
dirpath="checkpoints",
filename="best-checkpoint",
save_top_k=1,
verbose=True,
monitor="val_loss",
mode="min"
)
I can't figure out what's causing the error - can anyone help me?
View full source code here: https://colab.research.google.com/drive/1hT7PDVb0oGSpLejMGFBMWzRKTPwsSwwS?usp=sharing
| As I am looking into pytorch_lightning github, I do not see checkpoint_callback variable in init (https://github.com/Lightning-AI/lightning/blob/master/src/pytorch_lightning/trainer/trainer.py)
Are you sure thats how it's called? What do you want to achieve by passing this checkpoint_callback?
//edit:
I think you just have to append checkpoint_callback to callbacks list
| https://stackoverflow.com/questions/73290224/ |
Add new elements to Pytorch tensor | I have a tensor that looks like this:
I would like to add 0 to each inner tensor. So we have something like[0.1111, 0.6667, 0].
Any suggestion would be appreciated.
| You can do :
z = torch.zeros((10,1))
torch.cat((your_tensor,z),1)
| https://stackoverflow.com/questions/73293878/ |
pytorch sets grad attribute to none if I use simple minus instead of -= | This is a simple code to show the problem
import torch
X = torch.arange(-3, 3, step=0.1)
Y = X * 3
Y += 0.1 * torch.randn(Y.shape)
def my_train_model(iter):
w = torch.tensor(-15.0, requires_grad=True)
lr = 0.1
for epoch in range(iter):
print(w.grad)
yhat = w * X
loss = torch.mean((yhat - Y) ** 2)
loss.backward()
with torch.no_grad():
print(w.grad)
w = w - lr * w.grad # gradient exists if w-= lr*w.grad
print(w.grad)
w.grad.zero_()
print(loss)
my_train_model(4)
This sets the w.grad to none after performing the w = w - lr * w.grad, but the problem will be solved if I use w -= lr * w.grad instead of the above expression!
What is the problem with the first expression which sets w.grad to none?
| The function torch.no_grad() guarantees that no gradient is computed, which means any component wrapped in there is created with requires_grad=False, as you can see in this example.
The in-place operation only changes the value of the tensor, from this answer from forum:
An in-place operation is an operation that changes directly the content of a given Tensor without making a copy.
Therefore, with the problem that you proposed, w = w - lr * w.grad will replace w by the copy of itself without gradient, and w -= lr * w.grad only change the content of tensor which is still keep the gradient of itself from the operation outside of torch.no_grad().
| https://stackoverflow.com/questions/73298413/ |
Expand Pytorch tensor | The tensor a in shape of torch.Size([2, 2, 1, 2])
how to expand this tensor to the shape of torch.Size([2, 4, 1, 2]) without using for loop which takes time
For example, I have tensor a
>>> print(a, a.shape)
tensor([[[[0.2955, 0.8836]],
[[0.7607, 0.6657]]],
[[[0.6779, 0.5109]],
[[0.0785, 0.6564]]]]) torch.Size([2, 2, 1, 2])
I want to expand it to become tensor b
>>> print(b, b.shape)
tensor([[[[0.2955, 0.8836]],
[[0.2955, 0.8836]],
[[0.7607, 0.6657]],
[[0.7607, 0.6657]]],
[[[0.6779, 0.5109]],
[[0.6779, 0.5109]],
[[0.0785, 0.6564]],
[[0.0785, 0.6564]]]]) torch.Size([2, 4, 1, 2])
I tried torch.expand() but it only expands when the dimension=1.
How to achieve this format? Thank you
| Pytorch provides multiple functions with different styles to repeat the tensors. The function that you are looking for is named repeat_interleave. Simple example:
>>> a.repeat_interleave(2,dim=1)
tensor([[[[0.2955, 0.8836]],
[[0.2955, 0.8836]],
[[0.7607, 0.6657]],
[[0.7607, 0.6657]]],
[[[0.6779, 0.5109]],
[[0.6779, 0.5109]],
[[0.0785, 0.6564]],
[[0.0785, 0.6564]]]])
| https://stackoverflow.com/questions/73300477/ |
Is it possible to get the architecture of neural network built with Tensorflow and Pytorch using static analysis? | I'm currently analyzing hundreds of code repositories to identify parameter settings of ML algorithms. In this regard, I was wondering if it is possible to extract the architecture of neural networks that are built with Tensorflow and Pytorch using static analysis?
To clarify my problem, consider the development of a neural network with TF and Pytorch. Usually, a model is created by implementing a class that inherits from TF or Pytorch. Within the class, the architecture (e.g., layers) is specified. For example, see the code snipped below:
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
I was wondering if I can extract the architecture using static analysis. TF provides a function called summary() that prints a summary of a network, including its layers, output shape, and number of parameters. That is exactly what I want to extract with static analysis. The rationale using static analysis is that I analyze hundreds of code repositories and therefore it is not feasible to run the code for each repository.
| You have to compute the Abstract Syntax Tree (AST) of the code that contains the model. For that, you can use an open-source parser.
When you have to AST, you can traverse the graph and extract the model architecture by following tracking the data flow. That part is not straightforward, though. You probably need to look at a few examples and write good tests. But this will not work when you have certain parts of the model defined in other files. You need some way to of doing an interfile static analysis but it is hard.
Hacky way to do it
For each repo, you detect files that contain a class inheriting from nn.Module. You can do this by using the computing AST for each file or simply based on the file content. Now once you know the files containing a module, you create a python file. You import that file in this new file, define and instance of that class. Then you can use .summary function and write it to a file. Probably, there will be multiple nn.Module's per repo when the parts of models defined in several files. To find out the network, you can just take the longest summary.
for repo in repositories:
for file in repo.get_files():
if containsNNModule(file):
create_new_file_with_content(file)
# The file content contains one line for importing file
# One line for defining an instance of the module
# One line to print the summary.
# Create a python subprocess run the new file, capture its output and save it.
| https://stackoverflow.com/questions/73301775/ |
Extracting specific blocks from a module list | I'm using a pretrained model in which there are several self_attentions sequentially stacked each one after another and the number of them is 12. I need to extract the output of the fourth and 10th blocks of this sequential layers. In the following script, the BLock represents each self-attention layer:
dpr = [x.item() for x in torch.linspace(0, 0.1, 12)] # stochastic depth decay rule
self.blocks = nn.ModuleList([
Block(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, attention_type=self.attention_type)
for i in range(12)])
The self-attention layers (stack of Block) are as follows:
## Attention blocks
for blk in self.blocks:
x = blk(x, B, T, W)
How can I extract the fourth and the 10th layers' output?
| To extract the output of a layer, you'll need to use hooks. A forward hook is a function that is called after the forward method of the module was executed.
Here's an example of how to do it:
vit = model(...) # your model with 12 transformer blocks
features = {l:[] for l in range(len(vit.blocks))} # place holder for the extracted features
def make_hook_function(layer):
def hook(module, input, output):
features[layer].appned(output) # save the output of the layer to the place holder
return hook
# place the hooks on the layers that interest you
vit.blocks[4].register_forward_hook(make_hook_function(4))
vit.blocks[10].register_forward_hook(make_hook_function(10))
pred = vit(x) # run an image through the model
# now you can inspect features[4] and features[10]
A very comprehensive example of ViT feature extractor can be found here.
| https://stackoverflow.com/questions/73303113/ |
How to randomly set k elements in a dimension in pytorch tensor to a specific value? | For example, if I have tensor (shape [2, 3, 5])
[[[0.8823, 0.9150, 0.3829, 0.9593, 0.3904],
[0.6009, 0.2566, 0.7936, 0.9408, 0.1332],
[0.9346, 0.5936, 0.8694, 0.5677, 0.7411]],
[[0.4294, 0.8854, 0.5739, 0.2666, 0.6274],
[0.2696, 0.4414, 0.2969, 0.8317, 0.1053],
[0.2695, 0.3588, 0.1994, 0.5472, 0.0062]]]
and k = 2, I want to randomly set k elements in a dimension (e.g., dim=2) to a specific value (e.g., 5):
[[[0.8823, 0.9150, 0.3829, 5, 5],
[0.6009, 0.2566, 5, 0.9408, 5],
[5, 5, 0.8694, 0.5677, 0.7411]],
[[5, 0.8854, 0.5739, 5, 0.6274],
[5, 0.4414, 0.2969, 5, 0.1053],
[0.2695, 0.3588, 5, 0.5472, 5]]]
| Create a random binary mask with k True elements in dimension dim using argsortand set those to 5.
import torch
p = torch.tensor(
[[[0.8823, 0.9150, 0.3829, 0.9593, 0.3904],
[0.6009, 0.2566, 0.7936, 0.9408, 0.1332],
[0.9346, 0.5936, 0.8694, 0.5677, 0.7411]],
[[0.4294, 0.8854, 0.5739, 0.2666, 0.6274],
[0.2696, 0.4414, 0.2969, 0.8317, 0.1053],
[0.2695, 0.3588, 0.1994, 0.5472, 0.0062]]], requires_grad=True)
k = 2
mask = torch.rand(p.shape).argsort(2) < k
torch.where(mask, 5, p)
Output
tensor([[[5.0000, 0.9150, 5.0000, 0.9593, 0.3904],
[5.0000, 0.2566, 0.7936, 5.0000, 0.1332],
[0.9346, 5.0000, 0.8694, 0.5677, 5.0000]],
[[5.0000, 0.8854, 0.5739, 0.2666, 5.0000],
[5.0000, 0.4414, 0.2969, 5.0000, 0.1053],
[5.0000, 5.0000, 0.1994, 0.5472, 0.0062]]], grad_fn=<WhereBackward0>)
| https://stackoverflow.com/questions/73306207/ |
Increasing instances of a class with Data Augmentation | I am working with some classes of the Charades Dataset https://prior.allenai.org/projects/charades to detect indoor actions.
The structure of my dataset is as follows:
Where:
c025, c137 and c142 are actions;
XR436 has frames result of splitting a video where users are performing action c025 and the same for X3803, ... There is a total of 250 folders.
RI495 has frames result of splitting a video where users are performing action c137 and the same for DI402, ... There is a total of 40 folders.
TUCK3 has frames result of splitting a video where users are performing action c142 and the same for the rest. There is a total of 260 folders.
As you can see, the instances of class c137 are quite unbalanced with regard to class c025 and c142. Thus, i would like to increase the number of instances of this class using data augmentation. The idea is creating twin folders with certain transformations. For example, creating A4DID folder as a twin of RI495 with Equalization over each of the frames, A4456 folder as a twin of RI495 in GrayScale, ARTI3 as a twin of DI402 with rotation over the frames, etc. The pattern of transformations can be the same for every folder or not. Just interesting in augmenting the number of instances.
Do you know how to proceed? I am using Pytorch and I tried with torchvision.transforms and DataLoader from torch.utils.data but I have not achieved the result that I am looking for. Any idea on how to proceed?
PS: Undersampling of c025 and c142 is not an option, due to the classifier is not able to learn well with such limited amount of examples.
Thank you in advance
| A few thoughts:
Standard practice is to use transforms dynamically; that is, each time a data example is loaded, a compose or sequential set of transform operations are applied with random parameter settings. Thus, each time the datum is loaded, the resulting x (inputs) are different. This can be achieved by defining a stack of transforms to apply to each data example as it is loaded in a pytorch dataset object (see here). This helps provide data augmentation.
Class imbalance is a somewhat different issue, and is generally solved by either a.) oversampling (this is acceptable if using the above transform solution because the oversampled examples will have different transforms applied) or b.) over-weighting of these examples in the loss calculation. Of course, neither approach can account for the risk of receiving an out-of-distribution testing example which is higher the fewer and less diverse examples you have for a given class. The former can be acheived by defining a custom Sampler object that yields examples from your dataset in a class-balanced manner. The latter can be achieved by passing weights to the loss function (many pytorch loss functions such as CrossEntropyLoss already support weights).
| https://stackoverflow.com/questions/73306305/ |
Meaning of output shapes of ResNet9 model layers | I have a ResNet9 model, implemented in Pytorch which I am using for multi-class image classification. My total number of classes is 6. Using the following code, from torchsummary library, I am able to show the summary of the model, seen in the attached image:
INPUT_SHAPE = (3, 256, 256) #input shape of my image
print(summary(model.cuda(), (INPUT_SHAPE)))
However, I am quite confused about the -1 values in all layers of the ResNet9 model. Also, for Conv2d-1 layer, I am confused about the 64 value in the output shape [-1, 64, 256, 256] as I believe the n_channels value of the input image is 3. Can anyone please help me with the explanation of the output shape values? Thanks!
| Yes
your INPUT_SHAPE is torch.Size([3, 256, 256]) if it's channel first format AND (256, 256, 3) if it's channel last format.
As Pytorch model accepts it in channel first format , for you it shows torch.Size([3, 256, 256])
and talking about our output shape [-1, 64, 256, 256], this is the output shape of your first conv output which has 64 filter each of 256x256 dim and not your input_shape.
-1 represents your variable batch_size which can be fixed in dataloader
| https://stackoverflow.com/questions/73308149/ |
What is the Difference between asssigning layer and assigning weight of layer? | Imagine i have two code examples:
model.embedding = new_emb
and
model.shared.weight = new_emb.weight
What would be the difference between them?
| If you assign a layer weight, the assigned layer weight has to have the same shape as the current layer weight.
If you assign a new layer, you can assign any layer (as long as it can handle the input tensor shape and return the correct output tensor shape).
| https://stackoverflow.com/questions/73311660/ |
How to determine parameters for nn.Conv2d() | I am reading this research paper (https://www.cs.cmu.edu/~rsalakhu/papers/oneshot1.pdf) and trying to follow along with the code on Github. I don't understand how the parameters for the nn.Conv2d() were determined. For the first Conv2d: Does 64@96*96 mean 64 channels with a 96 x 96 kernel size? And if so then why is the kernel size 10 in the function? I have googled the parameters and their meanings and from what I read I understand that its (input_channels, output_channels, kernel_size)
Here is the github post: https://github.com/fangpin/siamese-pytorch/blob/master/train.py
For reference page 4 of the research paper has the model schematic.
self.conv = nn.Sequential(
nn.Conv2d(1, 64, 10), # 64@96*96
nn.ReLU(inplace=True),
nn.MaxPool2d(2), # 64@48*48
nn.Conv2d(64, 128, 7),
nn.ReLU(), # 128@42*42
nn.MaxPool2d(2), # 128@21*21
nn.Conv2d(128, 128, 4),
nn.ReLU(), # 128@18*18
nn.MaxPool2d(2), # 128@9*9
nn.Conv2d(128, 256, 4),
nn.ReLU(), # 256@6*6
)
self.liner = nn.Sequential(nn.Linear(9216, 4096), nn.Sigmoid())
self.out = nn.Linear(4096, 1)
| If you look at the model schematic, it's showing two things,
Parameters of the convolution kernel,
Parameters of the feature maps (output of the nn.Conv2D op)
For example first conv2d layer is 64@10x10, meaning 64 output channels and a 10x10 kernel.
Whereas the feature map is 64@96x96, which comes from applying 64@10x10 convolution op on 105x105x1 sized input. This way you get 64 output channels and a 105-10+1=96 sized width and height.
| https://stackoverflow.com/questions/73312854/ |
Plotting a quadratic loss using norm function from Pytorch and showing it using Plotly | I have a quadratic loss z=(1/2)||Aw-b||^2 where A is 4x2 matrix, w=[x,y] is a 2d vector, and b is a 4d vector. If we plot z, there would be a surface in terms of x,y. I want to plot z using Plotly library. To do this, I want to use Pytorch and the function torch.norm for calculating the norm. Here is a worked example for plotting a 3d surface and I want to modify it as follows:
import plotly.graph_objects as go
import numpy as np
A = torch.tensor([[ 0.1542, -0.0682],
[ 0.8631, 0.6762],
[-1.4002, 1.1773],
[ 0.4614, 0.2431]])
b = torch.tensor([-0.2332, -0.7453, 0.9061, 1.2118])
x = np.arange(-1,1,.01)
y = np.arange(-1,1,.01)
X,Y = np.meshgrid(x,y)
W = ??????
Z = 0.5*torch.norm(torch.matmul(A, W)-b)**2
fig = go.Figure(
data=[go.Surface(z=Z, x=x, y=y, colorscale="Reds", opacity=0.5)])
fig.update_layout(
title='My title',
autosize=False,
width=500,
height=500,
margin=dict(l=65, r=50, b=65, t=90),
scene_aspectmode='cube'
)
fig.show()
Question:
How should I modify W which includes x,y to plot the surface?
| You could simply do:
Z = [[0.5 * torch.norm(torch.matmul(A, torch.tensor([float(xx), float(yy)]))-b)**2 for xx in x] for yy in y]
Update: You can improve the performance significantly by using torch's micro batch feature. For this you have to reshape your data to lists of matrices. That means you have to extend tensor A to a list that contains only one matrix and W to a list that contains all mesh points, each as matrix.
import plotly.graph_objects as go
import torch
A = torch.tensor([[[0.1542, -0.0682],
[0.8631, 0.6762],
[-1.4002, 1.1773],
[0.4614, 0.2431]]])
b = torch.tensor([-0.2332, -0.7453, 0.9061, 1.2118])
x = torch.arange(-1, 1, 0.01)
y = torch.arange(-1, 1, 0.01)
W = torch.reshape(torch.cartesian_prod(x, y), (len(x) * len(y), 2, 1))
V = torch.reshape(torch.matmul(A, W), (len(x), len(y), 4)) - b
Z = 0.5 * torch.norm(V, dim=2)**2
| https://stackoverflow.com/questions/73315290/ |
Would this be a valid Implementation of an ordinal CrossEntropy? | Would this be a valid implementation of a cross entropy loss that takes the ordinal structure of the GT y into consideration? y_hat is the prediction from a neural network.
ce_loss = F.cross_entropy(y_hat, y, reduction="none")
distance_weight = torch.abs(y_hat.argmax(1) - y) + 1
ordinal_ce_loss = torch.mean(distance_weight * ce_loss)
| I'll attempt to answer this question by first fully defining the task, since the question is a bit sparse on details.
I have a set of ordinal classes (e.g. first, second, third, fourth,
etc.) and I would like to predict the class of each data example from
among this set. I would like to define an entropy-based loss-function
for this problem. I would like this loss function to weight the loss
between a predicted class torch.argmax(y_hat) and the true class y
according to the ordinal distance between the two classes. Does the
given loss expression accomplish this?
Short answer: sure, it is "valid". You've roughly implemented L1-norm ordinal class weighting. I'd question whether this is truly the correct weighting strategy for this problem.
For instance, consider that for a true label n, the bin n response is weighted by 1, but the bin n+1 and n-1 responses are weighted by 2. This means that a lot more emphasis will be placed on NOT predicting false positives than on correctly predicting true positives, which may imbue your model with some strange bias.
It also means that examples on the edge will result in a larger total sum of weights, meaning that you'll be weighting examples where the true label is say "first" or "last" more highly than the intermediate classes. (Say you have 5 classes: 1,2,3,4,5. A true label of 1 will require distance_weight of [1,2,3,4,5], the sum of which is 15. A true label of 3 will require distance_weight of [3,2,1,2,3], the sum of which is 11.
In general, classification problems and entropy-based losses are underpinned by the assumption that no set of classes or categories is any more or less related than any other set of classes. In essence, the input data is embedded into an orthogonal feature space where each class represents one vector in the basis. This is quite plainly a bad assumption in your case, meaning that this embedding space is probably not particularly elegant: thus, you have to correct for it with sort of a hack-y weight fix. And in general, this assumption of class non-correlation is probably not true in a great many classification problems (consider e.g. the classic ImageNet classification problem, wherein the class pairs [bus,car], and [bus,zebra] are treated as equally dissimilar. But this is probably a digression into the inherent lack of usefulness of strict ontological structuring of information which is outside the scope of this answer...)
Long Answer: I'd highly suggest moving into a space where the ordinal value you care about is instead expressed in a continuous space. (In the first, second, third example, you might for instance output a continuous value over the range [1,max_place]. This allows you to benefit from loss functions that already capture well the notion that predictions closer in an ordered space are better than predictions farther away in an ordered space (e.g. MSE, Smooth-L1, etc.)
Let's consider one more time the case of the [first,second,third,etc.] ordinal class example, and say that we are trying to predict the places of a set of runners in a race. Consider two races, one in which the first place runner wins by 30% relative to the second place runner, and the second in which the first place runner wins by only 1%. This nuance is entirely discarded by the ordinal discrete classification. In essence, the selection of an ordinal set of classes truncates the amount of information conveyed in the prediction, which means not only that the final prediction is less useful, but also that the loss function encodes this strange truncation and binarization, which is then reflected (perhaps harmfully) in the learned model. This problem could likely be much more elegantly solved by regressing the finishing position, or perhaps instead by regressing the finishing time, of each athlete, and then performing the final ordinal classification into places OUTSIDE of the network training.
In conclusion, you might expect a well-trained ordinal classifier to produce essentially a normal distribution of responses across the class bins, with the distribution peak on the true value: a binned discretization of a space that almost certainly could, and likely should, be treated as a continuous space.
| https://stackoverflow.com/questions/73320361/ |
How to set all elements of pytorch tensor to zero after a certain index in the given axis, where the index is given by another pytorch tensor? | I've two PyTorch tensors
mask = torch.ones(1024, 64, dtype=torch.float32)
indices = torch.randint(0, 64, (1024, ))
For every ith row in mask, I want to set all the elements after the index specified by ith element of indices to zero. For example, if the first element of indices is 50, then I want to set mask[0, 50:]=0. Is it possible to achieve this without using for loop?
Solution with for loop:
for i in range(mask.shape[0]):
mask[i, indices[i]:] = 0
| You can first generate a tensor of size (1024x64) where each row has numbers arranged from 0 to 63. Then apply a logical operation using the indices reshaped as (1024x1)
mask = torch.ones(1024, 64, dtype=torch.float32)
indices = torch.randint(0, 64, (1024, 1)) # Note the dimensions
mask[torch.arange(0, 64, dtype=torch.float32).repeat(1024,1) >= indices] = 0
| https://stackoverflow.com/questions/73325131/ |
Unable to convert Tensor to FloatTensor in Pytorch | I have:
def pytorchConvolution(img, kernel):
img=torch.from_numpy(img)
kernel=torch.from_numpy(kernel)
img.type(torch.FloatTensor)
kernel.type(torch.FloatTensor)
dtype_inputs = torch.quint8
dtype_filters = torch.qint8
scale, zero_point = 1.0, 0
q_filters = torch.quantize_per_tensor(kernel, scale, zero_point, dtype_filters)
q_inputs = torch.quantize_per_tensor(img, scale, zero_point, dtype_inputs)
bias = torch.randn(8, dtype=torch.float)
print(img.type())
convolution2d=qF.conv2d(q_inputs,q_filters,bias)
return(convolution2d)
which is used here:
blur_filter = (1/250)*np.ones([5, 5])
img_blurred_py = pytorchConvolution(img, blur_filter)
However, upon running this code, I get the following output, meaning PyTorch did not convert the tensor to FloatTensor
torch.DoubleTensor
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
Input In [190], in <cell line: 6>()
4 img_blurred = convolution(img, blur_filter)
5 img_blurred_c = convolutionImplantation(img, blur_filter)
----> 6 img_blurred_py = pytorchConvolution(img, blur_filter)
8 plt.axis("off")
9 plt.subplot(1, 2, 1)
Input In [189], in pytorchConvolution(img, kernel)
9 dtype_filters = torch.qint8
11 scale, zero_point = 1.0, 0
---> 12 q_filters = torch.quantize_per_tensor(kernel, scale, zero_point, dtype_filters)
13 q_inputs = torch.quantize_per_tensor(img, scale, zero_point, dtype_inputs)
14 bias = torch.randn(8, dtype=torch.float)
RuntimeError: Quantize only works on Float Tensor, got Double
enter image description here
I have set the default_tensor_type to FloatTensor, and tried to convert to other Tensor Types, however, PyTorch does not convert the tensor to any type. I need to convert both the tensors to FloatTensor to quantize them.
| The type function does not operate in place:
In [2]: a = torch.tensor([1,2])
In [3]: a.dtype
Out[3]: torch.int64
In [4]: a.type(torch.FloatTensor)
Out[4]: tensor([1., 2.])
In [5]: a.dtype
Out[5]: torch.int64
You need to assign these back into the variable:
In [7]: a = a.type(torch.FloatTensor)
In [8]: a.dtype
Out[8]: torch.float32
| https://stackoverflow.com/questions/73327614/ |
Parameters can't be updated when using torch.nn.DataParallel to train on multiple GPUs | import torch
import torch.nn as nn
import os
class Net(nn.Module):
def __init__(self):
super().__init__()
self.h = -1
def forward(self, x):
self.h =x
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
if torch.cuda.is_available():
print('using Cuda devices, num:', torch.cuda.device_count())
model = nn.DataParallel(Net())
x = 2
print(model.module.h)
model(x)
print(model.module.h)
When I use multiple GPUs to train my model, I find that the Net's params can't be updated correctly, it remains the initial value. However, when I use only one GPU instead, it's can be correctly updated. How can I fix this problem? thx! (The examples are posted in the image)
This is when I using two GPUs, the param 'h' didn't change:
This is when I using only one GPU, the param 'h' had changed:
| From the PyTorch's documentation (https://pytorch.org/docs/stable/generated/torch.nn.DataParallel.html):
In each forward, module is replicated on each device, so any updates to the running module in forward will be lost. For example, if module has a counter attribute that is incremented in each forward, it will always stay at the initial value because the update is done on the replicas which are destroyed after forward.
I am guessing PyTorch skips the copying part when there is only one GPU.
Also, your h is just an attribute. It is not a "parameter" in PyTorch.
| https://stackoverflow.com/questions/73328868/ |
NLP data processing between `BucketIterator` and `build_vocab_from_iterator` | I am using AG News Dataset to train model for using text classification.
The part using TabularDataset to generate dataset from csv file.
import torchtext
import torch
from torchtext.legacy.data import Field, TabularDataset, BucketIterator, Iterator
import spacy
def des_tokenize(x):
return x.split(' ')
def title_tokenize(x):
return x.split(' ')
def category_tokenize(x):
return x
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
CATEGORY = Field(tokenize=category_tokenize)
TITLE = Field(tokenize=title_tokenize, init_token='<SOS>', eos_token='<EOS>')
DES = Field(tokenize=des_tokenize, init_token='<SOS>', eos_token='<EOS>')
spacy_en = spacy.load('en_core_web_sm')
train_fields = [('id', None), ('category', CATEGORY), ('title', TITLE), ('description', DES)]
test_fields = [('title', TITLE), ('description', DES)]
train_data = TabularDataset(
path = '/content/drive/MyDrive/summer2/train.csv',
format = 'csv',
fields = train_fields,
skip_header = True)
test_data = TabularDataset(
path = '/content/drive/MyDrive/summer2/test.csv',
format = 'csv',
fields = test_fields,
skip_header = True)
After dataset being generated, choosing to use pre-train embedding model called
torchtext.vocab.GloVe to build vocab.
from torchtext.data.utils import get_tokenizer
from torchtext.vocab import build_vocab_from_iterator
train_batch_size = 10
test_batch_size = 1
max_length = 256
tokenizer = get_tokenizer('basic_english')
train_iter = torchtext.legacy.data.BucketIterator(
train_data,
batch_size=train_batch_size,
)
test_iter = torchtext.legacy.data.BucketIterator(
test_data,
batch_size=test_batch_size,
)
DES.build_vocab(
train_data,
vectors=torchtext.vocab.GloVe(name="6B", dim=50, max_vectors=50_000),
max_size=50_000,
)
TITLE.build_vocab(
train_data,
vectors=torchtext.vocab.GloVe(name="6B", dim=50, max_vectors=50_000),
max_size=50_000,
)
CATEGORY.build_vocab(train_data)
And the output looks great after create_batches function
def create_batches(self):
self.batches = batch(self.data(), self.batch_size, self.batch_size_fn)
# Create batches - needs to be called before each loop.
train_iter.create_batches()
# Loop through BucketIterator.
print('PyTorchText BuketIterator\n')
for batch in train_iter.batches:
# Let's check batch size.
print('Batch size: %d\n'% len(batch))
print('category\ttitle\tdescription'.ljust(10))
# Print each example.
for example in batch:
print('%s \t %s \t %s'.ljust(10) % (example.category, example.title, example.description))
print('\n')
# Only look at first batch. Reuse this code in training models.
break
Output looks like
PyTorchText BuketIterator
Batch size: 10
category title description
2 ['UPDATE', '1-Open-Rejuvenated', 'Haas', 'reaches', 'last', 'eight'] ['Germany', '#39;s', 'Tommy', 'Haas', 'continued', 'his', 'resurgence', 'with', 'a', '7-6', '6-1', '7-5', 'victory', 'over', 'Czech', 'teenager', 'Tomas', 'Berdych', 'on', 'Tuesday', 'to', 'reach', 'the', 'quarter-finals', 'of', 'the', 'US', 'Open', 'for', 'the', 'first', 'time.']
3 ['Japan', '#39;s', 'Nikkei', 'Average,', 'Topix', 'Advance;', 'Toyota,', 'Advantest', 'Gain'] ['Japan', '#39;s', 'Nikkei', '225', 'Stock', 'Average', 'rose', '56.74,', 'or', '0.5', 'percent,', 'to', '11,139.97', 'at', '9:01', 'am', 'in', 'Tokyo.', 'The', 'broader', 'Topix', 'index', 'gained', '5.35,', 'or', '0.5', 'percent,', 'to', '1132.']
2 ['Wildcats', 'on', 'the', 'rise', 'with', 'Santos'] ['The', 'University', 'of', 'New', "Hampshire's", 'impressive', '51-40', 'road', 'victory', 'over', '10th-ranked', 'Villanova', 'Saturday', 'night', 'vaulted', 'the', 'Wildcats', 'three', 'spots', 'to', 'ninth', 'in', 'this', "week's", 'Sports', 'Network', '1-AA', 'football', 'poll,', 'while', 'dropping', 'Villanova', 'to', '14th.']
1 ['Cracking', 'under', 'the', 'strain'] ['Severe', 'cracks', 'surfaced', 'inside', 'the', 'Israeli', 'government', 'this', 'week', 'as', 'its', 'senior', 'law', 'officers', 'publicly', 'fell', 'out', 'with', 'the', 'defence', 'establishment', 'and', 'the', 'Foreign', 'Ministry', 'over', 'the', 'country', '#39;s', 'future', 'strategy', 'in', 'the', 'face', 'of', 'the', 'July', 'verdict', 'of', 'the', 'International', '']
1 ['Arab', 'League', 'to', 'hold', 'emergency', 'meeting'] ['The', 'Arab', 'League', 'says', 'it', 'will', 'hold', 'an', 'emergency', 'session', 'to', 'discuss', 'the', 'violence', 'in', 'Gaza,', 'which', 'has', 'claimed', 'at', 'least', '56', 'Palestinians', 'this', 'week.']
2 ['Holmes', 'to', 'decide', 'on', 'double'] ['Kelly', 'Holmes', 'has', 'still', 'to', 'confirm', 'whether', 'she', 'will', 'attempt', 'to', 'repeat', 'her', 'Olympic', 'double', 'at', 'this', 'weekend', '#39;s', 'World', 'Athletics', 'Final', 'after', 'clearing', 'the', 'first', 'hurdle', 'with', 'a', 'victory', 'in', 'the', '1500m', 'yesterday.']
2 ['NBA', 'suspends', 'nine', 'players,', 'Artest', 'for', 'rest', 'of', 'season'] ['NBA', 'on', 'Sunday', 'suspended', 'nine', 'players', 'for', 'involving', 'in', 'a', 'melee', 'during', 'Friday', '#39;s', 'game', 'between', 'Detorit', 'Pistons', 'and', 'Indiana', 'Pacers,', 'with', 'Ron', 'Artest', 'suspended', 'for', 'the', 'rest', 'of', 'the', 'season,', '73', 'games.']
2 ['On', 'the', 'Far', 'Side', 'of', 'the', 'Field,', 'a', 'Familiar', 'Face'] ['Perhaps', 'there', 'will', 'be', 'a', 'moment', 'during', "Sunday's", 'game', 'between', 'the', 'Giants', 'and', 'the', 'Redskins', 'when', 'a', 'coach', 'and', 'his', 'former', 'franchise', 'quarterback', 'will', 'do', 'a', 'double', 'take.']
3 ['', '#39;QUIET', '#39;', 'RULE', 'MAY', 'CHANGE'] ['The', 'Securities', 'and', 'Exchange', 'Commission', 'wants', 'to', 'scrap', 'a', '1933', 'rule', 'that', 'forces', 'a', 'strict', '', 'quot;quiet', 'period', 'quot;', 'on', 'all', 'talk', 'about', 'a', 'company', 'just', 'prior', 'to', 'its', 'stock', 'being', 'sold', 'initially', 'to', 'the', 'public.']
2 ['Denehy', 'boosts', 'Walpole', ''] ['Danvers', 'coach', 'thought', 'he', 'had', 'the', 'perfect', 'game', 'plan', 'against', 'Walpole', 'last', 'night', 'in', 'the', 'Division', '2', 'playoffs', 'at', 'Endicott', 'College.', 'It', 'was', 'the', 'same', 'game', 'plan', 'that', 'earned', 'his', 'team', 'its', 'first', 'playoff', 'berth', 'in', '63', 'years.']
The question is that what if I use build_vocab_from_iterator to create iterator ?
build_vocab_from_iterator
Does the function has same meaning between my part using BucketIterator ?
Also, I think using Pretrained Word Embeddings GloVe is better than FastText in this work, because the model needs to classify the description is which types.
| After all, the solution which I just post can train the model.
And it had better to use stopwords from library to has better accuracy.
| https://stackoverflow.com/questions/73329568/ |
Can ideal num_workers for a large dataset in PyTorch be 0? | I am currently testing out different num_workers in DataLoader in PyTorch and it seems that 0 has the shortest running time.
I also tried out https://github.com/developer0hye/Num-Workers-Search, which is an automated num_workers search based on dataset and batch_size (and some other parameters), and it also gives 0 as the ideal num_workers.
The CPU itself is a server based AMD Epyc with 128 cores (256 threads), running on Ubuntu 20.04.
Can the CPU processing power be the answer to why the ideal num_workers is set to 0? It is a bit counter-intuitive, especially with a large number of threads.
| Yes this definitely can be the case.
If e.g. the bottleneck is e.g. a hard drive from which the data is read, then even with multiple workers data cannot be read faster. Then the overhead of having multiple processes really just decreases the performance.
But it can also be the case that wherever you load your data from is so fast that it is just no bottleneck at all, in which case having more workers also just adds overhead.
| https://stackoverflow.com/questions/73331758/ |
How to assign a 1d tensor to a 2d tensor using a mask matrix in tensorflow? | 1st: mask (11 true)
2nd: array (11 element)
3nd: zero_tensor (same shape as mask tensor): i want the position can be assigned corresponding element in array (position that was true in mask)
In torch, we can use zero_tensor[mask] = array, but how to do in tensorflow?
| Maybe try something like this:
import tensorflow as tf
x = tf.zeros((5, 3), dtype=tf.int32)
new_values = tf.constant([1, 1, 1, 2, 2, 2, 3, 4, 4, 5, 5], dtype=tf.int32)
mask = tf.constant([[True, True, True],
[True, True, True],
[True, False, False],
[True, True, False],
[True, True, False]])
print(x)
new_x = tf.tensor_scatter_nd_update(x, tf.where(mask), new_values)
print(new_x)
tf.Tensor(
[[0 0 0]
[0 0 0]
[0 0 0]
[0 0 0]
[0 0 0]], shape=(5, 3), dtype=int32)
tf.Tensor(
[[1 1 1]
[2 2 2]
[3 0 0]
[4 4 0]
[5 5 0]], shape=(5, 3), dtype=int32)
| https://stackoverflow.com/questions/73333118/ |
PyTorch AutoEncoder : mat1 and mat2 shapes cannot be multiplied (1x512 and 12x64) | I am trying to pass the output features of a CNN through an AutoEncoder. I used a hooklayer to extract the features of the CNN and converted them into a tensor.
extracted_features = torch.tensor(rn_output)
The size of the data after the conversion from tuple to tensor is torch.Size([1014,512])
The decoder section of the AutoEncoder is throwing the 'cannot be multiplied error' but my belief is the error is due to the setup and shape of the input.
AutoEncoder
class AutoEncoder(nn.Module):
def __init__(self):
super(AutoEncoder, self).__init__()
self.encoder = nn.Sequential(
nn.Linear(in_features=512, out_features=256), # N, 512 -> N,128
nn.ReLU(), # Activation Function
nn.Linear(in_features=256, out_features=128),
nn.ReLU(),
nn.Linear(in_features=128, out_features=64),
nn.ReLU(), # Activation Function
nn.Linear(in_features=64, out_features=12),
)
self.decoder = nn.Sequential(
nn.Linear(in_features=12, out_features=64), # N, 3 -> N,12
nn.ReLU(), # Activation Function
nn.Linear(in_features=64, out_features=128),
nn.Linear(in_features=128, out_features=256),
nn.ReLU(), # Activation Function
nn.Linear(in_features=256, out_features=512),
nn.Tanh()
)
def forward(self, x):
encoded = self.encoder(x)
decoded = self.decoder(x)
return decoded
Call to Autoencoder
model = AutoEncoder()
criterion = nn.MSELoss()
optimiser = torch.optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-5)
num_epochs = 10
outputs = []
for epoch in range(num_epochs):
for (img) in extracted_features:
recon = model(img)
loss = criterion(recon, img)
optimiser.zero_grad()
loss.backward()
optimiser.step()
print(f'Epoch:{epoch+1}, Loss:{loss.item():.4f}')
outputs.append((epoch, img, recon))
I have tried using a dataloader and passing the data in with a smaller batch size. I have also tried reshaping the images within the forward method but I still continue to get the same error
| I'm pretty sure your forward function is incorrectly performing the encoder-decoder step. I think you should change it from this:
encoded = self.encoder(x)
decoded = self.decoder(x)
to this:
encoded = self.encoder(x)
decoded = self.decoder(encoded)
The decoder generally operates on the encoded input not directly on the input itself, unless you're using a non-standard definition of encoder-decoder I'm unfamiliar with.
| https://stackoverflow.com/questions/73336539/ |
Why the error information "unrecognized arguments" return? | When I tried to use ArgumentParser() class to define the argument "epochs" as the training epoch of my CNN model with PyTorch, the system informed me this error. This is my code block:
# 2.1 define super arguments (training epochs for example)
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-e', '--epochs', default=10, type=int,
help='number of epochs to train the VAE for')
args = vars(parser.parse_args())
epochs = args['epochs']
When I executed it, the error was thrown out as:
usage: ipykernel_launcher.py [-h] [-e EPOCHS]
ipykernel_launcher.py: error: unrecognized arguments: -f /root/.local/share/jupyter/runtime/kernel-ae55ea85-75ab-4308-8b6a-3319e5b09a40.json
An exception has occurred, use %tb to see the full traceback.
SystemExit: 2
I do not know what this error information means and how to fix it. I never made any extra arguments with the prompt "-f". How can I deal with this error? Many thanks!!
| From your error message, I guess you are running the code in the jupyter notebook environment.
In jupyter notebook, if you want to use argparse, please modify the code to the following formοΌ
args = vars(parser.parse_args(args=[]))
| https://stackoverflow.com/questions/73337400/ |
How to add modules from torchtext.data? | I'm trying to do this from torchtext.data import TabularDataset, Field, LabelField, BucketIterator, however, I get the following exception:
ImportError: cannot import name 'TabularDataset' from 'torchtext.data' (D:\Users\shuvo\miniconda3\envs\vi38\lib\site-packages\torchtext\data_init_.py)
But I see it in the documentation (figure below). Is there any other way to import it?
| torchtext.data and its contents have been obsolete for a big while now (readthedocs are grossly outdated). For a time being, it's been available as torchtext.legacy.data, but it has been removed entirely in the recent versions as far as I know, in a favour of modern torchdata routines, such as torchdata.datapipes.iter.CSVParser.
| https://stackoverflow.com/questions/73339280/ |
'NoneType' object has no attribute 'to' in mps mode(for apple m1 computer chip) for pytorch | um_epochs = 5
device = torch.device("mps")
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer).to(device)
Then the terminal told me that:
1 num_epochs = 5
2 device = torch.device("mps")
----> 3 d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer).to(device)
AttributeError: 'NoneType' object has no attribute 'to'
Here is the function:
def train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size,
params=None, lr=None, optimizer=None):
for epoch in range(num_epochs):
train_l_sum, train_acc_sum, n = 0.0, 0.0, 0
for X, y in train_iter:
y_hat = net(X)
l = loss(y_hat, y).sum()
# Gradient zeroing
if optimizer is not None:
optimizer.zero_grad()
elif params is not None and params[0].grad is not None:
for param in params:
param.grad.data.zero_()
l.backward()
if optimizer is None:
sgd(params, lr, batch_size)
else:
optimizer.step()
train_l_sum += l.item()
train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
n += y.shape[0]
test_acc = evaluate_accuracy(test_iter, net)
print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f'
% (epoch + 1, train_l_sum / n, train_acc_sum / n, test_acc))
In the process of searching, I noticed that some alike problems are
owing to the overloading mechanism for "=" and "-". But in this function I didn't find any similar slice...
So what's the matter with this NoneType?
| The function train_ch3 does not return anything explicitly, which means that it returns NonType object. And for sure, NoneType object has not attribute named 'to'
I don't know what type of class dl3 is, but if you want to load a tensor or pytorch module onto a specific device, you should use the method to of that tensor or module like: net.to(device) or X.to(device), y.to(device)
| https://stackoverflow.com/questions/73345393/ |
Calculate accuracy of a tensor compared to a target tensor | I have my output tensor like this:
tensor([[0.1834, 0.8166],
[0.3031, 0.6969],
[0.3104, 0.6896],
[0.3065, 0.6935],
[0.3060, 0.6940],
[0.2963, 0.7037],
[0.2340, 0.7660],
[0.2302, 0.7698],
[0.2581, 0.7419],
[0.2081, 0.7919]], grad_fn=<PowBackward0>)
I would like to first convert my output tensor to something like this:
tensor([1., 1., 1......])
where the value indicate the index of the larger value(for example, 0.8166 > 0.1834 so the first element is 1).
Any suggestions would by appreciated!
| That's literally just your_tensor.argmax(dim=1).
your_tensor.argmax(dim=1).float() if you truly need it to be float.
After that, the accuracy can be calculated as sum(my_tensor == target_tensor) / len(target_tensor), for example. (See also this question).
| https://stackoverflow.com/questions/73348974/ |
I use pytorch to train a model to classify iris, but my acc was about 0.4 | I have tried many improvements like increasing epochs, using better loss functions and optimizers, deepening the network and shuffling the dataset, etc, but still to no avail. This problem has been bothering me for a long time, thanks for your help. Below is my code.
load and process dataset(updated)
def Iris_Reader(dataset):
train_data, test_data, train_label, test_label = train_test_split(dataset.data, dataset.target, test_size=0.4)
# scaler = StandardScaler()
# train_data = scaler.fit_transform(train_data)
# test_data = scaler.transform(test_data)
return torch.FloatTensor(train_data), torch.LongTensor(train_label), torch.FloatTensor(test_data), torch.LongTensor(test_label)
Define the classifier
class Classifier(nn.Module):
def __init__(self):
super().__init__()
#4*3*3 network
self.model = nn.Sequential(
nn.Linear(4,3),
nn.ReLU(),
nn.Linear(3,3),
)
#SGD
self.optimiser = torch.optim.SGD(self.parameters(), lr = 0.1)
#MSE LOSS_FUNCTION
self.loss_fn = nn.CrossEntropyLoss()
self.counter = 0
self.progress = []
def forward(self, input):
return self.model(input)
def train(self, input, target):
output = self.forward(input)
loss = self.loss_fn(output, target)
self.counter += 1
self.progress.append(loss.item())
self.optimiser.zero_grad()
loss.backward()
self.optimiser.step()
# plot loss
def plot_loss(self):
plt.figure(dpi=100)
plt.ylim([0,1.0])
plt.yticks([0, 0.25, 0.5, 1.0])
plt.scatter(x = [i for i in range(len(self.progress))], y = self.progress, marker = '.', alpha = 0.2)
plt.grid('on')
plt.show()
TRAIN
C = Classifier()
epochs = 10
dataset = datasets.load_iris()
for epoch in range(epochs):
train_data, train_label, _, _ = Iris_Reader(dataset)
for i, j in zip(train_data, train_label):
C.train(i, j)
TEST
score = 0
num = 0
# for epoch in range(epochs):
_, _, test_data, test_label = Iris_Reader(dataset)
for i,j in zip(test_data, test_label):
output = C.forward(i).detach().argmax()
if output == j:
# print(C.forward(i).detach(), j)
score += 1
num += 1
print(score, num, round(score/num, 3))
OUTPUT: 53 60 0.883
| There's a bunch of problems here:
First, you seem to shuffle data and labels independently, rendering the dataset useless.
Also, you recreate the dataset inside the loop every epoch, wasting the CPU time pointlessly.
Overall, the dataset creation can be shortened to something like this:
def Iris_Reader(dataset):
train_data, test_data, train_label, test_label = sklearn.model_selection.train_test_split(dataset.data, dataset.target, test_size=0.2)
return torch.FloatTensor(train_data), torch.LongTensor(train_label), torch.FloatTensor(test_data), torch.LongTensor(test_label)
and should be taken outside the loop.
Next, MSELoss() is suited for regression. For classification, CrossEntropyLoss() is the default choice.
Using sigmoid as activation in an intermediate layer is not the best choice, especially with a short number of epochs. ReLU should converge much better.
Last but not least, your loss chart would look much cleaner if the values were averaged per epoch.
Update: the implementation that ensures the target having the same size as network output, with additional feature scaling:
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def Iris_Reader(dataset):
label = nn.functional.one_hot(torch.LongTensor(dataset.target), num_classes=3).float()
train_data, test_data,train_label, test_label = train_test_split(dataset.data, label, test_size=0.2)
scaler = StandardScaler()
train_data = scaler.fit_transform(train_data)
test_data = scaler.transform(test_data)
return torch.FloatTensor(train_data), train_label, torch.FloatTensor(test_data), test_label
Oh, and you should probably also remove the final Sigmoid() since CrossEntropyLoss() applies logsoftmax anyway.
| https://stackoverflow.com/questions/73349963/ |
Import Error: Deploying custom Pytorch Model on streamlit | Please, so trying to deploy a custom Pytorch based web-app on streamlit, everything works locally, however when deployed, I find the following Error in the Logs:
Downloading: "https://github.com/ultralytics/yolov5/archive/master.zip" to /home/appuser/.cache/torch/hub/master.zip
2022-08-14 12:23:17.584 Uncaught app exception
Traceback (most recent call last):
File "/home/appuser/venv/lib/python3.9/site-packages/streamlit/scriptrunner/script_runner.py", line 557, in _run_script
exec(code, module.__dict__)
File "app.py", line 28, in <module>
model = torch.hub.load('ultralytics/yolov5', 'custom', path=run_model_path)
File "/home/appuser/venv/lib/python3.9/site-packages/torch/hub.py", line 339, in load
model = _load_local(repo_or_dir, model, *args, **kwargs)
File "/home/appuser/venv/lib/python3.9/site-packages/torch/hub.py", line 368, in _load_local
model = entry(*args, **kwargs)
File "/home/appuser/.cache/torch/hub/ultralytics_yolov5_master/hubconf.py", line 74, in custom
return _create(path, autoshape=autoshape, verbose=_verbose, device=device)
File "/home/appuser/.cache/torch/hub/ultralytics_yolov5_master/hubconf.py", line 31, in _create
from models.common import AutoShape, DetectMultiBackend
File "/home/appuser/.cache/torch/hub/ultralytics_yolov5_master/models/common.py", line 14, in <module>
import cv2
File "/home/appuser/venv/lib/python3.9/site-packages/cv2/__init__.py", line 5, in <module>
from .cv2 import *
ImportError: libGL.so.1: cannot open shared object file: No such file or directory
Here's what the requrements.txt contains:
pillow<=9.2.0
numpy<=1.21.0
streamlit==1.11.0
torch<=1.8.2+cu111
opencv<=4.5.1
Would love your assistance.
| If you're deploying the app, opencv-python-headless would be the appropriate package rather than opencv
| https://stackoverflow.com/questions/73351687/ |
Why iterating over a Pytorch dataloader never ends and goes forever? | I have created a dataloader whose length is 50000. When I calculate its length it prints out 50000.
class MyDataLoader(torch.utils.data.Dataset):
def __init__(self, data_size=50000):
self.data_size = data_size
def __len__(self) -> int:
return self.data_size
def __getitem__(self, idx) -> t.Tuple[torch.Tensor, torch.Tensor]:
image, label = my_function()#(has_star=True)
return image[None], label
dl = MyDataLoader()
print(len(dl))
50000
However, when I iterate over it, it goes forever like the following:
for j, i in enumerate(dl):
if j%10000 == 0:
print(j)
10000
20000
30000
40000
50000
60000
...
How is that possible?
| You have created a Dataset, not a Dataloader.
This should work:
import torch
from torch.utils.data import DataLoader
class MyDataset(torch.utils.data.Dataset):
def __init__(self, data_size=50000):
self.data_size = data_size
def __len__(self) -> int:
return self.data_size
def __getitem__(self, idx):
# print(idx)
return idx
dataset = MyDataset()
# Assume a default batch size of 1
dl = DataLoader(dataset)
print(len(dl))
for j, i in enumerate(dl):
if j%10000 == 0:
print(j)
# And with a different batch size:
dl = DataLoader(dataset, batch_size=2)
print(len(dl))
for j, i in enumerate(dl):
if j%10000 == 0:
print(j)
Note how len(dl) changes when the batch size changes.
| https://stackoverflow.com/questions/73356497/ |
How can we balance off the imbalance generated by the data loader for a binary classification problem | I have created a synthesized dataset and the corresponding data loader for a binary classification problem using Pytorch. The zero class happens almost 20% and the other one 80%. When I train my model it only predicts the 80% ones which makes sense because it has seen the one with label one 80% of the time.
How can I handle this imbalance after getting the data from the data loader?
Is BCELoss capable of understanding this situation?
import torch
from torch.utils.data import DataLoader
class MyDataset(torch.utils.data.Dataset):
def __init__(self, data_size=50000):
self.data_size = data_size
def __len__(self) -> int:
return self.data_size
def __getitem__(self, idx):
data, label (label=0 (20%) or label=1 (80%)) = my_function()
return data, label
dataset = MyDataset()
# Assume a default batch size of 1
batch_size = 1000
dl = DataLoader(dataset, batch_size=batch_size)
# network
loss_fn = torch.nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-6)
losses = []
for epoch in range(num_epochs):
print(f"EPOCH: {epoch}")
for data, label in tqdm(dl, total=len(dl)):
data= data.to(DEVICE).float()
label = label.to(DEVICE).float()
optimizer.zero_grad()
preds = model(data)
prob = torch.sigmoid(preds)
loss = loss_fn(prob, label)
loss.backward()
losses.append(loss.detach().cpu().numpy())
optimizer.step()
# break
Question:
I have read about the weight argument for BCELoss but I am not sure if I can use it here or not. To me, it does not handle imbalance in the data. Note that I cannot manipulate my dataset since in practice the percentage is inherit it the data and we cannot change it from source.
| I'm not sure what you mean by "after getting the data from the data loader" but I'll suggest anyway that you could oversample the minority class by using a WeightedRandomSampler. This will make sure that the dataloader always returns the same amount of samples for each class. So there will be a 50/50 chance that it returns a sample of class 1 and 0. Here is how to do it:
import torch
from torch.utils.data import DataLoader, WeightedRandomSampler
class MyDataset(torch.utils.data.Dataset):
def __init__(self, data_size=50000):
self.data_size = data_size
def __len__(self) -> int:
return self.data_size
def __getitem__(self, idx):
data, label (label=0 (20%) or label=1 (80%)) = my_function()
return data, label
dataset = MyDataset()
# Assume a default batch size of 1
batch_size = 1000
class_weights = [1/20, 1/80] # inverse relative amount of samples per class
sample_weights = [0] * len(dataset)
for idx, (data, label) in enumerate(dataset):
sample_weights[idx] = class_weights[label]
sampler = WeightedRandomSampler(sample_weights, num_samples=len(sample_weights), replacement=True)
dl = DataLoader(dataset, batch_size=batch_size, sampler=sampler)
# continue with your code...
And using a weighted loss can also improve the accuracy. You can simply do something like this:
weights = [1/20, 1/80] # or [4, 1] or [1/2, 1/4] you can try whatever as long as the proportions match the class distribution in your dataset
loss_fn = nn.BCELoss(weights=weights)
You can use both of the methods. And of course the most effective method: augmentation. If it's possible for you to synthetically create more samples from your dataset the do that. An example for augmentation with images is to flip, rotate, crop the images to create slighty different ones. You could add that to your dataset class and have a 80% that the minority class is augmented.
| https://stackoverflow.com/questions/73358348/ |
Better understanding of what is used to feed YOLO | I'm trying to construct a YOLO dataset.
A read a lot about the dataset and understood many things :
pc is the confidence and it corresponds to the IoU between predicted and ground truth bboxes
there are C classes
there are 4 coordinates times the number of bounding boxes (here only 1).
What I do not understand is this quote drawn from the YOLO paper :
Our final layer predicts both class probabilities and bounding box coordinates. We normalize the bounding box width and height by the image width and height so that they fall between 0 and 1. We parametrize the bounding box x and y coordinates to be offsets of a particular grid cell location so they are also bounded between 0 and 1.
I construct my bbox coordinates as many website and annotation solutions suggest, it leads to : cx, cy, rh, rw which are respectively the bbox center coordinates and the bbox height and width relative to the image (normalized by the image size). But this method doesn't seems to rely on the paper's method since cx and cy are note relative to a grid cell here.
I read the Hackernoon article but I don't understand how he sets his x and y : he mentions x=(220-149)/149 = 0.48 where 149 is his grid cell size and 220 is the absolute x coordinate of the bbox. But if there are more cells and one split the image by 6 for instance : 447/6 = 75, then x=(220-75)/75 = 1.93 which is not a relative value (greater than 1)...
My questions :
Does that mean that I had to take into account the grid size (and so the grid cell sizes) when I create my dataset ?
Do I need to include a pc in my training set ? And so, cut the image into cells and return a n*n matrice with 0 and 1 as a pc number ?
Thanks !
| I post here a summary of what has been said and give more context about my initial questions.
Bounding box coordinates
First of all, as mentionned by @MichelKok : the initial YOLO model uses offsets relative to grid cell size (at the contrary, YOLOv5 does not employ the grid structure anymore).
In YOLOv1, the bounding box regression is applied into a grid cell. Therefore input coordinates have to be relative to one grid cell . In other words, if an image is "split" into 3x3 grid cells, the first left cell is (0,0) and the botom right is (2,2).
One can implement this as folow :
cell_size = width/S #or height/S
cx_rcell = cx % cell_size / cell_size
cy_rcell = cy % cell_size / cell_size
Where :
cx and cx are respectively x and y coordinates of the center of the bounding box and are relative to the image (i.e. normalized by the with or height).
cell_size is the size of one grid cell, defined by the number of grid cell in one direction S
Finally, one can go back to the image relative coordinates :
cx = cx_rcell * cell_size - (1/cell_size) * int(cx_rcell/cell_size)
cy = cy_rcell * cell_size - (1/cell_size) * int(cy_rcell/cell_size)
YOLOv1 Loss function
There are 4 parts into this loss :
minimizing the squared error of cx and cy coordinates
minimizing the root squared error of w and h
minimizing the squared error of the confidence numbers
minimizing the squared error of the class probabilities
Note that this loss is constructed in such a way that it penalizes errors depending if an object appears in the current grid cell. As I understood it, this means that one need to deal with bounding box coordinate training set as tensors of shape (N, S, S, 5) in order to get the information "In which cell grid the center of this training bounding box is ?".
A simple implementation could be :
bbox_tensor = torch.zeros(N, S, S, 4)
bbox_tensor[int(cy_rcell / cell_size), int(cx_rcell / cell_size)] = torch.Tensor([cx_rcell , cy_rcell, w, h])
Here, the bounding box coordinates will be located in the cell (i,j) in S^2.
| https://stackoverflow.com/questions/73360500/ |
Pytorch, Pandas, Numpy different result on Windows and Linux | We are working on an AI project which amongst others calculates the position of a human body lying in a bed. External supporters provided us a code package which does this job and calculates the deviation between the real position of the body (detected by a camera) and the predicted position.
That code package has been developed on Windows and now needs to be ported to Ubuntu 20.04. Until now, in the code package for Ubuntu, we just changed some path names (backslash to slash) to make it work.
If we now run β the exactly same - code with the exactly same training and test data under Windows 10 and Ubuntu we observe the following strange behaviour:
The deviation between real body positions and predicted body positions is 25mm (average value) in Windows, which is a good result for our purposes and excepted as a match. In Ubuntu the deviation is 150mm (average value), which is a not usable result.
We also ran the Windows code package in a Windows 10 VM (Virtualbox) on the respective Ubuntu machine. The result is close to the result we get when running the code under βplainβ Ubuntu (not usable).
When running under Ubuntu, there is no difference whether we utilize CPU or GPU.
The code is written in Python 3 and executed under Python 3.7.12 in an Anaconda 3 virtual environment.
We assume that Linux/Ubuntu does not fully support a certain CPU instruction set. but at the end we do not have an explanation for this behaviour. Does anybody have an idea?
Our CPU:
Intel Core I7 (Caby Lake)
Our env.yaml for conda:
name: cosy-bunk-3.7
channels:
- conda-forge
- anaconda
- defaults
- pytorch
dependencies:
- python=3.7
- numpy
- matplotlib
- pandas
- ipykernel
- torchvision
- pytorch
- cudatoolkit=10.2
- torchaudio
- plotly
- scikit-learn
- pip
- pip:
- optuna
- dash
Output of 'conda listβ under Ubuntu:
# Name Version Build Channel
_libgcc_mutex 0.1 conda_forge conda-forge
_openmp_mutex 4.5 2_kmp_llvm conda-forge
alembic 1.8.1 pypi_0 pypi
alsa-lib 1.2.6.1 h7f98852_0 conda-forge
attr 2.5.1 h166bdaf_0 conda-forge
attrs 22.1.0 pypi_0 pypi
autopage 0.5.1 pypi_0 pypi
backcall 0.2.0 pyh9f0ad1d_0 conda-forge
backports 1.0 py_2 conda-forge
backports.functools_lru_cache 1.6.4 pyhd8ed1ab_0 conda-forge
blas 1.1 openblas conda-forge
brotli 1.0.9 pypi_0 pypi
brotli-bin 1.0.9 h166bdaf_7 conda-forge
brotlipy 0.7.0 py37h540881e_1004 conda-forge
ca-certificates 2022.6.15 ha878542_0 conda-forge
certifi 2022.6.15 py37h89c1867_0 conda-forge
cffi 1.15.1 py37h43b0acd_0 conda-forge
charset-normalizer 2.1.0 pyhd8ed1ab_0 conda-forge
click 8.1.3 pypi_0 pypi
cliff 3.10.1 pypi_0 pypi
cmaes 0.8.2 pypi_0 pypi
cmd2 2.4.2 pypi_0 pypi
colorlog 6.6.0 pypi_0 pypi
cryptography 37.0.4 py37h38fbfac_0 conda-forge
cudatoolkit 10.2.89 h713d32c_10 conda-forge
cudnn 7.6.5.32 h01f27c4_1 conda-forge
cycler 0.11.0 pyhd8ed1ab_0 conda-forge
dash 2.6.1 pypi_0 pypi
dash-core-components 2.0.0 pypi_0 pypi
dash-html-components 2.0.0 pypi_0 pypi
dash-table 5.0.0 pypi_0 pypi
dbus 1.13.6 h5008d03_3 conda-forge
debugpy 1.6.0 py37hd23a5d3_0 conda-forge
decorator 5.1.1 pyhd8ed1ab_0 conda-forge
entrypoints 0.4 pyhd8ed1ab_0 conda-forge
expat 2.4.8 h27087fc_0 conda-forge
fftw 3.3.10 nompi_ha7695d1_103 conda-forge
flask 2.2.2 pypi_0 pypi
flask-compress 1.12 pypi_0 pypi
font-ttf-dejavu-sans-mono 2.37 hab24e00_0 conda-forge
font-ttf-inconsolata 3.000 h77eed37_0 conda-forge
font-ttf-source-code-pro 2.038 h77eed37_0 conda-forge
font-ttf-ubuntu 0.83 hab24e00_0 conda-forge
fontconfig 2.14.0 h8e229c2_0 conda-forge
fonts-conda-ecosystem 1 0 conda-forge
fonts-conda-forge 1 0 conda-forge
fonttools 4.34.4 py37h540881e_0 conda-forge
freetype 2.10.4 h0708190_1 conda-forge
gettext 0.19.8.1 h73d1719_1008 conda-forge
giflib 5.2.1 h36c2ea0_2 conda-forge
glib 2.72.1 h6239696_0 conda-forge
glib-tools 2.72.1 h6239696_0 conda-forge
greenlet 1.1.2 pypi_0 pypi
gst-plugins-base 1.20.3 hf6a322e_0 conda-forge
gstreamer 1.20.3 hd4edc92_0 conda-forge
icu 70.1 h27087fc_0 conda-forge
idna 3.3 pyhd8ed1ab_0 conda-forge
importlib-metadata 4.12.0 pypi_0 pypi
importlib-resources 5.9.0 pypi_0 pypi
ipykernel 6.15.1 pyh210e3f2_0 conda-forge
ipython 7.33.0 py37h89c1867_0 conda-forge
itsdangerous 2.1.2 pypi_0 pypi
jack 1.9.18 h8c3723f_1002 conda-forge
jedi 0.18.1 pyhd8ed1ab_2 conda-forge
jinja2 3.1.2 pypi_0 pypi
joblib 1.1.0 pyhd8ed1ab_0 conda-forge
jpeg 9e h166bdaf_2 conda-forge
jupyter_client 7.3.4 pyhd8ed1ab_0 conda-forge
jupyter_core 4.11.1 py37h89c1867_0 conda-forge
keyutils 1.6.1 h166bdaf_0 conda-forge
kiwisolver 1.4.4 py37h7cecad7_0 conda-forge
krb5 1.19.3 h3790be6_0 conda-forge
lcms2 2.12 hddcbb42_0 conda-forge
ld_impl_linux-64 2.36.1 hea4e1c9_2 conda-forge
lerc 4.0.0 h27087fc_0 conda-forge
libblas 3.9.0 15_linux64_openblas conda-forge
libbrotlicommon 1.0.9 h166bdaf_7 conda-forge
libbrotlidec 1.0.9 h166bdaf_7 conda-forge
libbrotlienc 1.0.9 h166bdaf_7 conda-forge
libcap 2.64 ha37c62d_0 conda-forge
libcblas 3.9.0 15_linux64_openblas conda-forge
libclang 14.0.6 default_h2e3cab8_0 conda-forge
libclang13 14.0.6 default_h3a83d3e_0 conda-forge
libcups 2.3.3 hf5a7f15_1 conda-forge
libdb 6.2.32 h9c3ff4c_0 conda-forge
libdeflate 1.13 h166bdaf_0 conda-forge
libedit 3.1.20191231 he28a2e2_2 conda-forge
libevent 2.1.10 h9b69904_4 conda-forge
libffi 3.4.2 h7f98852_5 conda-forge
libflac 1.3.4 h27087fc_0 conda-forge
libgcc-ng 12.1.0 h8d9b700_16 conda-forge
libgfortran-ng 12.1.0 h69a702a_16 conda-forge
libgfortran5 12.1.0 hdcd56e2_16 conda-forge
libglib 2.72.1 h2d90d5f_0 conda-forge
libiconv 1.16 h516909a_0 conda-forge
liblapack 3.9.0 15_linux64_openblas conda-forge
libllvm14 14.0.6 he0ac6c6_0 conda-forge
libnsl 2.0.0 h7f98852_0 conda-forge
libogg 1.3.4 h7f98852_1 conda-forge
libopenblas 0.3.20 pthreads_h78a6416_1 conda-forge
libopus 1.3.1 h7f98852_1 conda-forge
libpng 1.6.37 h753d276_3 conda-forge
libpq 14.4 hd77ab85_0 conda-forge
libprotobuf 3.20.1 h6239696_0 conda-forge
libsndfile 1.0.31 h9c3ff4c_1 conda-forge
libsodium 1.0.18 h36c2ea0_1 conda-forge
libstdcxx-ng 12.1.0 ha89aaad_16 conda-forge
libtiff 4.4.0 h0e0dad5_3 conda-forge
libtool 2.4.6 h9c3ff4c_1008 conda-forge
libudev1 249 h166bdaf_4 conda-forge
libuuid 2.32.1 h7f98852_1000 conda-forge
libvorbis 1.3.7 h9c3ff4c_0 conda-forge
libwebp 1.2.3 h522a892_1 conda-forge
libwebp-base 1.2.3 h166bdaf_2 conda-forge
libxcb 1.13 h7f98852_1004 conda-forge
libxkbcommon 1.0.3 he3ba5ed_0 conda-forge
libxml2 2.9.14 h22db469_3 conda-forge
libzlib 1.2.12 h166bdaf_2 conda-forge
llvm-openmp 14.0.4 he0ac6c6_0 conda-forge
lz4-c 1.9.3 h9c3ff4c_1 conda-forge
magma 2.5.4 h5da55e3_2 conda-forge
mako 1.2.1 pypi_0 pypi
markupsafe 2.1.1 pypi_0 pypi
matplotlib 3.5.2 py37h89c1867_1 conda-forge
matplotlib-base 3.5.2 py37hc347a89_1 conda-forge
matplotlib-inline 0.1.3 pyhd8ed1ab_0 conda-forge
mkl 2022.1.0 h84fe81f_915 conda-forge
munkres 1.1.4 pyh9f0ad1d_0 conda-forge
mysql-common 8.0.30 haf5c9bc_0 conda-forge
mysql-libs 8.0.30 h28c427c_0 conda-forge
nccl 2.13.4.1 h1a5f58c_0 conda-forge
ncurses 6.3 h27087fc_1 conda-forge
nest-asyncio 1.5.5 pyhd8ed1ab_0 conda-forge
ninja 1.11.0 h924138e_0 conda-forge
nspr 4.32 h9c3ff4c_1 conda-forge
nss 3.78 h2350873_0 conda-forge
numpy 1.21.6 py37h976b520_0 conda-forge
openblas 0.3.20 pthreads_h320a7e8_1 conda-forge
openjpeg 2.4.0 hb52868f_1 conda-forge
openssl 1.1.1q h166bdaf_0 conda-forge
optuna 2.10.1 pypi_0 pypi
packaging 21.3 pyhd8ed1ab_0 conda-forge
pandas 1.3.5 py37he8f5f7f_0 conda-forge
parso 0.8.3 pyhd8ed1ab_0 conda-forge
pbr 5.9.0 pypi_0 pypi
pcre 8.45 h9c3ff4c_0 conda-forge
pexpect 4.8.0 pyh9f0ad1d_2 conda-forge
pickleshare 0.7.5 py_1003 conda-forge
pillow 9.2.0 py37h44f0d7a_0 conda-forge
pip 22.2.2 pyhd8ed1ab_0 conda-forge
plotly 5.9.0 pyhd8ed1ab_0 conda-forge
ply 3.11 py_1 conda-forge
portaudio 19.6.0 h57a0ea0_5 conda-forge
prettytable 3.3.0 pypi_0 pypi
prompt-toolkit 3.0.30 pyha770c72_0 conda-forge
psutil 5.9.1 py37h540881e_0 conda-forge
pthread-stubs 0.4 h36c2ea0_1001 conda-forge
ptyprocess 0.7.0 pyhd3deb0d_0 conda-forge
pulseaudio 14.0 h7f54b18_8 conda-forge
pycparser 2.21 pyhd8ed1ab_0 conda-forge
pygments 2.12.0 pyhd8ed1ab_0 conda-forge
pyopenssl 22.0.0 pyhd8ed1ab_0 conda-forge
pyparsing 3.0.9 pyhd8ed1ab_0 conda-forge
pyperclip 1.8.2 pypi_0 pypi
pyqt 5.15.7 py37hf30b843_0 conda-forge
pyqt5-sip 12.11.0 py37hd23a5d3_0 conda-forge
pysocks 1.7.1 py37h89c1867_5 conda-forge
python 3.7.12 hb7a2778_100_cpython conda-forge
python-dateutil 2.8.2 pyhd8ed1ab_0 conda-forge
python_abi 3.7 2_cp37m conda-forge
pytorch 1.12.0 cuda102py37haad9b4f_202 conda-forge
pytorch-mutex 1.0 cuda pytorch
pytz 2022.1 pyhd8ed1ab_0 conda-forge
pyyaml 6.0 pypi_0 pypi
pyzmq 23.2.0 py37h0c0c2a8_0 conda-forge
qt-main 5.15.4 ha5833f6_2 conda-forge
readline 8.1.2 h0f457ee_0 conda-forge
requests 2.28.1 pyhd8ed1ab_0 conda-forge
scikit-learn 1.0.2 py37hf9e9bfc_0 conda-forge
scipy 1.7.3 py37hf2a6cf1_0 conda-forge
setuptools 59.8.0 py37h89c1867_1 conda-forge
sip 6.6.2 py37hd23a5d3_0 conda-forge
six 1.16.0 pyh6c4a22f_0 conda-forge
sleef 3.5.1 h9b69904_2 conda-forge
sqlalchemy 1.4.40 pypi_0 pypi
sqlite 3.39.2 h4ff8645_0 conda-forge
stevedore 3.5.0 pypi_0 pypi
tbb 2021.5.0 h924138e_1 conda-forge
tenacity 8.0.1 pyhd8ed1ab_0 conda-forge
threadpoolctl 3.1.0 pyh8a188c0_0 conda-forge
tk 8.6.12 h27826a3_0 conda-forge
toml 0.10.2 pyhd8ed1ab_0 conda-forge
torchaudio 0.12.0 py37_cu102 pytorch
torchvision 0.13.0 cuda102py37h9785060_0 conda-forge
tornado 6.2 py37h540881e_0 conda-forge
tqdm 4.64.0 pypi_0 pypi
traitlets 5.3.0 pyhd8ed1ab_0 conda-forge
typing-extensions 4.3.0 hd8ed1ab_0 conda-forge
typing_extensions 4.3.0 pyha770c72_0 conda-forge
unicodedata2 14.0.0 py37h540881e_1 conda-forge
urllib3 1.26.11 pyhd8ed1ab_0 conda-forge
wcwidth 0.2.5 pyh9f0ad1d_2 conda-forge
werkzeug 2.2.2 pypi_0 pypi
wheel 0.37.1 pyhd8ed1ab_0 conda-forge
xcb-util 0.4.0 h166bdaf_0 conda-forge
xcb-util-image 0.4.0 h166bdaf_0 conda-forge
xcb-util-keysyms 0.4.0 h166bdaf_0 conda-forge
xcb-util-renderutil 0.3.9 h166bdaf_0 conda-forge
xcb-util-wm 0.4.1 h166bdaf_0 conda-forge
xorg-libxau 1.0.9 h7f98852_0 conda-forge
xorg-libxdmcp 1.1.3 h7f98852_0 conda-forge
xz 5.2.5 h516909a_1 conda-forge
zeromq 4.3.4 h9c3ff4c_1 conda-forge
zipp 3.8.1 pypi_0 pypi
zlib 1.2.12 h166bdaf_2 conda-forge
zstd 1.5.2 h8a70e8d_3 conda-forge
Output of 'conda listβ under Windows:
# Name Version Build Channel
alembic 1.8.1 pypi_0 pypi
attrs 22.1.0 pypi_0 pypi
autopage 0.5.1 pypi_0 pypi
backcall 0.2.0 pyh9f0ad1d_0 conda-forge
backports 1.0 py_2 conda-forge
backports.functools_lru_cache 1.6.4 pyhd8ed1ab_0 conda-forge
blas 1.0 mkl anaconda
brotli 1.0.9 pypi_0 pypi
brotli-bin 1.0.9 h8ffe710_7 conda-forge
ca-certificates 2022.6.15 h5b45459_0 conda-forge
certifi 2022.6.15 py37h03978a9_0 conda-forge
cffi 1.15.1 py37hd8e9650_0 conda-forge
click 8.1.3 pypi_0 pypi
cliff 3.10.1 pypi_0 pypi
cmaes 0.8.2 pypi_0 pypi
cmd2 2.4.2 pypi_0 pypi
colorama 0.4.5 pyhd8ed1ab_0 conda-forge
colorlog 6.6.0 pypi_0 pypi
cudatoolkit 11.3.1 h280eb24_10 conda-forge
cycler 0.11.0 pyhd8ed1ab_0 conda-forge
dash 2.6.1 pypi_0 pypi
dash-core-components 2.0.0 pypi_0 pypi
dash-html-components 2.0.0 pypi_0 pypi
dash-table 5.0.0 pypi_0 pypi
debugpy 1.6.0 py37hf2a7229_0 conda-forge
decorator 5.1.1 pyhd8ed1ab_0 conda-forge
entrypoints 0.4 pyhd8ed1ab_0 conda-forge
flask 2.2.2 pypi_0 pypi
flask-compress 1.12 pypi_0 pypi
fonttools 4.34.4 py37hcc03f2d_0 conda-forge
freetype 2.10.4 h546665d_1 conda-forge
future 0.18.2 py37h03978a9_5 conda-forge
greenlet 1.1.2 pypi_0 pypi
icu 58.2 vc14hc45fdbb_0 [vc14] anaconda
importlib-metadata 4.12.0 pypi_0 pypi
importlib-resources 5.9.0 pypi_0 pypi
intel-openmp 2022.1.0 h57928b3_3787 conda-forge
ipykernel 6.15.1 pyh025b116_0 conda-forge
ipython 7.33.0 py37h03978a9_0 conda-forge
itsdangerous 2.1.2 pypi_0 pypi
jedi 0.18.1 pyhd8ed1ab_2 conda-forge
jinja2 3.1.2 pypi_0 pypi
joblib 1.1.0 pyhd8ed1ab_0 conda-forge
jpeg 9b vc14h4d7706e_1 [vc14] anaconda
jupyter_client 7.3.4 pyhd8ed1ab_0 conda-forge
jupyter_core 4.11.1 py37h03978a9_0 conda-forge
kiwisolver 1.4.4 py37h8c56517_0 conda-forge
libblas 3.9.0 12_win64_mkl conda-forge
libbrotlicommon 1.0.9 h8ffe710_7 conda-forge
libbrotlidec 1.0.9 h8ffe710_7 conda-forge
libbrotlienc 1.0.9 h8ffe710_7 conda-forge
libcblas 3.9.0 12_win64_mkl conda-forge
liblapack 3.9.0 12_win64_mkl conda-forge
libpng 1.6.37 h1d00b33_2 conda-forge
libsodium 1.0.18 h8d14728_1 conda-forge
libsqlite 3.39.2 h8ffe710_1 conda-forge
libtiff 4.0.8 vc14h04e2a1e_10 [vc14] anaconda
libuv 1.44.2 h8ffe710_0 conda-forge
libwebp 1.2.4 h8ffe710_0 conda-forge
libwebp-base 1.2.4 h8ffe710_0 conda-forge
m2w64-gcc-libgfortran 5.3.0 6 conda-forge
m2w64-gcc-libs 5.3.0 7 conda-forge
m2w64-gcc-libs-core 5.3.0 7 conda-forge
m2w64-gmp 6.1.0 2 conda-forge
m2w64-libwinpthread-git 5.0.0.4634.697f757 2 conda-forge
mako 1.2.1 pypi_0 pypi
markupsafe 2.1.1 pypi_0 pypi
matplotlib 3.5.3 py37h03978a9_0 conda-forge
matplotlib-base 3.5.3 py37h54234da_0 conda-forge
matplotlib-inline 0.1.3 pyhd8ed1ab_0 conda-forge
mkl 2021.4.0 h0e2418a_729 conda-forge
mkl-service 2.4.0 py37h75fcce0_0 conda-forge
msys2-conda-epoch 20160418 1 conda-forge
munkres 1.1.4 pyh9f0ad1d_0 conda-forge
nest-asyncio 1.5.5 pyhd8ed1ab_0 conda-forge
ninja 1.11.0 h2d74725_0 conda-forge
numpy 1.21.6 py37h2830a78_0 conda-forge
openssl 1.1.1q h8ffe710_0 conda-forge
optuna 2.10.1 pypi_0 pypi
packaging 21.3 pyhd8ed1ab_0 conda-forge
pandas 1.3.5 py37h9386db6_0 conda-forge
parso 0.8.3 pyhd8ed1ab_0 conda-forge
pbr 5.10.0 pypi_0 pypi
pickleshare 0.7.5 py_1003 conda-forge
pillow 9.2.0 py37hdc2b20a_1
pip 22.2.2 pyhd8ed1ab_0 conda-forge
plotly 5.10.0 pyhd8ed1ab_0 conda-forge
prettytable 3.3.0 pypi_0 pypi
prompt-toolkit 3.0.30 pyha770c72_0 conda-forge
psutil 5.9.1 py37hcc03f2d_0 conda-forge
pycparser 2.21 pyhd8ed1ab_0 conda-forge
pygments 2.12.0 pyhd8ed1ab_0 conda-forge
pyparsing 3.0.9 pyhd8ed1ab_0 conda-forge
pyperclip 1.8.2 pypi_0 pypi
pyqt 5.9.2 py37h6538335_4 conda-forge
pyreadline3 3.4.1 pypi_0 pypi
python 3.7.12 h7840368_100_cpython conda-forge
python-dateutil 2.8.2 pyhd8ed1ab_0 conda-forge
python_abi 3.7 2_cp37m conda-forge
pytorch 1.10.2 cpu_py37h907fbb5_0 anaconda
pytz 2022.2 pyhd8ed1ab_0 conda-forge
pywin32 303 py37hcc03f2d_0 conda-forge
pyyaml 6.0 pypi_0 pypi
pyzmq 23.2.0 py37hcce574b_0 conda-forge
qt 5.9.7 vc14h73c81de_0 [vc14] anaconda
scikit-learn 1.0.2 py37hcabfae0_0 conda-forge
scipy 1.7.3 py37hb6553fb_0 conda-forge
setuptools 59.8.0 py37h03978a9_1 conda-forge
sip 4.19.8 py37h6538335_1000 conda-forge
six 1.16.0 pyh6c4a22f_0 conda-forge
sqlalchemy 1.4.40 pypi_0 pypi
sqlite 3.39.2 h8ffe710_1 conda-forge
stevedore 3.5.0 pypi_0 pypi
tbb 2021.5.0 h2d74725_1 conda-forge
tenacity 8.0.1 pyhd8ed1ab_0 conda-forge
threadpoolctl 3.1.0 pyh8a188c0_0 conda-forge
tk 8.6.7 vc14hb68737d_1 [vc14] anaconda
torchaudio 0.10.2 py37_cu113 pytorch
torchvision 0.11.3 py37_cu113 pytorch
tornado 6.2 py37hcc03f2d_0 conda-forge
tqdm 4.64.0 pypi_0 pypi
traitlets 5.3.0 pyhd8ed1ab_0 conda-forge
typing-extensions 4.3.0 hd8ed1ab_0 conda-forge
typing_extensions 4.3.0 pyha770c72_0 conda-forge
ucrt 10.0.20348.0 h57928b3_0 conda-forge
unicodedata2 14.0.0 py37hcc03f2d_1 conda-forge
vc 14.2 hb210afc_6 conda-forge
vs2015_runtime 14.29.30037 h902a5da_6 conda-forge
wcwidth 0.2.5 pyh9f0ad1d_2 conda-forge
werkzeug 2.2.2 pypi_0 pypi
wheel 0.37.1 pyhd8ed1ab_0 conda-forge
zeromq 4.3.4 h0e60522_1 conda-forge
zipp 3.8.1 pypi_0 pypi
zlib 1.2.11 vc14h1cdd9ab_1 [vc14] anaconda
| After deeper research we discovered the error in the prepairing of the data caused by the different handling of os.listdir() in python. The order is not the same on windows and linux machines.
| https://stackoverflow.com/questions/73371174/ |
Class can't read its attribute | I following this pytorch tutorial
On the basis of this link I wrote the following code:
import torch
import torchvision
from torch.utils.data import Dataset,DataLoader
import numpy as np
import math
class WineDataset(Dataset):
def __int__(self):
xy =np.loadtxt("wine.csv",delimiter=',',dtype=np.float32,skiprows=1)
self.n_samples =xy.shape[0]
self.x_data = torch.from_numpy(xy[:, 1:])
self.y_data = torch.from_numpy(xy[:, [0]])
def __getitem__(self, index):
return self.x_data[index],self.y_data[index]
def __len__(self):
return self.n_samples
# create dataset
dataset = WineDataset()
# get first sample and unpack
first_data = dataset[0]
features, labels = first_data
print(features, labels)
But when I run the code, it gives me following error:
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\AI_Project\Dataset_DataLoader.py", line 19, in <module>
first_data = dataset.__getitem__(0)
File "C:\Users\User\PycharmProjects\AI_Project\Dataset_DataLoader.py", line 13, in __getitem__
return self.x_data[index],self.y_data[index]
AttributeError: 'WineDataset' object has no attribute 'x_data'
This line is also written on GitHub:
# create dataset
dataset = WineDataset()
# get first sample and unpack
first_data = dataset[0]
features, labels = first_data
print(features, labels)
Where is the mistake?
| Change def __int__(self) to def __init__(self). Right now you have no constructor.
| https://stackoverflow.com/questions/73375451/ |
What's the fastest way to slice a portion of a tensor to another in PyTorch? | I have three tensors as shown below:
a = tensor([[5, 2, 3, 24],
[8, 66, 7, 89],
[9, 10, 1, 12]])
b = tensor([[10, 22, 13, 1],
[35, 6, 17, 3],
[11, 13, 5,8]])
c = tensor([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0,0]])
I want to chnage c values using this formula:
Note that the last values (column) in c are not changed at this point.
c[:,:-1]= a[:,:-1] -a[:, 1:] - b[:, 1:]
This means I will have
c = tensor([[5-2-22, 2-3-13, 3-24-1, 0],
[8-66-6, 66-7-17, 7-89-3, 0],
[9-10-13, 10-1-5, 1-12-8,0]])
>>> c = tensor([[-19, -14, -22, 0],
[-64, 42, -85, 0],
[-14, 4, -19,0]])
Finally, to change the last column, I want to use c[:, -1] = b[:, -1] - 1
And my final tensor will look like this:
c = tensor([[-19, -14, -22, 0],
[-64, 42, -85, 2],
[-14, 4, -19,7]])
| I think the fact that you are "overriding" the elements of c is causing you errors.
Try creating c "from scratch", by concatenating its two parts:
c = torch.cat([a[:,:-1] -a[:, 1:] - b[:, 1:],
b[:, -1:] - 1], dim=-1)
| https://stackoverflow.com/questions/73380378/ |
Speeding up a pytorch tensor operation | I am trying to speed up the below operation by doing some sort of matrix/vector-multiplication, can anyone see a nice quick solution?
It should also work for a special case where a tensor has shape 0 (torch.Size([])) but i am not able to initialize such a tensor.
See the image below for the type of tensor i am referring to:
tensor to add to test
def adstock_geometric(x: torch.Tensor, theta: float):
x_decayed = torch.zeros_like(x)
x_decayed[0] = x[0]
for xi in range(1, len(x_decayed)):
x_decayed[xi] = x[xi] + theta * x_decayed[xi - 1]
return x_decayed
def adstock_multiple_samples(x: torch.Tensor, theta: torch.Tensor):
listtheta = theta.tolist()
if isinstance(listtheta, float):
return adstock_geometric(x=x,
theta=theta)
x_decayed = torch.zeros((100, 112, 1))
for idx, theta_ in enumerate(listtheta):
x_decayed_one_entry = adstock_geometric(x=x,
theta=theta_)
x_decayed[idx] = x_decayed_one_entry
return x_decayed
if __name__ == '__main__':
ones = torch.tensor([1])
hundreds = torch.tensor([idx for idx in range(100)])
x = torch.tensor([[idx] for idx in range(112)])
ones = adstock_multiple_samples(x=x,
theta=ones)
hundreds = adstock_multiple_samples(x=x,
theta=hundreds)
print(ones)
print(hundreds)
| I came up with the following, which is 40 times faster on your example:
import torch
def adstock_multiple_samples(x: torch.Tensor, theta: torch.Tensor):
arange = torch.arange(len(x))
powers = (arange[:, None] - arange).clip(0)
return ((theta[:, None, None] ** powers[None, :, :]).tril() * x).sum(-1)
It behaves as expected:
>>> x = torch.arange(112)
>>> theta = torch.arange(100)
>>> adstock_multiple_samples(x, theta)
... # the same output
Note that I considered that x was a 1D-tensor, as for your example the second dimension was not needed.
It also works with theta = torch.empty((0,)), and it returns an empty tensor.
| https://stackoverflow.com/questions/73389529/ |
Pytorch and ray tune: why the error; raise TuneError("Trials did not complete", incomplete_trials)? | I want to embed hyperparameter optimisation with ray into my pytorch script.
I wrote this code (which is a reproducible example):
## Standard libraries
CHECKPOINT_PATH = "/home/ad1/new_dev_v1"
DATASET_PATH = "/home/ad1/"
import torch
device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu")
from importlib import reload
from itertools import *
import matplotlib
from itertools import groupby
from libs_public.api import get_pantry_token
from matplotlib import pyplot as plt
from matplotlib.colors import to_rgb
from openbabel import pybel
from openbabel.pybel import readstring,descs
from operator import itemgetter
from pathlib import Path
from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogger
from ray import tune
from ray.tune import CLIReporter
from ray.tune.integration.pytorch_lightning import TuneReportCallback, TuneReportCheckpointCallback
from ray.tune.schedulers import ASHAScheduler, PopulationBasedTraining
from sklearn import preprocessing
from sklearn.metrics import f1_score, precision_score, recall_score,roc_auc_score
from socket import TIPC_DEST_DROPPABLE
from torch.nn import Linear
from torch.utils.data import TensorDataset
from torch_geometric.data import Data, Dataset,DataLoader,DenseDataLoader,InMemoryDataset
from torch_geometric.datasets import TUDataset
from torch_geometric.nn import GCNConv
from torch_geometric.nn import global_mean_pool
from torchmetrics.functional import precision_recall
from torchvision import transforms
from torchvision.datasets import CIFAR10
from tqdm.notebook import tqdm
import getpass, argparse
import joblib
import json
import logging
import math
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import openbabel
import os
import pandas as pd
import pytorch_lightning as pl
import random
import re
import requests
import seaborn as sns
import sklearn
import sys
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data as data
import torch_geometric
import torch_geometric.data as geom_data
import torch_geometric.nn as geom_nn
import torchmetrics
import torchvision
import warnings
matplotlib.rcParams['lines.linewidth'] = 2.0
pl.seed_everything(42)
print(device)
sns.reset_orig()
sns.set()
sys.path.append('/home/ad1/git/')
torch.backends.cudnn.deterministic = True
warnings.filterwarnings('ignore')
# Setting the seed
pl.seed_everything(42)
# Ensure that all operations are deterministic on GPU (if used) for reproducibility
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
device = torch.device("cuda:0") if torch.cuda.is_available() else torch.device("cpu")
print(device)
import torch
from torch_geometric.datasets import TUDataset
from torch.nn import Linear
from torch_geometric.nn import global_mean_pool
from torch_geometric.data import Data, Dataset,DataLoader
from torch.utils.data import TensorDataset
from ray import tune
from ray.tune import CLIReporter
from ray.tune.schedulers import ASHAScheduler, PopulationBasedTraining
from ray.tune.integration.pytorch_lightning import TuneReportCallback, TuneReportCheckpointCallback
dataset = TUDataset(root='/tmp/MUTAG', name='MUTAG', use_node_attr=True)
loader = DataLoader(dataset, batch_size=32, shuffle=True)
train_dataset = dataset
val_dataset = dataset
test_dataset = dataset
graph_train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
graph_val_loader = DataLoader(val_dataset, batch_size=64) # Additional loader if you want to change to a larger dataset
graph_test_loader = DataLoader(test_dataset, batch_size=64)
#will change this when it makes sense
#config = {
# "dropout": tune.uniform(0.4,0.5)
# }
config = {'dropout':0.4}
gnn_layer_by_name = {
"GCN": geom_nn.GCNConv,
"GAT": geom_nn.GATConv,
"GraphConv": geom_nn.GraphConv
}
class GCNLayer(nn.Module):
def __init__(self, c_in, c_out):
super().__init__()
self.projection = nn.Linear(c_in, c_out)
def forward(self, node_feats, adj_matrix):
"""
Inputs:
node_feats - Tensor with node features of shape [batch_size, num_nodes, c_in]
adj_matrix - Batch of adjacency matrices of the graph. If there is an edge from i to j, adj_matrix[b,i,j]=1 else 0.
Supports directed edges by non-symmetric matrices. Assumes to already have added the identity connections.
Shape: [batch_size, num_nodes, num_nodes]
"""
# Num neighbours = number of incoming edges
num_neighbours = adj_matrix.sum(dim=-1, keepdims=True)
node_feats = self.projection(node_feats)
node_feats = torch.bmm(adj_matrix, node_feats)
node_feats = node_feats / num_neighbours
return node_feats
class GNNModel(nn.Module):
def __init__(self, c_in, c_hidden, c_out, num_layers=2, layer_name="GCN", dp_rate=config['dropout'], **kwargs):
"""
Inputs:
c_in - Dimension of input features
c_hidden - Dimension of hidden features
c_out - Dimension of the output features. Usually number of classes in classification
num_layers - Number of "hidden" graph layers
layer_name - String of the graph layer to use
dp_rate - Dropout rate to apply throughout the network
kwargs - Additional arguments for the graph layer (e.g. number of heads for GAT)
"""
super().__init__()
gnn_layer = gnn_layer_by_name[layer_name]
layers = []
in_channels, out_channels = c_in, c_hidden
for l_idx in range(num_layers-1):
layers += [
gnn_layer(in_channels=in_channels,
out_channels=out_channels,
**kwargs),
nn.ReLU(inplace=True),
nn.Dropout(config['dropout'])
]
in_channels = c_hidden
layers += [gnn_layer(in_channels=in_channels,
out_channels=c_out,
**kwargs)]
self.layers = nn.ModuleList(layers)
def forward(self, x, edge_index):
"""
Inputs:
x - Input features per node
edge_index - List of vertex index pairs representing the edges in the graph (PyTorch geometric notation)
"""
for l in self.layers:
# For graph layers, we need to add the "edge_index" tensor as additional input
# All PyTorch Geometric graph layer inherit the class "MessagePassing", hence
# we can simply check the class type.
if isinstance(l, geom_nn.MessagePassing):
x = l(x, edge_index)
else:
x = l(x)
return x
class GraphGNNModel(nn.Module):
def __init__(self, c_in, c_hidden, c_out, dp_rate_linear=0.5, **kwargs):
"""
Inputs:
c_in - Dimension of input features
c_hidden - Dimension of hidden features
c_out - Dimension of output features (usually number of classes)
dp_rate_linear - Dropout rate before the linear layer (usually much higher than inside the GNN)
kwargs - Additional arguments for the GNNModel object
"""
super().__init__()
self.GNN = GNNModel(c_in=c_in,
c_hidden=c_hidden,
c_out=c_hidden, # Not our prediction output yet!
**kwargs)
self.head = nn.Sequential(
nn.Dropout(config['dropout']),
nn.Linear(c_hidden, c_out)
)
def forward(self, x, edge_index, batch_idx):
"""
Inputs:
x - Input features per node
edge_index - List of vertex index pairs representing the edges in the graph (PyTorch geometric notation)
batch_idx - Index of batch element for each node
"""
x = self.GNN(x, edge_index)
x = geom_nn.global_mean_pool(x, batch_idx) # Average pooling
x = self.head(x)
return x
#see https://pytorch-lightning.readthedocs.io/en/stable/common/lightning_module.html
class GraphLevelGNN(pl.LightningModule):
def __init__(self, **model_kwargs):
super().__init__()
# Saving hyperparameters
self.save_hyperparameters()
self.model = GraphGNNModel(**model_kwargs)
self.loss_module = nn.BCEWithLogitsLoss() #if self.hparams.c_out == 1 else nn.CrossEntropyLoss()
def forward(self, data, mode="train"):
x, edge_index, batch_idx = data.x, data.edge_index, data.batch
x = self.model(x, edge_index, batch_idx)
x = x.squeeze(dim=-1)
if self.hparams.c_out == 1:
preds = (x > 0).float()
data.y = data.y.float()
else:
preds = x.argmax(dim=-1)
loss = self.loss_module(x, data.y)
acc = (preds == data.y).sum().float() / preds.shape[0]
f1 = f1_score(preds,data.y) ##change f1/precision and recall was just testing
precision = precision_score(preds,data.y)
recall = recall_score(preds,data.y)
#roc_auc = roc_auc_score(preds,data.y) ##ADD THIS BACK IN
return loss, acc, f1,precision, recall
def configure_optimizers(self):
optimizer = optim.SGD(self.parameters(),lr=0.1) # High lr because of small dataset and small model
return optimizer
def training_step(self, batch, batch_idx):
loss, acc, _,_, _ = self.forward(batch, mode="train")
self.log('train_loss', loss,on_epoch=True,logger=True)
self.log('train_acc', acc,on_epoch=True,logger=True)
#self.log('train_precision',precision_and_recall)
return loss
def validation_step(self, batch, batch_idx):
loss, acc, _,_, _ = self.forward(batch, mode="val")
self.log('val_acc', acc,on_epoch=True,logger=True)
self.log('val_loss', loss,on_epoch=True,logger=True)
def test_step(self, batch, batch_idx):
loss, acc, f1,precision, recall = self.forward(batch, mode="test")
self.log('test_acc', acc,on_epoch=True,logger=True)
self.log('test_f1', f1,on_epoch=True,logger=True)
self.log('test_precision', precision,on_epoch=True,logger=True)
self.log('test_recall', recall,on_epoch=True,logger=True)
#self.log('roc_auc', roc_auc,on_epoch=True,logger=True)
from pytorch_lightning import loggers as pl_loggers
def train_graph_classifier(model_name, **model_kwargs):
pl.seed_everything(42)
# Create a PyTorch Lightning trainer with the generation callback
root_dir = os.path.join(CHECKPOINT_PATH, "GraphLevel" + model_name)
os.makedirs(root_dir, exist_ok=True)
csv_logger = pl_loggers.CSVLogger(save_dir="logs/")
tune_report_callback = TuneReportCheckpointCallback(
metrics={
"val_loss": "val_loss",
"val_acc": "val_acc",
},
filename="ray_ckpt",
on="validation_end",
)
trainer = pl.Trainer(default_root_dir=root_dir,
callbacks=[ModelCheckpoint(save_weights_only=True, mode="max", monitor="val_acc"),tune_report_callback],
# TuneReportCallback(
# {
# "loss": "val_loss",
# "mean_accuracy": "val_accuracy"
# },
# on="test_end")] # need to change this to validation but error at the minute
# ,
gpus=1 if str(device).startswith("cuda") else 0,
max_epochs=3,
progress_bar_refresh_rate=1,
logger=csv_logger,
)
trainer.logger._default_hp_metric = None # Optional logging argument that we don't need
# Check whether pretrained model exists. If yes, load it and skip training
pretrained_filename = os.path.join(CHECKPOINT_PATH, f"GraphLevel{model_name}.ckpt")
if os.path.isfile(pretrained_filename):
print("Found pretrained model, loading...")
model = GraphLevelGNN.load_from_checkpoint(pretrained_filename)
else:
pl.seed_everything(42)
model = GraphLevelGNN(c_in = dataset.num_node_features,
c_out=1, #if tu_dataset.num_classes==2 else tu_dataset.num_classes,
**model_kwargs)
trainer.fit(model, graph_train_loader, graph_val_loader)
model = GraphLevelGNN.load_from_checkpoint(trainer.checkpoint_callback.best_model_path)
# Test best model on validation and test set
#train_result = trainer.test(model, graph_train_loader, verbose=False)
#test_result = trainer.test(model, graph_test_loader, verbose=False)
#result = {"test": test_result[0]['test_acc'], "train": train_result[0]['test_acc']}
#return model, result
return model
# Example of ASHA Scheduler
scheduler_asha = ASHAScheduler(
max_t=100,
grace_period=1,
reduction_factor=2,
)
from ray.tune.integration.pytorch_lightning import TuneReportCallback, TuneReportCheckpointCallback
reporter = CLIReporter(
parameter_columns=['dropout'],
metric_columns=["val_loss", "val_acc", "training_iteration"]
)
model = train_graph_classifier(model_name="GraphConv",
c_hidden=128,
layer_name="GraphConv",
num_layers=3,
dp_rate_linear=0.5,
dp_rate=0.0)
result = tune.run(
tune.with_parameters(
model,
#feature_size=10,
#target_size=2,
epochs=50,
gpus=0
),
resources_per_trial={
"cpu": 1,
"gpu": 0,
},
local_dir='/home/ad1/ray_ckpt2', # path for saving checkpoints
metric="val_loss",
mode="min",
config=config,
num_samples=16,
scheduler=scheduler_asha,
progress_reporter=reporter,
name="test",
)
And the error returned is:
(tune_with_parameters pid=65319) 2022-08-17 16:28:47,053 ERROR function_runner.py:286 -- Runner Thread raised error.
(tune_with_parameters pid=65319) Traceback (most recent call last):
(tune_with_parameters pid=65319) File "/root/miniconda3/lib/python3.7/site-packages/ray/tune/function_runner.py", line 277, in run
(tune_with_parameters pid=65319) self._entrypoint()
(tune_with_parameters pid=65319) File "/root/miniconda3/lib/python3.7/site-packages/ray/tune/function_runner.py", line 352, in entrypoint
(tune_with_parameters pid=65319) self._status_reporter.get_checkpoint(),
(tune_with_parameters pid=65319) File "/root/miniconda3/lib/python3.7/site-packages/ray/util/tracing/tracing_helper.py", line 462, in _resume_span
(tune_with_parameters pid=65319) return method(self, *_args, **_kwargs)
(tune_with_parameters pid=65319) File "/root/miniconda3/lib/python3.7/site-packages/ray/tune/function_runner.py", line 645, in _trainable_func
(tune_with_parameters pid=65319) output = fn()
(tune_with_parameters pid=65319) File "/root/miniconda3/lib/python3.7/site-packages/ray/tune/utils/trainable.py", line 410, in inner
(tune_with_parameters pid=65319) trainable(config, **fn_kwargs)
(tune_with_parameters pid=65319) File "/root/miniconda3/lib/python3.7/site-packages/torch/nn/modules/module.py", line 1130, in _call_impl
(tune_with_parameters pid=65319) return forward_call(*input, **kwargs)
(tune_with_parameters pid=65319) TypeError: forward() got an unexpected keyword argument 'checkpoint_dir'
Traceback (most recent call last):
File "test_pytorch.py", line 390, in <module>
name="test",
File "/root/miniconda3/lib/python3.7/site-packages/ray/tune/tune.py", line 741, in run
raise TuneError("Trials did not complete", incomplete_trials)
ray.tune.error.TuneError: ('Trials did not complete', [tune_with_parameters_a90c2_00000, tune_with_parameters_a90c2_00001,
...cut for space
tune_with_parameters_a90c2_00014, tune_with_parameters_a90c2_00015])
Could someone show me where I'm going wrong, how to I run HPO with tune in this network and then train the model with the best hyperparameters and then return the model for prediction?
| Ray Tune expects a function trainable in the form of
def train_fn(config):
# ...
In your case, it is probably best to wrap the train_graph_classifier function, e.g.
def train_fn(config):
train_graph_classifier(
model_name="GraphConv",
layer_name="GraphConv",
**config)
analysis = tune.run(
train_fn,
config={
# provide your hyperparameter search space here
"c_hidden": tune.choice([64, 128]),
"dp_rate_linear": tune.quniform(0.0, 1.0, 0.1),
# ...
},
metric="val_loss",
mode="min",
# ...
print(analysis.best_checkpoint)
If you provide the TuneReportCheckpointCallback to the trainer, the analysis.best_checkpoint should contain the best model that can be then loaded for prediction, e.g.
with analysis.best_checkpoint.as_directory() as tmpdir:
trainer = GraphLevelGNN.load_from_checkpoint(tmpdir)
| https://stackoverflow.com/questions/73392060/ |
How to use trained pytorch model for prediction | I have a pretrained pytorch model which is saved in .pth format. How can i use it for prediction on new dataset in a separate python file.
I need a detailed guide.
| Well for prediction theres something called forward pass
import torch
from torch_model import Model # Made up package
device = torch.device('cpu' if torch.cuda.is_available() else 'gpu')
model = Model()
model.load_state_dict(torch.load('weights.pt'))
model = model.to(device) # Set model to gpu
model.eval();
inputs = torch.random.randn(1, 3, 224, 224) # Dtype is fp32
inputs = inputs.to(device) # You can move your input to gpu, torch defaults to cpu
# Run forward pass
with torch.no_grad():
pred = model(inputs)
# Do something with pred
pred = pred.detach().cpu().numpy() # remove from computational graph to cpu and as numpy
| https://stackoverflow.com/questions/73396203/ |
How to plot multiple scalars in Tensorboard in the same figure without spamming the experiment list? | This is not an answer, just a workaround.
This too, is not an answer, (images taken from there).
I am looking for an answer with code in in pytorch-lightning.
Also could be phrased: How to plot training and validation losses on the same graph in Tensorboard with Pytorch lightning, without spamming Tensorboard?
I want to create graphs like this one
but without causing spam like this
All I could find was this answer, which explains only either how to plot such a multi-scalar graph with spam, or avoid spam while splitting the graphs.
How can I just get multiple scalars into a single graph?
Code (using pytorch lightning):
tb = self.logger.experiment # This is a SummaryWriter
label_ind_by_names = {
"A": 0,
"B": 1,
"C": 2,
"D": 3,
"E": 4,
"F": 5,
"G": 6,
"H": 7,
"I": 8,
"J": 9,
}
computed_confusion = np.random.randint(low=0, high=100, size=(10, 10))
per_class_accuracy = computed_confusion.diagonal()/(computed_confusion.sum(1) + np.finfo(float).eps)
drs = {names: per_class_accuracy[label_ind_by_names[names]] for names in label_ind_by_names.keys() if any("is_damaged_True" in n for n in names)}
fas = {names: 1.0 - per_class_accuracy[label_ind_by_names[names]] for names in label_ind_by_names.keys() if any("is_damaged_False" in n for n in names)}
code for separate graphs:
for names, dr in drs.items():
tb.add_scalar(f"dr/{str(names)}", dr, self.current_epoch)
for names, fa in fas.items():
tb.add_scalar(f"fa/{str(names)}", fa, self.current_epoch)
and for united graphs which disorganize the plot list
tb.add_scalars(
"DR", {
str(k): v for k, v in drs.items()
},
self.current_epoch
)
tb.add_scalars(
"FA", {
str(k): v for k, v in fas.items()
},
self.current_epoch
)
| I finally found a sufficient answer here. Here is the doc.
Here is an adaptation to pytorch-lightning:
def on_fit_start(self):
tb = self.logger.experiment # noqa
layout_scalar_names_losses = [r"train_loss_epoch", "val_loss_epoch"]
layout = {
"metrics": {
f"loss_epoch": ["Multiline", layout_scalar_names_losses],
}
}
tb.add_custom_scalars(layout)
and
def _common_log(self, loss, stage: str):
assert stage in ("train", "val", "test")
self.log(f"{stage}_loss", loss, on_step=True, on_epoch=True)
def training_step(self, batch, batch_nb):
stage = "train"
augmented_image, outputs, labels, loss = self._common_step(batch, batch_nb, stage=stage)
self._common_log(loss, stage=stage)
return {"loss": loss, "outputs": outputs, "labels": labels}
def validation_step(self, batch, batch_nb):
stage = "val"
augmented_images, outputs, labels, loss = self._common_step(batch, batch_nb, stage=stage)
self._common_log(loss, stage=stage)
return {"loss": loss, "outputs": outputs, "labels": labels}
def _common_step(self, batch, batch_nb, stage: str):
assert stage in ("train", "val", "test")
augmented_image, labels = batch
outputs, aux_outputs = self(augmented_image)
loss = self._criterion(outputs, labels)
return augmented_image, outputs, labels, loss
This shows the following, under the "custom scalars" tab in Tensorboard.
I was still unable to do this for scalars other than the losses, but will update this answer when I do, as I am certain this is the way to go.
| https://stackoverflow.com/questions/73399268/ |
What is pytorch opposite of nonzero | The nonzero in PyTorch return the indexes of non-zero elements.
tensor([ True, False, True, True, True, True, True, False, True, False])
tensor([0, 2, 3, 4, 5, 6, 8])
What is the opposite of it? To get indexes of all zeros?
| (x == 0).nonzero()
Simply reforming the nonzero function.
| https://stackoverflow.com/questions/73400842/ |
Printing only the first weights of a neural network | I have my model (a VGG16, but it is not important). I want to check only some parameters of my network, for example the first ones.
To do this I do list(model.parameters()) and it prints all the parameters.
Now, considering that a VGG has this shape:
VGG16(
(block_1): Sequential(
(0): Conv2d(1, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(2): ReLU()
(3): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(4): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
(5): ReLU()
(6): MaxPool2d(kernel_size=(2, 2), stride=(2, 2), padding=0, dilation=1, ceil_mode=False)
)
...
If I want only the weights of the convolutions I do this: list(model.block_1[0].parameters()) and it prints this:
[Parameter containing:
tensor([[[[-0.3215, -0.0771, 0.4429],
[-0.6455, -0.0827, -0.4266],
[-0.2029, -0.2288, 0.1696]]],
[[[ 0.5323, -0.2418, -0.1031],
[ 0.5917, 0.2669, -0.5630],
[ 0.3064, -0.4984, -0.1288]]],
[[[ 0.3804, 0.0906, -0.2116],
[ 0.2659, -0.3325, -0.1873],
[-0.5044, 0.0900, 0.1386]]],
Now, these lists are always enormous. How can I print only the first values, for example, the first matrix?
[[[[-0.3215, -0.0771, 0.4429],
[-0.6455, -0.0827, -0.4266],
[-0.2029, -0.2288, 0.1696]]]
| You can treat it as a NumPy array when it's processed correctly. In your example, this should work:
from torchvision import models
model = models.vgg16()
first_param = list(model.features[0].parameters())[0].data
The first_param will hold the tensor as:
tensor([[[[-0.3215, -0.0771, 0.4429],
[-0.6455, -0.0827, -0.4266],
[-0.2029, -0.2288, 0.1696]]],
[[[ 0.5323, -0.2418, -0.1031],
[ 0.5917, 0.2669, -0.5630],
[ 0.3064, -0.4984, -0.1288]]],
[[[ 0.3804, 0.0906, -0.2116],
[ 0.2659, -0.3325, -0.1873],
[-0.5044, 0.0900, 0.1386]]]
Then just continue as NumPy array:
print(first_param[0])
>> tensor([[[[-0.3215, -0.0771, 0.4429],
[-0.6455, -0.0827, -0.4266],
[-0.2029, -0.2288, 0.1696]]])
| https://stackoverflow.com/questions/73404902/ |
Error importing LayoutLMv2ForTokenClassification from HuggingFace | I am trying to run this demo notebook on colab and I am getting the following pytorch error when importing LayoutLMv2ForTokenClassification:
from transformers import LayoutLMv2ForTokenClassification
Error:
ModuleNotFoundError Traceback (most recent call last)
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\transformers\utils\import_utils.py in _get_module(self, module_name)
1029 try:
-> 1030 return importlib.import_module("." + module_name, self.__name__)
1031 except Exception as e:
~\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py in import_module(name, package)
126 level += 1
--> 127 return _bootstrap._gcd_import(name[level:], package, level)
128
~\AppData\Local\Programs\Python\Python39\lib\importlib\_bootstrap.py in _gcd_import(name, package, level)
~\AppData\Local\Programs\Python\Python39\lib\importlib\_bootstrap.py in _find_and_load(name, import_)
~\AppData\Local\Programs\Python\Python39\lib\importlib\_bootstrap.py in _find_and_load_unlocked(name, import_)
~\AppData\Local\Programs\Python\Python39\lib\importlib\_bootstrap.py in _load_unlocked(spec)
~\AppData\Local\Programs\Python\Python39\lib\importlib\_bootstrap_external.py in exec_module(self, module)
~\AppData\Local\Programs\Python\Python39\lib\importlib\_bootstrap.py in _call_with_frames_removed(f, *args, **kwds)
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\transformers\models\layoutlmv2\modeling_layoutlmv2.py in <module>
48 import detectron2
---> 49 from detectron2.modeling import META_ARCH_REGISTRY
50
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\detectron2\modeling\__init__.py in <module>
19 )
---> 20 from .meta_arch import (
21 META_ARCH_REGISTRY,
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\detectron2\modeling\meta_arch\__init__.py in <module>
5
----> 6 from .panoptic_fpn import PanopticFPN
7
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\detectron2\modeling\meta_arch\panoptic_fpn.py in <module>
13 from .build import META_ARCH_REGISTRY
---> 14 from .rcnn import GeneralizedRCNN
15 from .semantic_seg import build_sem_seg_head
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\detectron2\modeling\meta_arch\rcnn.py in <module>
17 from ..proposal_generator import build_proposal_generator
---> 18 from ..roi_heads import build_roi_heads
19 from .build import META_ARCH_REGISTRY
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\detectron2\modeling\roi_heads\__init__.py in <module>
14 )
---> 15 from .roi_heads import (
16 ROI_HEADS_REGISTRY,
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\detectron2\modeling\roi_heads\roi_heads.py in <module>
16 from ..matcher import Matcher
---> 17 from ..poolers import ROIPooler
18 from ..proposal_generator.proposal_utils import add_ground_truth_to_proposals
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\detectron2\modeling\poolers.py in <module>
9 from detectron2.structures import Boxes
---> 10 from detectron2.utils.tracing import assert_fx_safe
11
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\detectron2\utils\tracing.py in <module>
3 import torch
----> 4 from torch.fx._symbolic_trace import _orig_module_call
5 from torch.fx._symbolic_trace import is_fx_tracing as is_fx_tracing_current
ModuleNotFoundError: No module named 'torch.fx._symbolic_trace'
The above exception was the direct cause of the following exception:
RuntimeError Traceback (most recent call last)
<ipython-input-36-b5a73c6d310a> in <module>
4 device_ids = [0,1]
5
----> 6 from transformers import LayoutLMv2ForTokenClassification, TrainingArguments, Trainer
7 from datasets import load_metric
8 import numpy as np
~\AppData\Local\Programs\Python\Python39\lib\importlib\_bootstrap.py in _handle_fromlist(module, fromlist, import_, recursive)
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\transformers\utils\import_utils.py in __getattr__(self, name)
1019 elif name in self._class_to_module.keys():
1020 module = self._get_module(self._class_to_module[name])
-> 1021 value = getattr(module, name)
1022 else:
1023 raise AttributeError(f"module {self.__name__} has no attribute {name}")
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\transformers\utils\import_utils.py in __getattr__(self, name)
1018 value = self._get_module(name)
1019 elif name in self._class_to_module.keys():
-> 1020 module = self._get_module(self._class_to_module[name])
1021 value = getattr(module, name)
1022 else:
~\PycharmProjects\playground\camelot\camelotenv\lib\site-packages\transformers\utils\import_utils.py in _get_module(self, module_name)
1030 return importlib.import_module("." + module_name, self.__name__)
1031 except Exception as e:
-> 1032 raise RuntimeError(
1033 f"Failed to import {self.__name__}.{module_name} because of the following error (look up to see its"
1034 f" traceback):\n{e}"
RuntimeError: Failed to import transformers.models.layoutlmv2.modeling_layoutlmv2 because of the following error (look up to see its traceback):
No module named 'torch.fx._symbolic_trace'
Can anyone please help?
Thanks!
| This is issue from importing torch.fix flag check for symbolic trace and new commit error of detectron (use 5aeb252b194b93dc2879b4ac34bc51a31b5aee13 this checkout and install )
for temporary work
or clone pytorch with new commit
| https://stackoverflow.com/questions/73415504/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.