instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
Delete and Reinitialize pertained BERT weights / parameters | I tried to fine-tune BERT for a classification downstream task.
Now I loaded the model again and I run into the following warning:
Some weights of the model checkpoint at bert-base-uncased were not used when initializing BertModel: ['cls.predictions.transform.dense.weight', 'cls.predictions.transform.LayerNorm.weight',... | As long as you're fine-tuning a model for a downstream task this warning can be ignored. The idea is that the [CLS] token weights from the pretrained model aren't going to be useful for downstream tasks and need to be fine-tuned.
Huggingface randomly initializes them because you're using bert-base-cased which is a Bert... | https://stackoverflow.com/questions/67590284/ |
Computing the loss of a function of predictions with pytorch | I have a convolutional neural network that predicts 3 quantities: Ux, Uy, and P. These are the x velocity, y-velocity, and pressure field. They are all 2D arrays of size [100,60], and my batch size is 10.
I want to compute the loss and update the network by calculating the CURL of the predicted velocity with the CURL o... | You could try something like this:
def discrete_curl(self, pred):
new_arr = torch.zeros((pred.shape[0],100,60))
for pred_idx in range(pred.shape[0]):
for m in range(100):
for n in range(60):
if n <= 58:
if m <= 98:
... | https://stackoverflow.com/questions/67606907/ |
RuntimeError: No CUDA GPUs are available | I want to train a gpt2 model in my laptop and I have a GPU in it and my os is windows , but I always got this error in python:
torch._C._cuda_init()
RuntimeError: No CUDA GPUs are available
when I tried to check the availability of GPU in the python console, I got true:
import torch
torch.cuda.is_available()
Out[4]: T... | In my case the problem was that the CUDA drivers that I was trying to install, didn't support my GPU model. In your case, please check which CUDA driver supports your GPU model. You are now installing 10.2. In my case CUDA 11.0 and 11.2 supported my GPU model but not 11.3 which I was trying to install.
If you got the s... | https://stackoverflow.com/questions/67613855/ |
Binary classification - BCELoss and model output size not corresponding | I'm doing a binary classification, hence I used a binary cross entropy loss:
criterion = torch.nn.BCELoss()
However, I'm getting an error:
Using a target size (torch.Size([64, 1])) that is different to the input size (torch.Size([64, 2])) is deprecated. Please ensure they have the same size.
My model ends with:
x... | Binary Cross-Entropy Loss (BCELoss) is used for binary classification tasks. Therefore if N is your batch size, your model output should be of shape [64, 1] and your labels must be of shape [64].Therefore just squeeze your output at the 2nd dimension and pass it to the loss function -
Here is a minimal working example... | https://stackoverflow.com/questions/67614640/ |
FastAI fastbook - what does it do and why do I need to setup a book? | I tried running on my google colab notebook:
!pip install -Uqq fastbook
import fastbook
as it is written in the FastAI book, chapter 2.
but nor the book or anywhere on google there is an explanation on what is this liberty at all.
amazingly, the page for it does not include any explanation on what fastbook does- onl... |
fastbook.setup_book()
It is used setup when you are using google colab specifically and working with FastAI library. It helps to connect the colab notebook to google drive using an authentication token.
| https://stackoverflow.com/questions/67615589/ |
AWS Sagemaker custom PyTorch model inference on raw image input | I am new to AWS Sagemaker. I have custom CV PyTorch model locally and deployed it to Sagemaker endpoint. I used custom inference.py code to define model_fn, input_fn, output_fn and predict_fn methods. So, I'm able to generate predictions on json input, which contains url to the image, the code is quite straigtforward:
... | As always, after asking I found a solution. Actually, as the error suggested, I had to convert input to bytes or bytearray. For those who may need the solution:
from io import BytesIO
img = Image.open(open(PATH, 'rb'))
img_byte_arr = BytesIO()
img.save(img_byte_arr, format=img.format)
img_byte_arr = img_byte_arr.getva... | https://stackoverflow.com/questions/67622080/ |
Can I reduce number of GPUs without terminating the training? | Let's say I am using multiple GPUs (0,1,2,3) on one machine and later someone else also needs to use GPUs on this machine. Is there a way for me to reduce the number of gpu usage (i.e. only use 0 and 1) from my training without terminating the training and start over again? I don't want to waste the training I already ... | I do not think that this is possible. You should save checkpoints so that you can later continue training where you left. This is possible with Hugging Face API.
training_args = Seq2SeqTrainingArguments(
output_dir=model_directory,
num_train_epochs=args.epochs,
do_eval=True,
eval... | https://stackoverflow.com/questions/67644405/ |
How does one run PyTorch on a A40 GPU without errors (with DDP too)? | I tried running my pytorch code but got this error:
A40 with CUDA capability sm_86 is not compatible with the current PyTorch installation.
The current PyTorch install supports CUDA capabilities sm_37 sm_50 sm_60 sm_61 sm_70 sm_75 compute_37.
If you want to use the A40 GPU with PyTorch, please check the instructions at... | My guess is the following:
A40 gpus have CUDA capability of sm_86 and they are only compatible with CUDA >= 11.0. But CUDA >= 11.0 is only compatible with PyTorch >= 1.7.0 I believe.
So do:
conda install pytorch==1.7.1 torchvision==0.8.2 torchaudio==0.7.2 cudatoolkit=11.0 -c pytorch
or
conda install pytorch t... | https://stackoverflow.com/questions/67645531/ |
AttributeError: module 'torch' has no attribute 'rfft' with PyTorch | I am getting an error using a code that should work according to the documentation.
The goal is to calculate the Feature Similarity Index Measure (FSIM) using the piq Python library.
Terminal Output:
TiffPage 1: ByteCounts tag is missing
Traceback (most recent call last):
File "...\.venv\lib\site-packages\IPytho... | The latest version of pytorch implements all fast fourier functions in the module torch.fft, apparently piq rely on an older version of pytorch, so if you want to run piq consider downgrading your pytorch version, for example:
pip3 install torch==1.7.1 torchvision==0.8.2
| https://stackoverflow.com/questions/67647299/ |
How to fix an error with the quickstart tutorial for pytorch? | I am trying to follow the tutorial on pytorch HERE, but there seems to be a problem. I have created a custom dataloader named training_data that returns an object as required HERE which is a dictionary
{"image": image, "label": label}
where image is a tensor and label is a string. I then follow the... | Your labels y need to be torch tensors. Since you currently have strings, and assuming you are doing classification among n classes, you can simply map them using a list. For example, with three classes, inside the __init__ of your Dataset class:
self.label_names = ["class1", "class2", "class3&... | https://stackoverflow.com/questions/67649060/ |
Pytorch List of all gradients in a model | I'm trying to clip my gradients in a simple deep network model (for RL). But for that I want to fetch statistics of gradients in each epochs, e.g. mean, max etc. Through this I will be able to determine the threshold value to clip my gradients to.
So the way I can approach this was if there was any way to fetch all the... | You can iterate over the parameters to obtain their gradients. For example,
for param in model.parameters():
print(param.grad)
The example above just prints the gradient, but you can apply it suitably to compute the information you need.
| https://stackoverflow.com/questions/67665126/ |
Running BERT SQUAD model on GPU | I am using the BERT Squad model to ask the same question on a collection of documents (>20,000). The model currently runs on my CPU and it takes around a minute to process a single document - which means that I'll need several days to complete the program.
I was wondering if I could speed this up by running the mode... | It's been a while, but I'll answer anyway in the hope that maybe it will help someone.
You can copy each tensor to the GPU using the to method.
For example your batch contains 4 pytorch tensors: input ids, attention masks, segment ids and labels
device = torch.device("cuda")
b_input_ids = batch[0].to(device)
... | https://stackoverflow.com/questions/67675458/ |
Loss is nan, stopping training when training Mask-RCNN multi-class segmentation | number of train data: 346
number of test data: 69
Epoch: [0] [0/346] eta: 0:35:20 lr: 0.000019 loss: -312.6024 (-312.6024) loss_classifier: 1.5789 (1.5789) loss_box_reg: 0.1299 (0.1299) loss_mask: -314.3485 (-314.3485) loss_objectness: 0.0266 (0.0266) loss_rpn_box_reg: 0.0106 (0.0106) time: 6.1275 data: 0.1599 max mem:... | There can be two issues:
Check the coordinate of boxes, make sure [xmin, ymin, xmax, ymax] is positive
Make sure the mask's length is the same as boxes.
| https://stackoverflow.com/questions/67678922/ |
Data Loading in Pytorch for a dataset having all the classes in same folder | I am new to deep learning and Pytorch. I have data set of 6000 images that have all four classes in a single folder. I used the following snippet to upload my data.
torchvision.datasets.ImageFolder(root='/content/drive/My Drive/DFU/base_dir/train_dir', transform=None)
I read that for ImageFolder, the images s... | The simplest solution would be to reorganise the images into class-subfolders based on the csv file, and load as intended by ImageFolder:
import pandas as pd
from pathlib import Path
root = '/content/drive/My Drive/DFU/base_dir/train_dir'
my_csv_file = ...
# Loading csv as {image:class,...} format
df = pd.read_csv(my... | https://stackoverflow.com/questions/67694644/ |
Is torch.empty_like() dependent on the input value as well as input size? | The description in the torch docs for torch.empty_like says:
torch.empty_like(input, *, dtype=None, layout=None, device=None, requires_grad=False, memory_format=torch.preserve_format) → Tensor
Returns an uninitialized tensor with the same size as input. torch.empty_like(input) is equivalent to torch.empty(input.size()... | The docs description is correct. I am not sure if you are confused by torch.empty_like returning different outputs on different calls, but you can see this is also the behaviour of torch.empty by calling e.g. torch.empty((2,3), dtype=torch.int64) multiple times.
Note torch.empty_like does depend on the dtype of the inp... | https://stackoverflow.com/questions/67697347/ |
Load pytorch model from S3 bucket | I want to load a pytorch model (model.pt) from a S3 bucket. I wrote the following code:
from smart_open import open as smart_open
import io
load_path = "s3://serial-no-images/yolo-models/model4/model.pt"
with smart_open(load_path) as f:
buffer = io.BytesIO(f.read())
model.load_state_dict(torch.load(b... | According to the documentation, the following works:
from smart_open import open as smart_open
import io
load_path = "s3://serial-no-images/yolo-models/model4/model.pt"
with smart_open(load_path, 'rb') as f:
buffer = io.BytesIO(f.read())
model.load_state_dict(torch.load(buffer))
I have tried this be... | https://stackoverflow.com/questions/67706477/ |
issue in loading Model using PyTorch in google-collaboratory | I am trying to Load the Model in google_collaboratory to get evaluate it and generate all the statistics results.
My trying
import torch
import torch.nn.functional as F
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torch.backends.cudnn as cudnn
import numpy as np
import torch.nn as nn
import o... | This problem is that when you save the weight you actually uses torch.save(model instead of model.state_dict()
One way to solve this is import the models "the same way you did when train". This is important as when you save the whole model it save the name reference along with the weight.
Maybe you'll need to... | https://stackoverflow.com/questions/67708073/ |
PyTorch does not make initial weights random | I created a Neural Network that takes two greyscale images 14x14 pixels portraying a digit (from MNIST database) and returns 1 if the first digit is less or equal to the second digit, returns 0 otherwise. The code runs, but every time the initial weights are the same. They should be random
Forcing the initial weights t... | Correct me if I'm wrong here but only the weights of the first layer should be the same each time you run this. The thing is when you import the dlc_practical_monologue.py there's this thing in it:
if args.seed >= 0:
torch.manual_seed(args.seed)
which fires up if the seed is >=0 (default is 0).
This should o... | https://stackoverflow.com/questions/67709281/ |
Using weights in CrossEntropyLoss and BCELoss (PyTorch) | I am training a PyTorch model to perform binary classification. My minority class makes up about 10% of the data, so I want to use a weighted loss function. The docs for BCELoss and CrossEntropyLoss say that I can use a 'weight' for each sample.
However, when I declare CE_loss = nn.BCELoss() or nn.CrossEntropyLoss() an... | Another way you could accomplish your goal is to use reduction=none when initializing the loss and then multiply the resulting tensor by your weights before computing the mean.
e.g.
loss = torch.nn.BCELoss(reduction='none')
model = torch.sigmoid
weights = torch.rand(10,1)
inputs = torch.rand(10,1)
targets = torch.rand... | https://stackoverflow.com/questions/67730325/ |
apply a function over all combination of tensor rows in pytorch | I want to make a function f1(arg_tensor) which gets a pytorch tensor as an argument.
In this function I use another function:
f2(tensor_row_1, tensor_row_2) which gets two pytorch's tensor rows as an arguments and outputs a scalar.
f2(..) should be applied over all combinations of tensor's rows [1..n] (i.e. apply funct... | Yes, one can do it with a simple broadcasting trick:
def f1(tensor):
tensor = tensor.permute(1, 0)
return torch.nn.functional.kl_div(
tensor.unsqueeze(dim=2), tensor.unsqueeze(dim=1), reduction="none"
).mean(dim=0)
def manual_f1(tensor):
result = []
for row1 in tensor:
fo... | https://stackoverflow.com/questions/67741628/ |
Constrain parameters to be -1, 0 or 1 in neural network in pytorch | I want to constrain the parameters of an intermediate layer in a neural network to prefer discrete values: -1, 0, or 1. The idea is to add a custom objective function that would increase the loss if the parameters take any other value. Note that, I want to constrain parameters of a particular layer, not all layers.
How... | Extending upon @Shai answer and mixing it with this answer one could do it simpler via custom layer into which you could pass your specific layer.
First, the calculated derivative of torch.abs(x**2 - torch.abs(x)) taken from WolframAlpha (check here) would be placed inside regularize function.
Now the Constrainer layer... | https://stackoverflow.com/questions/67772546/ |
What is the edifference between spacy.load('en_core_web_sm') vs spacy.load(en) | I have seen both of these written down in Colab Notebooks, Can someone please explain the difference between them? Thanks
| In spaCy v2, it was possible to use shorthand to refer to a model in some circumstances, so "en" could be the same as "en_core_web_sm".
The way this worked internally kind of relied on symlinks, which added file system state and caused issues on Windows. This caused troubleshooting problems and conf... | https://stackoverflow.com/questions/67774456/ |
How do I use the fastai saved model? | I trained my model in google colab, and downloaded the .pkl file in my computer. Now, how do I use it? How do I load the .pkl file and do I need to install fastai for it to work?
|
How do I load the .pkl file
Assuming you've saved your model using learner.save you can use complementary learner.load method.
do I need to install fastai for it to work
Yes, you need fastai if you saved it this way. You could also save PyTorch model itself contained inside learner via:
torch.save(learner.model, &q... | https://stackoverflow.com/questions/67778201/ |
IndexError: too many indices for tensor of dimension 2 | here is the dataset:
class price_dataset(Dataset):
def __init__(self, transform=None):
xy = pd.read_csv('data_balanced_full.csv')
self.n_samples = xy.shape[0]
xy = xy.to_numpy()
self.x_data = torch.from_numpy(xy[:, 7:].astype(np.float32))
self.y_data = torch.from_numpy(xy[:... | 'data' and 'label' are not indices but keys of a dictionnary. This dictionary is accessible and calling __getitem__ as follows : dataset_normalized[idx] with idx an integer.
Moreover, you cannot invoke your transformation directly on a dictionary. You should call it on sample['data'] instead.
I advise you to carefully ... | https://stackoverflow.com/questions/67779568/ |
Installation problem with PyTorch's Geometric. "torch-scatter" produces an error with exit status 1 | Could anyone if used PyTorch geometric before, help me resolve this issue. I'm having trouble installing torch-scatter from PyTorch Geometric to deal with some tabular data for question answering task based on TAPAS model. I presume there is a compile error at source. I tried checking other forums and found no solution... | I had this problem too which is solved by install C++ build tools. You can install it from vs_buildtools.exe that is downloadable here
| https://stackoverflow.com/questions/67787392/ |
Extremely poor accuracy upon training network from scratch | I am trying to retrain resnet50 from scratch using a dataset that is similar to ImageNet. I wrote the following training loop:
def train_network(epochs , train_loader , val_loader , optimizer , network):
since = time.time ( )
train_acc_history = []
val_acc_history = []
best_model_weights = copy.deepcop... | I tried your training loop without the weight checkpoint and got accuracy over 90% on fashionMNIST dataset using my own ResNet. So if you are using a good loss/optimizer I would suggest looking at the network architecture or creation of the data-loaders.
def train_network(epochs , train_loader , val_loader , optimizer ... | https://stackoverflow.com/questions/67788670/ |
Failed to Build Torch-Scatter in Pytorch Geometry | I am very new to the concept of Graph Neural Networks. To learn more I tried installing torch geometric, but it is giving a huge error(which I can't even paste here).
My Versions:
>>> import torch
>>> torch.__version__
'1.8.1'
>>> torch.version.cuda
'10.1'
The command I used to install torch... | Try checking python version it should be less then 3.9 as wheel for torch-scatter for python 3.9 is not released yet.
Create new environment with python 3.8
install pytorch cuda version and then :-
pip install torch-scatter -f https://pytorch-geometric.com/whl/torch-1.8.1+cu101.html
if still not working try
pip install... | https://stackoverflow.com/questions/67792006/ |
Weighted random sampler - oversample or undersample? | Problem
I am training a deep learning model in PyTorch for binary classification, and I have a dataset containing unbalanced class proportions. My minority class makes up about 10% of the given observations. To avoid the model learning to just predict the majority class, I want to use the WeightedRandomSampler from tor... | A small snippet of code to use WeightedRandomSampler
First, define the function:
def make_weights_for_balanced_classes(images, nclasses):
n_images = len(images)
count_per_class = [0] * nclasses
for _, image_class in images:
count_per_class[image_class] += 1
weight_per_class = [0.] * nclasses
... | https://stackoverflow.com/questions/67799246/ |
Pytorch - Use a UNet to perform Image Deblurring/Image Reconstruction | Currently, I'm working with a dataset where I have two kinds of images: "sharp version" of the image and "blurry version" of the same images, where a blur was added synthetically. My goal is to train a model that takes the blurry version of the images in and tries to deblur the image as much as it c... | The U-net you're using is for segmentation (classification of each pixels of the image) whereas you're trying to denoise the image (getting your image "sharper"/remove noise). It explains the results you got.
To get what you want you need and as DerekG said, you first need to modify the number of channels of ... | https://stackoverflow.com/questions/67807350/ |
Installing geffnet with pip | I used a google colab notebook to run a certain model. It required me to install geffnet like this.
!pip -q install geffnet
How can I install geffnet locally?
I tried the line below but I get an error when trying to get efficientnet_b7. "RuntimeError: Unknown model (efficientnet_b7)
pip3 install geffnet
| Were your other python installing commands work properly?
Try with a version likethis,
pip install geffnet==0.9.0
Still not working,try to use Pytorch instead of Colab, sometimes issue may be fixed
| https://stackoverflow.com/questions/67812297/ |
Convert list of tensors into tensor pytorch | I have a list of embeddings. The list has N lists with M embedding (tensors) each.
list_embd = [[M embeddings], [M embeddings], ...]
(Each embedding is a tensor with size (1,512))
What I want to do is create a tensor size (N, M), where each "cell" is one embedding.
Tried this for numpy array.
array = np.zero... | You can use torch.cat and torch.stack to create a final 3D tensor of shape (N, M, 512):
final = torch.stack([torch.cat(sub_list, dim=0) for sub_list in list_embd], dim=0)
First, you use torch.cat to create a list of N 2D tensors of shape (M, 512) from each list of M embeddings. Then torch.stack is used to stack these ... | https://stackoverflow.com/questions/67814465/ |
Runtime error: CUDA out of memory by the end of training and doesn’t save model; pytorch | I'm not so experienced in Data Science and pytorch and I have problems with implementing at least anything here(currently I'm making a NN for segmentation tasks). There is some kind of memory problem, although it doesn't meen anything - every epoch takes a lot less memory than it is in the risen
import torch
from torch... | The problem is your loss_train list, which stores all losses from the beginning of your experiment. If the losses you put in were mere float, that would not be an issue, but because of your not returning a float in the train function, you are actually storing loss tensors, with all the computational graph embedded in t... | https://stackoverflow.com/questions/67819077/ |
In Pytorch, quantity.backward() computes the gradient of quantity wrt which of the parameters? | The backward method computes the gradient wrt to which parameters? All of the params with requires_grad having True value?
Interestingly, in Pytorch
computing gradients
and
loading the optimizer that updates parameters based on gradients
need different informations about the identity of parameters of interest to be... | Computing quantity requires constructing a 2-sorted graph with nodes being either tensors or differentiable operations on tensors (a so-called computational graph). Under the hood, pytorch keeps track of this graph for you. When you call quantity.backward(), you're asking pytorch to perform an inverse traversal of the ... | https://stackoverflow.com/questions/67826958/ |
How can I handle this datasets to create a datasetDict? | I'm trying to build a datasetDictionary object to train a QA model on PyTorch. I have these two different datasets:
test_dataset
Dataset({
features: ['answer_text', 'answer_start', 'title', 'context', 'question', 'answers', 'id'],
num_rows: 21489
})
and
train_dataset
Dataset({
features: ['answer_text', '... | to get the validation dataset, you can do like this:
train_dataset, validation_dataset= train_dataset.train_test_split(test_size=0.1).values()
This function will divide 10% of the train dataset into the validation dataset.
and to obtain "DatasetDict", you can do like this:
import datasets
dd = datasets.Datas... | https://stackoverflow.com/questions/67852880/ |
i'm confused with CoordConv | i read a paper which written by uber lab
https://medium.com/@Cambridge_Spark/coordconv-layer-deep-learning-e02d728c2311
they create a network named Coordconv,and in this coordconv they not only add two layer of meshgrid but also with a simple conv net.
it said through this way they add positional info to every pixel p... | About CoordConv
Here is the original paper which proposed the CoordConv layer: CoordConv paper.
I will try to convey my instinctive undersanding of this operation.
How AddCoords works
The way the information is added is by stacking (concatenating, to be more accurate) two new 2D tensors to the data. Those two channels ... | https://stackoverflow.com/questions/67857323/ |
pytorch isn't running on gpu while true | I want to train on my local gpu but it's only running on cpu while torch.cuda.is_available() is actually true and i can see my gpu but it runs only on cpu , so how to fix it
my CNN model:
import torch.nn as nn
import torch.nn.functional as F
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
# define the ... | To utilize cuda in pytorch you have to specify that you want to run your code on gpu device.
a line of code like:
use_cuda = torch.cuda.is_available()
device = torch.device("cuda" if use_cuda else "cpu")
will determine whether you have cuda available and if so, you will have it as your device.
late... | https://stackoverflow.com/questions/67859185/ |
Understanding the order when reshaping a tensor | For a tensor:
x = torch.tensor([
[
[[0.4495, 0.2356],
[0.4069, 0.2361],
[0.4224, 0.2362]],
[[0.4357, 0.6762],
[0.4370, 0.6779],
[0.4406, 0.6663]]
],
[
[[0.5796, 0.4047],
[0.5655, 0.4080],
[0.5431, 0.... | The order of the elements in memory in python, pytorch, numpy, c++ etc. are in row-major ordering:
[ first, second
third, forth ]
While in matlab, fortran, etc. the order is column major:
[ first, third
second, fourth ]
For higher dimensional tensors, this means elements are ordered from the last dimension to t... | https://stackoverflow.com/questions/67868450/ |
Can I add new training pictures to my object detection model without re-running the whole training again? | I used yolov5 to train an object detection model. is it possible to add more annotated images after i have already trained the original model or must i restart the whole training with the new set of images?
| You are asking about continual learning - this is a very active field of research, and there is no single solution/method to tackle it. You'll have to do more research to find the right approach for your specific settings.
| https://stackoverflow.com/questions/67898366/ |
Pytorch mixed precision learning, torch.cuda.amp running slower than normal | I am trying to infer results out of a normal resnet18 model present in torchvision.models attribute. The model is simply trained without any mixed precision learning, purely on FP32.
However, I want to get faster results while inferencing, so I enabled torch.cuda.amp.autocast() function only while running a test infere... | It's most likely because of the GPU you're using - P100, which has 3584 CUDA cores but 0 tensor cores -- the latter of which typically play the main role in mixed precision speedup. You may want to take a quick look at the "Hardware Comparison" section on this article.
If you're stuck to using Colab, the only... | https://stackoverflow.com/questions/67904276/ |
How to convert this tensor flow code into pytorch code? | I am trying to implement an Image Denoising Gan which is written in tensorflow to pytorch and I am unable to understand what is tf.variable_scope and tf.Variable similar in pytorch. please help.
def conv_layer(input_image, ksize, in_channels, out_channels, stride, scope_name, activation_function=lrelu, reuse=False):
... | You can replace tf.Variable with torch.tensor, torch.tensor can hold gradients all the same.
In torch, you also don't create a graph and then access things in there by name via some scope. You would just create the tensor and then can access it directly. The output variable there would just be accessible to you do with... | https://stackoverflow.com/questions/67940962/ |
Simulating many agents in PyTorch using multiprocessing | I want to simulate multiple reinforcement learning agents that are coded using Pytorch. The agents do not share any data dynamically, so I expect that the task should be "embarassingly parallel". I need a lot of simulations (I want to see what is the distribution my agents converge to) so I hope to speed it u... | It looks like your problem is in this line
p = mp.Process(target=model.simulate(N = 10, T = 50), args= ())
The part model.simulate(N = 10, T = 50) is executed first, then the result (I'm assuming None if there is no return from this method) is passed to the mp.Process as the target parameter. So you are doing all the ... | https://stackoverflow.com/questions/67956061/ |
Python - PyTorch: IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices | I am working with PyTorch on a Text Classification problem with BERT. This is the PyTorch Dataset format I am using but when I try to access the inputs from the Dataset I get an error.
PyTorch Dataset
The Dataset Returns a Dictionary containing : ids, mask, token_type_ids, targets
class JigsawDataset:
def __init__(... | I figured out the problem.
Incorrect Code
ids = dataset["ids"]
mask = dataset["mask"]
token_type_ids = ["token_type_ids"]
Correct Code
ids = dataset[0]["ids"]
mask = dataset[0]["mask"]
token_type_ids = [0]["token_type_ids"]
The problem was that "... | https://stackoverflow.com/questions/67956097/ |
Pytorch issue with loss and number of epochs | I'm building a neural network by adapting the code shown in curiosily's tutorial. Instead of using weather data, I'm feeding in my own data (all numerical) to solve a time-series regression problem. Under the Finding Good Parameters section, they calculate the loss (difference between calculated and actual output value... | The original post is working with a binary classification problem, where the accuracy metric makes sense (note that the predicted floats are first converted to a boolean tensor: predicted = y_pred.ge(.5).view(-1)).
On the other hand, your question stated that you are working with a regression problem, in which case acc... | https://stackoverflow.com/questions/67977571/ |
TypeError: Int' object is not callable when calling Bert methods for producing embeddings | I have the following code and I obtain 'TypeError: 'tuple' object is not callable'(in new_time) but I dont understand why. I wrote it based on this tutorial
https://jalammar.github.io/a-visual-guide-to-using-bert-for-the-first-time/ and
https://github.com/getalp/Flaubert
My code :
#torch == 1.8.1
#numpy == 1.20.2
#pan... | This is because from_pretrained function gives you a tuple of model and dictionary and you did not separate them. Modify you code like this (add another variable):
flaubert, info = FlaubertModel.from_pretrained(language_model_dir, output_loading_info=True)
You have set output_loading_info to True. So it also return a ... | https://stackoverflow.com/questions/67982333/ |
RuntimeError: Expected 4-dimensional input for 4-dimensional weight | I have a network, in which there are 3 architectures that share the same classifier.
class VGGBlock(nn.Module):
def __init__(self, in_channels, out_channels,batch_norm=False):
super(VGGBlock,self).__init__()
conv2_params = {'kernel_size': (3, 3),
'stride' : (1, 1),
... | From your code & error, I guess you're passing binary image (h, w, 1) to the network.
The issue raises in Conv2d layer, where it expects 4 dimensional input.
To rephrase - Conv2d layer expects 4-dim tensor like:
T = torch.randn(1,3,128,256)
print(T.shape)
out: torch.Size([1, 3, 128, 256])
Where:
The first dimensi... | https://stackoverflow.com/questions/68001067/ |
Both validation loss and accuracy are increasing using a pre-trained VGG-16 | So, I'm doing a 4 label x-ray images classification on around 12600 images:
Class1:4000
Class2:3616
Class3:1345
Class4:4000
I'm using VGG-16 architecture pertained on the imageNet dataset with cross-entrpy and SGD and a batch size of 32 and a learning rate of 1e-3 running on pytorch
[[749., 6., 50., 2.],
[... | I think your question already says about what is going on. Your model is overfitting as you have also figured out. Now, as you are training more your model slowly becoming more specialized to the train set and loosing the the capability to generalize gradually. So the softmax probabilities are getting more and more fla... | https://stackoverflow.com/questions/68004619/ |
Unable to install Pytorch on Mac OS X from scratch due to Pytorch package conflicts with Conda - how to fix? | I have python 3.9 and I am trying to install pytorch current version (as of this writing 1.9). But when I do it I get the following error:
(synthesis) miranda9@Brandos-MBP ~ % conda install pytorch torchvision torchaudio -c pytorch
Collecting package metadata (current_repodata.json): done
Solving environment: failed wi... | For me it seems that adding conda-forge to the channels works. My understanding of why that works is that the pytorch channel doesn't have all packages or something (details here: https://github.com/pytorch/pytorch/issues/59517).
Do:
conda install -y pytorch torchvision torchaudio -c pytorch -c conda-forge
other examp... | https://stackoverflow.com/questions/68010933/ |
Why Resnet model in tensorflow and pytorch give different feature length? | I'm trying to extract features of images through Resnet models pretrained on imagenet dataset as for the network should give the length of 2048 features. When I experimented with TensorFlow it gave the same amount of feature-length but when I try PyTorch version Resnet it gives me the length of 1000.
codes are as below... | Printing the layers of the pytorch resnet will yield:
(fc): Linear(in_features=2048, out_features=1000, bias=True)
as the last layer of the resnet in Pytorch, because the model is by default set up for use as a classifier on imagenet data (1000 classes). If you want 2048 features instead, you can simply delete this la... | https://stackoverflow.com/questions/68020735/ |
Error while creating train transform using torch vision | I am using torch vision to create the following train transformation. I do not understand what's wrong and how I can fix it?
train_transform = torch.nn.Sequential(
transforms.ToTensor(),
transforms.RandomApply([
transforms.RandomApply([transforms.RandomRotation(15)], 0.6),
transforms.RandomAp... | torch.nn.Sequential scripts your transformations. You can only use scriptable transformations in torch.nn.Sequential and transforms.ToTensor() is not a scriptable transformation.
A scriptable transformation only takes a Tensor as an input. This is why you cannot use transforms.ToTensor() in the torch.nn.Sequential func... | https://stackoverflow.com/questions/68024067/ |
Equivalent AdaptiveAvgPool2d API in cuDNN | Is there an equivalent API in cuDNN as the AdaptiveAvgPool2d in Pytorch?
| yes, it's possible. you can create the pooling descriptor.
here is the official documentation for the API-
https://docs.nvidia.com/deeplearning/cudnn/api/index.html#cudnnPoolingMode_t
| https://stackoverflow.com/questions/68029335/ |
RuntimeError: `lengths` array must be sorted in decreasing order when `enforce_sorted` is True. - Pytorch | It have been 5 hours sitting here getting the same error:
RuntimeError: `lengths` array must be sorted in decreasing order when `enforce_sorted` is True. You can pass `enforce_sorted=False` to pack_padded_sequence and/or pack_sequence to sidestep this requirement if you do not need ONNX exportability.
I'm working on ... | After some few minutes I found the solution and I was able to get accuracy of aprox ~93% on a single training epoch.
I changed my LABEL field to:
LABEL = data.LabelField(preprocessing=get_sentiment, dtype = torch.float)
Then i changed my AmazonLSTMRNN model in the forward method by adding enforce_sorted=False to the p... | https://stackoverflow.com/questions/68033951/ |
Albumentations in Pytorch: Inconsistent Augmentation for multi-target datasets | I'm using Pytorch and want to perform the data augmentation of my images with Albumentations. My dataset object has two different targets: 'blurry' and 'sharp'. Each instance of both targets needs to have identical changes. When I try to perform the data augmentation with a Dataset object like this:
class ApplyTransfor... | You can stack your blurry and sharp images, apply your augmentation then unstack them
| https://stackoverflow.com/questions/68040933/ |
Tensorboard in pytorch does not load anything in Browser | I am using tensorboard to monitor the training progress of the model from this codebase. To open tensorboard, I ran the command tensorboard --logdir=checkpoints/ as suggested in the codebase. I know that to open tensorboard, I need to pass the directory path in --logdir where the events file is present, which I did. It... | This issue got resolved once I uninstalled torch_tb_profiler and downgraded Tensorboard 2.5.0 to 1.15.0 as suggested in this answer
| https://stackoverflow.com/questions/68058295/ |
"AssertionError: Cannot handle batch sizes > 1 if no padding token is > defined" and pad_token = eos_token | I am trying to finetune a pre-trained GPT2-model. When applying the respective tokenizer, I originally got the error message:
Using pad_token, but it is not set yet.
Thus, I changed my code to:
GPT2_tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
GPT2_tokenizer.pad_token = GPT2_tokenizer.eos_token
When c... | I've been running into a similar problem, producing the same error message you were receiving. I can't be sure if your problem and my problem were caused by the same issue, since I can't see your full stack trace, but I'll post my solution in case it can help you or someone else who comes along.
You were totally correc... | https://stackoverflow.com/questions/68084302/ |
How to get the size of a Hugging Face pretrained model? | I keep getting a CUDA out of memory error when trying to fine-tune a Hugging Face pretrained XML Roberta model. So, the first thing I want to find out is the size of the pretrained model.
model = XLMRobertaForCausalLM.from_pretrained('xlm-roberta-base', config=config)
device = torch.device("cuda") if torch.cu... | If you facing CUDA out of memory errors, the problem is mostly not the model, rather than the training data. You can reduce the batch_size (number of training examples used in parallel), so your gpu only need to handle a few examples each iteration and not a ton of.
However, to your question:
I would recommend you objs... | https://stackoverflow.com/questions/68086929/ |
Pytorch slowing down after few iterations | I am trying to implement a model in PyTorch. The training procedure is quite complex and take a while, but what I have noticed is that the model is very fast on the first few batches, and then suddenly gets about 500. I guess it is due to some memory leak issue, as if python was not really letting free the memory of re... | Check out this page and scroll down to "Asynchronous execution".
Basically, you are measuring the time to enqueue your operation into the GPU not the time it actually takes to execute your operations. This is because GPU calls are asynchronous as described in the link. I copied the relevant part below:
By de... | https://stackoverflow.com/questions/68087073/ |
How to move multiple tensors to the Cuda device concurrently? | policy_data, value_data, action_mask = policy_data.cuda(non_blocking=True), value_data.cuda(non_blocking=True), action_mask.cuda(non_blocking=True)
rewards, regret_probs = rewards.cuda(non_blocking=True), regret_probs.cuda(non_blocking=True)
return action_probs.cpu(), sample_probs.cpu(), sample_indices.cpu(), update
... | Seems like one potential solution would be to pack all of the data into a single tensor (though of course you'd likely pay a small cost due to unused elements within this compacted representation.) An alternative would be to store this compact tensor as a sparse tensor (no additional data, but slightly more memory cons... | https://stackoverflow.com/questions/68087621/ |
PyTorch CUDA error: an illegal memory access was encountered | Relatively new to using CUDA. I keep getting the following error after a seemingly random period of time:
RuntimeError: CUDA error: an illegal memory access was encountered
I have seen people suggest things such as using cuda.set_device() rather than cuda.device(), setting torch.backends.cudnn.benchmark = False
but I c... | It was partially said by the answer of the OP, but the problem under the hood with illegal memory access is that the GPU runs out of memory.
In my case, when I run a script on Windows I get the error message:
RuntimeError: CUDA out of memory. Tried to allocate 1.64 GiB (GPU 0; 4.00 GiB total capacity; 1.10 GiB already ... | https://stackoverflow.com/questions/68106457/ |
Get file names and file path using PyTorch dataloader | I am using PyTorch 1.8 and Python 3.8 to read images from a folder using the following code:
print(f"PyTorch version: {torch.__version__}")
# PyTorch version: 1.8.1
# Device configuration-
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"currently available device: {device}&... | The default ImageFolder Dataset holds the paths of all images in self.samples. All you need to do is modify __getitem__ to return the paths as well.
| https://stackoverflow.com/questions/68112479/ |
Good accuracy and loss on training vs bad accuracy on validation | I am learning pytorch and I have created binary classification algorithm. After having trained the model I have very low loss and quite good accuracy. However, on validation the accuracy is exactly 50%. I am wondering if I loaded samples incorrectly or the algorithm does not perform well.
Here you can find the plot of ... | Going by your "Training loss and accuracy" plot your model is overfitting. Your train loss is near zero after 25 epochs and you continue training for 200+ epochs. This is wrong way to train a model. You should rather be doing early stopping based on the validation set. ie. Run one epoch of train and one epoch... | https://stackoverflow.com/questions/68113134/ |
difference in code between using nn.RNN or not | hi im new to rnn's and I found RNN NLP FROM SCRATCH from pytorch official tutorials, and I think it's named "from scartch" because it didn't use the nn.RNN built in nn in pytorch some line like this self.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True) in the def __init__(self, input_size, ... | This model is referring the implementation of RNN before autograde module introduce, it is a pure implementation of RNN. In this example hidden state and gradient entirely handled by graph.
def init_hidden(self):
return torch.zeros(1, self.hidden_size)
the line above initializes the hidden state(which is zeros... | https://stackoverflow.com/questions/68116129/ |
What is the purpose of optimizer's state_dict in PyToch Big Graph's embedding dataset? | The documentation for PyTorch Big Graph (PBG) states that "An additional dataset may exist, optimizer/state_dict, which contains the binary blob (obtained through torch.save()) of the state dict of the model’s optimizer." When inspecting this dataset, it seems to be stored as an array of bytes. Could someone ... |
Could someone conceptually explain the point of state_dict
If you know about Adam or SGD's momentum you probably know that there're some parameters in the optimizer that change in every step. When resume training on top of loading the model weights it'll make convergence faster if you load these parameters too.
You c... | https://stackoverflow.com/questions/68118646/ |
Slice a list with two other lists in tensorflow / pytorch | How can I slice a list with two other lists? In another word, how can I do a vectorized slicing in tensorflow?
indptr = [0 2 2 5 7]
values = [2 4 3 2 1 1 5]
values[indptr[:-1]:indptr[1:]] # --> throws exception
expected output:
[[2, 4],
[],
[3, 2, 1],
[1, 5]]
More specifically, I wanna vectorized the following... | In tensorflow, tf.scatter_nd can be used for the purpose.
@tf.function
def csr_to_dense(indptr,indices,values,m,n):
repeats=indptr[1:]-indptr[:-1]
ind1=tf.repeat(tf.range(m),repeats)
indices=tf.stack([ind1,indices],1)
return tf.scatter_nd(indices,values,(m,n))
indptr=tf.constant([0,2,2,5,7])
indices=tf.constan... | https://stackoverflow.com/questions/68122235/ |
pytorch's grid_sample return an incorrect value | I have a 3D matrix: img[i, j, k] = i+j+k.
In my opinion, if I want the value of (1, 2, 3), the grid_sample should return 6. But it not.
The code is:
import torch
from torch.nn import functional as F
import numpy as np
X, Y, Z = 10, 20, 30
img = np.zeros(shape=[X, Y, Z], dtype=np.float32)
for i in range(X):
for j in... | Finally, I find the solution. The reason why the above code return an incorrect value is that the torch.grid_sample accept (z, y, x) point.
Thus, the correct code should be:
import torch
from torch.nn import functional as F
import numpy as np
X, Y, Z = 10, 20, 30
img = np.zeros(shape=[X, Y, Z], dtype=np.float32)
for i ... | https://stackoverflow.com/questions/68131325/ |
huggingface-hub 0.0.12 requires packaging>=20.9, but you'll have packaging 20.4 which is incompatible | huggingface-hub 0.0.12 requires packaging>=20.9, but you'll have packaging 20.4 which is incompatible
enter image description here
| You will have to update the huggingface-hub through
pip install --upgrade huggingface-hub
| https://stackoverflow.com/questions/68140977/ |
I want to get feature value of an object with YOLOv5 | I want to get feature value of an object with YOLOv5. I'm guessing there is a hint in "detect.py" in opensource.
How can I get feature value of the object used for inference?Please tell me how to resolve.
| The variable 'det' inside the def run in detect.py(line 181), you can know the xyxy value, the confidence score, and the number of class name of the object.
Since 'det' is a tensor data type, you will need to converting 'det'.
If you want to get only the number of class name of the object, you can easily get it by conv... | https://stackoverflow.com/questions/68157783/ |
convert pytorch model with multiple networks to onnx | I am trying to convert pytorch model with multiple networks to ONNX, and encounter some problem.
The git repo: https://github.com/InterDigitalInc/HRFAE
The Trainer Class:
class Trainer(nn.Module):
def __init__(self, config):
super(Trainer, self).__init__()
# Load Hyperparameters
self.config... | After research and try, I found a method which maybe in correct way:
Convert each net(Encoder, Mod_Net, Decoder) to onnx model, and handle their input/output in latter logic-process or any further procedure (e.g convert to tflite model).
I'm trying to port onto Android using this method.
#Edit 20210705-03:52GMT#
Anothe... | https://stackoverflow.com/questions/68177899/ |
Read data from numpy array into a pytorch tensor without creating a new tensor | Let's say I have a numpy array arr = np.array([1, 2, 3]) and a pytorch tensor tnsr = torch.zeros(3,)
Is there a way to read the data contained in arr to the tensor tnsr, which already exists rather than simply creating a new tensor like tnsr1 = torch.tensor(arr).
This is a simplified example of the problem, since I am ... | You can do that using torch.from_numpy(arr). Here is an example that shows that it's not being copied.
import numpy as np
import torch
arr = np.random.randint(0,high=10**6,size=(10**4,10**4))
%timeit arr.copy()
tells me that it took 492 ms ± 6.54 ms to copy the array of random integers.
On the other hand
%timeit torc... | https://stackoverflow.com/questions/68183227/ |
Create a CNN that has a Kernel that is 1xD, where D is number of columns that slides vertically over a MxD matrix? | Create a CNN that has a Kernel that is 1xD, where D is number of columns that slides vertically over a MxD matrix?
I'm trying to create a CNN in Pytorch that has a kernel that slides a 1xD kernel over a 2D image vertically so the output should be Mx1. As in the CNN convolves each row of the image then produces a single... | Kernels in nn.Conv2d do not have to be square, they can also be rectangular:
class MyModel(nn.Module):
def __init__(self, in_channels, out_channels, N, D):
super(MyModel, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=(N, D), padding=0, stride=1)
def forward(self, x):
ret... | https://stackoverflow.com/questions/68187971/ |
"torch.relu_(input) unknown parameter type" from pytorch | I am trying to run this 3D pose estimation repo in Google Colab on a GPU, but after doing all of the steps and putting in my own left/right cam vids, I get this error in Colab:
infering thread started
1 1
: cannot connect to X server
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/li... | Since the traceback happens in the pytorch library, I checked the code there on the pytorch github.
What the error means is that you are calling an inplace activation function in torch.relu_ to some object called input. However, what is happening is that the type of input is not recognized by the torch backend which is... | https://stackoverflow.com/questions/68188278/ |
How to implement this equation in pytorch? | I'm trying to implement GNNs from a research paper and I have to code the following equations to get some sort of relatedness scores sj.
Since I am new to pytorch, I'm having some difficulties implementing equations.
Following are the set of equations that I want to code:
I have the following inputs h(t) = input_a = h... | All the operations you could do to pytorch tensors are documented over here:
https://pytorch.org/docs/stable/torch.html
I suggest command + F to search for the operation you need.
For the 1st equations you gave:
You can find torch.tanh() as shown here: https://pytorch.org/docs/stable/generated/torch.tanh.html#torch.ta... | https://stackoverflow.com/questions/68191076/ |
Why the method of log_prob in my Pytorch doesn't work | For example, I have a Beta distribution in Pytorch, and the parameter a=0.01 and b=1.4709.
The density function is as below:
Density function of the Beta distribution
Then I sample an action from this distribution which is 1.1754943508222875e-38.
Now, there is something happened, after I calculate the log_prob of this ... | log_prob returns the log of the probability density/mass function (pdf) evaluated at the given sample value. Probability density mass is not the same as probability since for a continuous distribution like the Beta distribution the probability of any single value is actually 0. As such, there's no stipulation that the... | https://stackoverflow.com/questions/68199047/ |
Graph Neural Network Regression | I am trying to implement a regression on a Graph Neural Network. Most of the examples that I see are that of classification in this area, none so far of regression. I saw one for classification as follows:
from torch_geometric.nn import GCNConv
class GCN(torch.nn.Module):
def __init__(self, hidden_channels):
super(... | add a linear layer,and don't forget use a regression loss function
class GCN(torch.nn.Module):
def __init__(self, hidden_channels):
super(GCN, self).__init__()
torch.manual_seed(12345)
self.conv1 = GCNConv(dataset.num_features, hidden_channels)
self.conv2 = GCNConv(hidden_channels, d... | https://stackoverflow.com/questions/68202388/ |
What are the expected values in the input in Pytorch? | I am new to Pytorch, following the tutorials. I want to implement a regresor for a nonlinear function with 4 real inputs and 2 real outputs. I cannot find anywhere what is the supposed range for the inputs and outputs. They should go between -1 and 1? Between 0 and 1? Can it be anything?
More details
I have written the... | Data transformation
They should go between -1 and 1? Between 0 and 1? Can it be anything?
They can be any real valued numbers, but in general we standardize input values using mean and standard deviation (so the result has 0 mean and 1 variance) like this (for two dimensional data that you have, assuming samples are ... | https://stackoverflow.com/questions/68212002/ |
Where can I get official PyTorch documentation in pdf form? | I want to learn PyTorch in great detail.
I have read all the docs and tutorials on the main site. I learn better from paper. When I print from website pages, I am getting very small letters. This makes the printouts difficult to read them.
The packages offer PDF documentation, but I cannot find a similar file for the m... | I don't think there is an official pdf. The pytorch documentation uses sphinx to generate the web version of the documentation. But sphinx can also generate PDFs.
So you could download the git repo of pytorch, install sphinx, and then generate the PDF yourself using sphinx.
The instructions to built the HTML can be fou... | https://stackoverflow.com/questions/68220613/ |
Why transformations go into the dataset and not into the NN itself in Pytorch? | I am new to Pytorch and I am now following the tutorial on transforms. I see that the transformations are configured into the dataset object. I am wondering, however, why aren't they configured within the neural network itself. My naive point of view is that the transformations should be in any case the most external l... | These are some of the reason that can explain why one would do this.
We would like to use the same NN code for training as well as testing / inference. Typically during inference, we don't want to do any transformation and hence one might want to keep it out of the network. However, you may argue that one can just sim... | https://stackoverflow.com/questions/68221863/ |
nvcc not found but cuda runs fine? | I was trying to run nvcc -V to check cuda version but I got the following error message.
Command 'nvcc' not found, but can be installed with:
sudo apt install nvidia-cuda-toolkit
But gpu acceleration is working fine for training models on cuda. Is there another way to find out cuda compiler tools version. I know nvidia... | Most of the time, nvcc and other CUDA SDK binaries are not in the environment variable PATH. Check the installation path of CUDA; if it is installed under /usr/local/cuda, add its bin folder to the PATH variable in your ~/.bashrc:
export CUDA_HOME=/usr/local/cuda
export PATH=${CUDA_HOME}/bin:${PATH}
export LD_LIBRARY_P... | https://stackoverflow.com/questions/68221962/ |
RuntimeError: Function AddmmBackward returned an invalid gradient | RuntimeError: Function AddmmBackward returned an invalid gradient at index 2 - got [100, 80] but expected shape compatible with [80, 80]
And my NN :
| It could be because of your neural network shape is not compatible to the previous shape.
Try changing your fc1 from nn.Linear(in_feature=80, out_feature=80) to nn.Linear(in_feature=100, out_feature=80)
| https://stackoverflow.com/questions/68222763/ |
pytorch cifar10 dataset - cannot get first item | I have selected the CIFAR 10 dataset using the torchvision library:
trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transforms.ToTensor())
Then I try to select the first item in the dataset, which as I understand implements the get_ite... | I was hitting this error too:
def get_transformations():
return transforms.Compose([transforms.ToTensor()])
...
self.transforms = get_transformations()
...
# Load the image + augment
img = Image.open(img_path).convert("RGB")
img = self.transforms(img)
...
Original Traceback (most recent call last):
... | https://stackoverflow.com/questions/68223871/ |
Almost non-existent training accuracy and low test accuracy | I am really new to Machine Learning and I am not so well versed in coding in general. However there is need to look through the customers feedback at our store, that average quite a lot each year, yet we cannot tell % of positive, negative and neutral.
Currently I am trying to train a Bert Model to do simple multi labe... | Here _, preds = torch.max(outputs, dim=1), you probably want argmax, not max?
Print out preds and targets to better see what's going on.
Edit after preds and targets printed out. For epochs 4 and 5, preds matches targets exactly, so train accuracy should be 1. I think the issue is that the accuracy is divided by n_exam... | https://stackoverflow.com/questions/68225540/ |
Making predictions on new images using a CNN in pytorch | I'm new in pytorch, and i have been stuck for a while on this problem. I have trained a CNN for classifying X-ray images. The images can be found in this Kaggle page https://www.kaggle.com/prashant268/chest-xray-covid19-pneumonia/ .
I managed to get good accuracy both on training and test data, but when i try to make ... | Regarding your problem, I have a really good way to debug this to target where the problem most likely will be and so it will be really easy to fix your issue.
So, my debugging process would be based on the fact that your CNN performs well on the test set. Firstly set your test loader batch size to 1 temporarily. Afte... | https://stackoverflow.com/questions/68239580/ |
How does pytorch.autograd.Function calculate dL_dy? | This code calculate grad of y=x**2.
In this code, dL_dy is [0., 2., 8.] How do they calculate dL_dy? Where did this tensor came from ?
import torch
from torch.autograd import Function
class Square(Function):
@staticmethod
def forward(ctx,input):
ctx.save_for_backward (input)
return torch.squa... | Let say your f(y) = x**2, so f'(y) = 2*x
x = torch.arange(3).to(torch.float64).requires_grad_(True) means x=[0,1,2], we can compute y = x**2 = [0,1,4].
So when you call L.backward(), it will apply f'(y) (calculating the gradient of y), and stored in dL_dy.
That's why dL_dy = f'(y) = 2 * [0,1,4] = [0,2,8]
| https://stackoverflow.com/questions/68241041/ |
Error in creating an offline PDF documentatin for PyTorch | I wanted to make an offline PDF on my system for PyTorch documentation. After reading from several resources #1, #2, #3
git clone https://github.com/pytorch/pytorch
cd pytorch/docs/
make latexpdf
First two commands are working fine. Third command leads to the following error
Traceback (most recent call last):
Fil... | The PyTorch version installed in your machine (1.4.0) is older than the one you cloned (most recent). Two ways to fix it:
Checkout to the version you have installed (if you want the doc of 1.4 version):
git clone https://github.com/pytorch/pytorch
# move back to the 1.4 release, which you have installed in your mach... | https://stackoverflow.com/questions/68244269/ |
RuntimeError: expected scalar type Float but found Double (LSTM classifier) | I'm training my LSTM classifier.
epoch_num = 30
train_log = []
test_log = []
set_seed(111)
for epoch in range(1, epoch_num+1):
running_loss = 0
train_loss = []
lstm_classifier.train()
for (inputs, labels) in tqdm(train_loader, desc='Training epoch ' + str(epoch), leave=False):
inputs, labels = inputs.... |
RuntimeError: expected scalar type Float but found Double
The error at line loss = criterion(outputs, labels) is quite clear in that it requites your datatype to be float rather than double, but it doesn't explicitly say whether outputs or label is creating this.
My guess is its because of labels. Try converting it t... | https://stackoverflow.com/questions/68250903/ |
Easy way to convert a tensor shape In pytorch | Input
I have torch tensor as fallow.
The shape for this input_tensor is torch.size([4,4])
input_tensor =
tensor([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
I'm going to create a tensor that stacks up the tensor that comes out of the above input_tensor by moving th... | You can use torch.split() together with torch.cat() as follows:
output_tensor = torch.cat(torch.split(input_tensor, 2, dim=1))
The ouput with be:
output =
tensor([[ 0, 1],
[ 4, 5],
[ 8, 9],
[12, 13],
[ 2, 3],
[ 6, 7],
[10, 11],
[14, 15]])
| https://stackoverflow.com/questions/68254939/ |
About pytorch tensor caculation | I want to ask a question about torch calculation that if I only want to subtract the elements on the diagonal of the matrix without changing the elements in the remaining positions, is there any way to achieve it?
| One way to do this is by getting the diagonal, doint the required operation on its elements and replacing the original one. Example code:
x = torch.rand(3, 3)
#get the original diagonal and for example substract 3
replaced_diag = x.diagonal() - 3
#replace the original diagonal
x.diagonal().copy_(replaced_diag)
For ref... | https://stackoverflow.com/questions/68255093/ |
Pytorch - RuntimeError: Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss_forward | I was trying & experimenting something with PyTorch, where I created my own inputs & targets. I fed these inputs to the model (which is a basic ANN with 2 hidden layers, nothing wrong with that). But for some reason I am not being able to calculate the CrossEntropyLoss(). I am not being able to figure out why. ... | I could replicate you error using this code.
import torch.nn as nn
loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.tensor([1., 2., 3.])
loss(input, target)
Error:
RuntimeError: expected scalar type Long but found Float
changed the datatype of target to target = torch.tensor(... | https://stackoverflow.com/questions/68256087/ |
Pytorch: gradient computation fails when in-place operation follows certain functions | Consider the following piece of code:
import torch
from torch import nn
a = torch.tensor([1.], requires_grad=True)
b = nn.Tanh()(a)
# b = nn.Linear(1,1)(a)
b *= 1
# b = b * 1
b.sum().backward()
Running the code results in RuntimeError:
RuntimeError: one of the variables needed for gradient computation has been modifie... | I just found some text from the Pytorch official site:
In-place correctness checks
Every tensor keeps a version counter, that is incremented every time it is marked dirty in any operation. When a Function saves any tensors for backward, a version counter of their containing Tensor is saved as well. Once you access sel... | https://stackoverflow.com/questions/68256550/ |
Installing pytorch with conda | I've just been trying to dabble in AI in the past few weeks, I've tried installing pytorch with conda and it all seems to work but then I get the error:
ImportError: /home/lp35791/.local/lib/python3.8/site-packages/torch/lib/libtorch_cuda.so: cannot read file data
I've been trawling through the web but can't seem to fi... | You seem to have installed PyTorch in your base environment, you therefore cannot use it from your other "pytorch" env.
Either:
directly create a new environment (let's call it pytorch_env) with PyTorch: conda create -n pytorch_env -c pytorch pytorch torchvision
switch to the pytorch environment you have alre... | https://stackoverflow.com/questions/68267305/ |
Poetry hangs when installing torch | I'm trying to add pytorch_pretrained_bert package, but it hangs on downloading torch. I've been waiting for almost 30 mins already. I'm running this command: poetry add pytorch_pretrained_bert -vvv and the output is as such:
PS C:\Users\aaaa\Desktop\AI\nexus\ocr> poetry add pytorch_pretrained_bert -vvv
Using virtual... | TL;DR: This is easily verified by either a green colored version number and dot as shown in this screenshot or running poetry run <package> --version and having successful output.
Short Answer
When I've installed packages with Poetry, I've seen some packages, like pylint, only display the line
Installing pylint (... | https://stackoverflow.com/questions/68270223/ |
Conv2D padding in TensorFlow and PyTorch | I am trying to convert TensorFlow model to PyTorch but having trouble with padding. My code for for relevant platforms are as follow:
TensorFlow
conv1 = tf.layers.conv2d(
inputs=input_layer,
filters=32,
kernel_size=[5, 5],
padding="same",
... | To answer your questions:
The reason why Pytorch doesn't have padding = 'same' to quite simply put it is due to its dynamic computation graph in comparison to Tensorflow static graph.
Both the codes are not equivalent as different padding is used.
'Same' padding tries to pad evenly on the left and right, but if the a... | https://stackoverflow.com/questions/68271586/ |
Why does torch.scatter requires a smaller shape for indices than values? | A similar question was already asked here, but I think the solution is not suited for my case.
I just wonder why it is not possible to do a torch.scatter operation, where my index tensor is bigger than my value tensor. In my case I have duplicate indices, e.g. the following value tensor a and the index tensor idx:
a = ... | Not a solution, but a workaround:
a = torch.tensor([[0, 1, 0, 0],
[0, 0, 1, 0]])
idx = torch.tensor([[1, 1, 2, 3, 3],
[0, 0, 1, 2, 2]])
rows = torch.arange(0, a.size(0))[:,None]
n_col = idx.size(1)
a[rows.repeat(1, n_col), idx] = 1
rows.repeat(1, n_col) gives the row index to th... | https://stackoverflow.com/questions/68274722/ |
ValueError: no gopen handler defined | I am new to using webdataset library from pytorch. I have created .tar files of a sample dataset present locally in my system using webdataset.TarWriter(). The .tar files creation seems to be successful as I could extract them separately on windows platform and verify the same dataset files.
Now, I create train_dataset... | I have had the same error since yesterday, I finally found the culprit. WebDataset/tarIterators.py makes use of WebDataset/gopen.py. In gopen.py urllib.parse.urlparse is called to parse the url to be opened, in your case the url is D:/PhD/....
gopen_schemes = dict(
__default__=gopen_error,
pipe=gopen_pipe,
... | https://stackoverflow.com/questions/68299665/ |
Convert tensor of integers to binary tensor with 1 only at that index | Is there a pain free to convert a tensor of integers to a binary tensor with 1 only at that integers index in pytorch?
e.g.
tensor([[1,3,2,6]])
would become
tensor([[0,1,0,0,0,0,0],
[0,0,0,1,0,0,0],
[0,0,1,0,0,0,0],
[0,0,0,0,0,0,1]])
| t = tensor([[1,3,2,6]])
rows = t.shape[1]
cols = t.max() + 1
output = torch.zeros(rows, cols) # initializes zeros array of desired dimensions
output[list(range(rows)), t.tolist()] = 1 # sets cells to 1
To clarify the last operation, you can pass in a list of the row numbers and column numbers, and it will set all th... | https://stackoverflow.com/questions/68308241/ |
How to understand decoder_start_token_id and forced_bos_token_id in mbart? | When I want to use huggingface's pretrained models such as mbart to conduct multilingual experiments, the meaning of paramaters decoder_start_token_id and forced_bos_token_id confuse me. I find codes like:
# While generating the target text set the decoder_start_token_id to the target language id.
# The following exam... | In the standard sequence-to-sequence models, the decoding starts with providing the decoder with the [bos] symbols, it generates the word w1, which is provided as the input of the decoder in the next step. and the decoder generates the word w2. This continues until the [eos] (end-of-sentence) token is generated.
[bos] ... | https://stackoverflow.com/questions/68313263/ |
Classification in LSTM returns same value for classification | This is my first time posting in stack overflow so forgive me if I do any sort of mistake.
I have 10000 data, and each data has a label of 0 and 1. I want to perform classification using LSTM as this is time series data.
input_dim = 1
hidden_dim = 32
num_layers = 2
output_dim = 1
# Here we define our model as a class... | A common phenomenon in NN training is that they will initially converge to a very naive solution to the problem where they output a constant prediction that minimizes the error on the training data. My guess is that in your training data, the ratio between 0 and 1 classes is close to 0.5423. Depending on whether your m... | https://stackoverflow.com/questions/68315278/ |
Hermetic / Non Hermetic Packages in Python | While going through PyTorch documentation, I came across the term hermetic packages:
torch.package adds support for creating hermetic packages containing arbitrary PyTorch code. These packages can be saved, shared, used to load and execute models at a later date or on a different machine, and can even be deployed to p... | In the context, hermatic is used to mean that the already preinstalled libraries and configuration of your machine you are running on (macos laptop, to windows desktop, etc.) will be able to build Pytorch and its depedancies in an identical way.
The following link has a section on hermatic builds:
https://www.google.co... | https://stackoverflow.com/questions/68321832/ |
Retrieving intermediate features from pytorch torch.hub.load | I have a Net object instantiated in pytorch via torch.hub.load:
model = torch.hub.load('facebookresearch/pytorchvideo', 'slowfast_r50', pretrained=True)
The final layer is a projection to a 400-dim vector. Is there a way to get the pentultimate layer instead during a forward pass?
| Yes, easiest way is to switch the layer with torch.nn.Identity (which simply returns it's inputs unchanged):
Line below changes this submodule:
(6): ResNetBasicHead(
(dropout): Dropout(p=0.5, inplace=False)
(proj): Linear(in_features=2304, out_features=400, bias=True)
(output_pool): AdaptiveAvgPool3d(... | https://stackoverflow.com/questions/68324172/ |
My Loss Function doesn't get smaller values during training | I am trying to predict the center of my palm
The structure of my neural network consists of 2 cnn which both are followed by max-pooling and a linear layer that has 2 outputs, one for x and the other one for y. The input is a 720x720 image.
class MyNeuralNetwork(torch.nn.Module):
def __init__(self):
super(M... | Your loss values are extremly high as you see. I would propose that you normalize your outputs by using the sigmoid activation function. Now the coordinates are in the range 0-1 and can be later translated to the image by multiplying them with 720. To calculate the loss, you have to divide your target cooridnates by 72... | https://stackoverflow.com/questions/68335560/ |
How to calculate Gradient of the loss with respect to input? | I have a pre-trained PyTorch model. I need to calculate the gradient of the loss with respect to the network's inputs using this model (without training again and only using the pre-trained model).
I wrote the following code, but I am not sure it is correct or not.
test_X, test_y = load_data(mode='test')
testse... |
does this list gradient_losses actually storing what I wish to store?
Yes, if you are looking to get the derivative of the loss with respect to the input then that seems to be the correct way to do it. Here is minimal example, take f(x) = a*x. Then df/dx = a.
>>> x = torch.rand(10, requires_grad=True)
>&g... | https://stackoverflow.com/questions/68338357/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.