instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
PyTorch tensors topk for every tensor across a dimension | I have the following tensor
inp = tensor([[[ 0.0000e+00, 5.7100e+02, -6.9846e+00],
[ 0.0000e+00, 4.4070e+03, -7.1008e+00],
[ 0.0000e+00, 3.0300e+02, -7.2226e+00],
[ 0.0000e+00, 6.8000e+01, -7.2777e+00],
[ 1.0000e+00, 5.7100e+02, -6.9846e+00],
[ 1.0000e+00, 4.4070e+03, -7.1008e+00],
[... | I did it like this:
val, ind = inp[:, :, 2].squeeze().topk(k=4, dim=1, sorted=True)
new_ind = ind.unsqueeze(-1).repeat(1,1,3)
result = inp.gather(1, new_ind)
I don't know if this is the best way to do this but it worked.
| https://stackoverflow.com/questions/66906505/ |
How is PyTorch's Class BCEWithLogitsLoss exactly implemented? | According to the PyTorch documentation, the advantage of the class BCEWithLogitsLoss() is that one can use the
log-sum-exp trick for numerical stability.
If we use the class BCEWithLogitsLoss() with the parameter reduction set to None, they have a formula for that:
I now simplified the terms, and obtain after some l... | nn.BCEWithLogitsLoss is actually just cross entropy loss that comes inside a sigmoid function. It may be used in case your model's output layer is not wrapped with sigmoid. Typically used with the raw output of a single output layer neuron.
Simply put, your model's output say pred will be a raw value. In order to get p... | https://stackoverflow.com/questions/66906884/ |
Confused on using dropout in batch gradient descent with Q-learning | I am using PyTorch and adding dropout layers to my inner layers.
class MLP(nn.Module):
#def __init__(self, n_inputs, n_action, n_hidden_layers=2, hidden_dim=8, drop=0.25):
def __init__(self, console_file, n_inputs, n_action, layers_list, drop=0.25):
super(MLP, self).__init__()
print("Layers structure:&... | I'm not sure what is the problem, but let me try to explain how things work.
The .train() and .eval() calls only change the .training flag to True or False.
The Dropout layer samples the noise during the forward pass. Here's an example of forward implementation (I removed the ifs for the alpha and feature dropouts for ... | https://stackoverflow.com/questions/66917708/ |
Saving a pytoch tensor as a 32-bit grayscale Image | I have manipulated a 32-bit grayscale .tif image which I converted to tensor using PIL. After this I saved it with:
torchvision.utils.save_image(train_img_poac,fp=str(j)+".tif")
This method automatically converts the tensor to an RGB format image. I want my output image to be a 32-bit grayscale image.
I trie... | Unfortunately save_image doesn't have an option for preserving one-channel images. You can use a different library like OpenCV:
import cv2
image = train_img_poac.numpy()
cv2.imwrite('image_name', image)
| https://stackoverflow.com/questions/66929030/ |
AttributeError:module 'torchtext.data' has no attribute 'TabularDataset' | I want to create a dataset from a tsv file with pytorch.
I was thinking of using
torchtext.data.TabularDataset.splits
but I'm getting an error message.
AttributeError:module 'torchtext.data' has no attribute 'TabularDataset'
| Try torchtext.legacy.data.TabularDataset.splits
| https://stackoverflow.com/questions/66931604/ |
"module 'torchtext.data' has no attribute 'Field'" | import torchtext
ENGLISH = torchtext.data.Field(tokenize=tokenizer_english, lower=True, init_token="<sos>", eos_token="<eos>")
Error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
... |
[BC Breaking] Legacy
In v0.9.0 release, we move the following legacy code to torchtext.legacy. This is part of the work to revamp the torchtext library and the motivation has been discussed in Issue #664:
torchtext.legacy.data.field
torchtext.legacy.data.batch
torchtext.legacy.data.example
torchtext.legacy.data.itera... | https://stackoverflow.com/questions/66945577/ |
In Pytorch, is there a difference between (x<0) and x.lt(0)? | Suppose x is a tensor in Pytorch. One can either write:
x_lowerthanzero = x.lt(0)
or:
x_lowerthanzero = (x<0)
with seemingly the exact same results. Many other operations have Pytorch built-in equivalents: x.gt(0) for (x>0), x.neg() for -x, x.mul() etc.
Is there a good reason to use one form over the other?
| They are equivalent. < is simply a more readable alias.
Python operators have canonical function mappings e.g:
Algebraic operations
Operation
Syntax
Function
Addition
a + b
add(a, b)
Subtraction
a - b
sub(a, b)
Multiplication
a * b
mul(a, b)
Division
a / b
truediv(a, b)
Exponentiation
a ** b
pow(a, b... | https://stackoverflow.com/questions/66965389/ |
ValueError: Unknown CUDA arch (8.6) or GPU not supported | when I build DCNv2 in my conda environment,I got this message.
I have checked cuda by nvidia-smi:
Tue Apr 6 20:03:13 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.67 Driver Version: 460.67 CUDA Version: 11.2 |
|-----------------------------... | Your GPU is "too new" for CUDA 10. Support for cards with compute capability 8.6 like yours was added in CUDA 11.1 (thank you @RobertCrovella for the correction). This means you'll need to use CUDA 11.1 or newer.
| https://stackoverflow.com/questions/66968382/ |
how to change the labels in a datafolder of pytorch? | I first load an unlabeled dataset as following:
unlabeled_set = DatasetFolder("food-11/training/unlabeled", loader=lambda x: Image.open(x), extensions="jpg", transform=train_tfm)
and now since I'm trying to conduct semi-supervised learning: I'm trying to define the following function. The input &quo... | PyTorch DataSets can return tuples of values, but they have no inherent "features"/"target" distinction. You can create your modified DataSet like so:
labeled_data = [*zip(dataset, labels)]
data_loader = DataLoader(labeled_dataset, batch_size=batch_size, shuffle=False)
for imgs, labels in data_load... | https://stackoverflow.com/questions/66971274/ |
PyTorch warning about using a non-full backward hook when the forward contains multiple autograd Nodes | After a recent upgrade, when running my PyTorch loop, I now get the warning
Using a non-full backward hook when the forward contains multiple autograd Nodes`".
The training still runs and completes, but I am unsure where I am supposed to place the register_full_backward_hook function.
I have tried adding it to e... | PyTorch version 1.8.0 deprecated register_backward_hook (source code) in favor of register_full_backward_hook (source code).
You can find it in the patch notes here: Deprecated old style nn.Module backward hooks (PR #46163)
The warning you're getting:
Using a non-full backward hook when the forward contains multiple a... | https://stackoverflow.com/questions/66994662/ |
Installing PyTorch on Jetson Nano Ubuntu 18 | I am trying to install PyTorch on Jetson Nano Ruining Ubuntu 1804. My reference is https://dev.to/evanilukhin/guide-to-install-pytorch-with-cuda-on-ubuntu-18-04-5217
When I try the following command this is what I get:
(my_env) crigano@crigano-desktop:~$ python3.8 -m pip install numpy ninja pyyaml mkl mkl-include setup... | If you just want to use PyTorch on the bare-metal Jetson Nano, simply install it with NVIDIA's pre-compiled binary wheel. Other packages can be found in the Jetson Zoo.
MKL is developed by Intel "to optimize code for current and future generations of Intel® CPUs and GPUs." [PyPI]. Apparently it does run on ot... | https://stackoverflow.com/questions/66995722/ |
Get a list of tensor from masked indices | I'm trying to get a list of tensors based on different group,
e.g.,
x = tensor([ 0.3018, -0.0079, 1.4995, -1.4422, 1.6007])
indices = torch.tensor([0,0,1,1,2])
res = func(x,indices)
I want my result to be
res= [[0.3018, -0.0079], [1.4995, -1.4422], [1.6007]]
I'm wondering how can I achieve this result, I checked... | How about
res = [x[indices == i_] for i_ in indices.unique()]
| https://stackoverflow.com/questions/66997166/ |
loading model failed in torchserving | i learning to serve a model using pytorch serving and i am new to this serving
this is the handler file i created for serving the vgg16 model
i am using the model from kaggle
Myhandler.py file
import io
import os
import logging
import torch
import numpy as np
import torch.nn.functional as F
from PIL import Image
from... |
i am using the model from kaggle
I presume you got the model from https://www.kaggle.com/pytorch/vgg16
I think you are loading the model incorrectly.
You are loading a checkpoint, which would work if your model was saved like this:
torch.save({
'epoch': epoch,
'model_state_dict': model.state_dict(),
... | https://stackoverflow.com/questions/67000060/ |
PyTorch input/output data sizes | I'm trying out PyTorch for the first time, and running into a couple problems. I've shared some of my code below and have two questions.
Q1: What should my output size be? Each input should lead to one output, equal to one of 6 possible output labels (1-6). Should output size be 1 or 6?
Q2: Something is wrong with my a... |
Pytorch's CrossEntropyLoss expects output of size (n) (with the score of each of the n classes) and label as an integer of the correct class's index.
Your rnn based model is spitting out tensors of shape [batch, input_size, 6], since it is an rnn and producing a sequence of the same length as the input (with 6 scores ... | https://stackoverflow.com/questions/67005759/ |
Pytorch: how to change requires_grad to be true in an OrderedDict | Suppose I have a neural network object from torch.nn, by default the requires_grad is False for its parameters. I want to change it to be True. But the following naive approach fails:
From torch import nn
a = nn.Linear(1, 1)
a.state_dict()[‘weight’].requires_grad = True
print(a.state_dict()[‘weight’].requires_grad)
Th... | By default trainable nn objects parameters will have requires_grad=True.
You can verify that by doing:
import torch.nn as nn
layer = nn.Linear(1, 1)
for param in layer.parameters():
print(param.requires_grad)
# or use
print(layer.weight.requires_grad)
print(layer.bias.requires_grad)
To change requires_grad stat... | https://stackoverflow.com/questions/67010964/ |
PyTorch - Change weights of Conv2d | For some reason, I cannot seem to assign all the weights of a Conv2d layer in PyTorch - I have to do it in two steps. Can anyone help me with what I am doing wrong?
layer = torch.nn.Conv2d(in_channels=1, out_channels=2, kernel_size=(2,2), stride=(2,2))
layer.state_dict()['weight']
gives me a tensor of size (2,1,2,2)
t... | I'm not sure about why you can't directly assign them but the more proper way to achieve what you're trying to do would be
layer.load_state_dict({'weight': torch.tensor([[[[0.4738, -0.2197],
[-0.3436, -0.0754]]],
[[[0.1662, 0.4098],
[-0.4306, -0.4828]]]])}... | https://stackoverflow.com/questions/67014613/ |
Different test results with pytorch lightning | I use Pytorch Lightning to train a small NN transfert learning) with the hymenoptera photos (inspired from here).
In the test_step method, it prints the real classes (classes) and the predictions (preds).
After the training, I do the same (verification step) but I get different results.
import torch
from torch import n... | I realize that I forget to add:
model.freeze()
before using the model for the second time.
So, now, both results are the same.
| https://stackoverflow.com/questions/67028391/ |
Detectron2 Speed up inference instance segmentation | I have working instance segmentation, I'm using "mask_rcnn_R_101_FPN_3x" model. When I inference image it takes about 3 second / image on GPU. How can I speed up it faster ?
I code in Google Colab
This is my setup config:
cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmen... | There is a third way. You could use a faster toolkit for the inference e.g. OpenVINO. OpenVINO is optimized specifically for Intel hardware but it should work with any CPU. It optimizes your model by converting to Intermediate Represantation (IR), performing graph pruning and fusing some operations into others while pr... | https://stackoverflow.com/questions/67035685/ |
Understanding custom policies in stable-baselines3 | I was trying to understand the policy networks in stable-baselines3 from this doc page.
As explained in this example, to specify custom CNN feature extractor, we extend BaseFeaturesExtractor class and specify it in policy_kwarg.features_extractor_class with first param CnnPolicy:
model = PPO("CnnPolicy", &qu... | What I can say after i went through all the library code. CnnPolicy is differ to MlpPolicy only in implemented default BaseFeatureExtraction class. This make sense only in a case when you are not trying to create your custom BaseFeatureExtraction class.
Let me try to explain, we can see two types of policies:
MlpPolicy... | https://stackoverflow.com/questions/67036250/ |
How to reshape multichannel image with a PyTorch encoder? | I have a tensor with dimensions [18, 512, 512], representing grayscale heatmaps for up to 18 specific objects on a 512x512 image. In order to generate a suitable representation of this image for my conditional GAN, I need to reshape this tensor into a [512, 4, 4] shape using an encoder. However, I can't understand how ... | You can try a couple of different approaches for your problem, like viewing it as a one big vector then slowly reducing it to your size, or permuting dimensions and applying different operations etc. Since there is no full code for testing it on the actual problem, I can't really say which will work better, but my firs... | https://stackoverflow.com/questions/67049161/ |
AttributeError in torch_geometric.transforms | I have a problem that I cannot understand: even though a module ‘torch_geometric.transforms’ has an attribute ‘AddTrainValTestMask’ according to documentation , I cannot import it. I keep receiving an error AttributeError: module 'torch_geometric.transforms' has no attribute 'AddTrainValTestMask
My Pytorch version is 1... | It has been renamed to RandomNodeSplit in the latest version of torch_geometric. You can directly use RandomNodeSplit to replace it.
| https://stackoverflow.com/questions/67064190/ |
Worker timeout when preloading Pytorch model in Flask app on Render.com | In my app.py I have a function that uses a pretrained Pytorch model to generate keywords
@app.route('/get_keywords')
def get_keywords():
generated_keywords = ml_controller.generate_keywords()
return jsonify(keywords=generated_keywords)
and in ml_controller.py I have
def generate_keywords():
model = load_ke... | The problem is that there's some bug that occurs for Pytorch models when Gunicorn is started with the --preload flag.
Render.com secretly adds this flag and doesn't show it in the settings which is why it took me days to figure this out. You can see all settings Render.com adds by calling printenv in the console.
To re... | https://stackoverflow.com/questions/67069183/ |
Pytorch: load checkpoint from batch without iterating over dataset again | Instead of loading from an epoch wise checkpoint I need to be able to load from a batch. I am aware that this is not optimal but since I only have limited training time before my training gets interrupted (google colab free version) I need to be able to load from the batch it stopped or around that batch.
I also do not... | You can achieve your goal by creating a custom Dataset class with a property self.start_index=step*batch and in your __getitem__ function the new index should be (self.start_index+idx)%len(self.data_qs)
If you create your Dataloader with shuffle=False then this tricks will work.
Additionally, With shuffle=True you can ... | https://stackoverflow.com/questions/67072628/ |
Finding function/class definitions in PyTorch | I want to find out where certain classes and functions are defined within PyTorch (and other libraries).
Unfortunately, the following doesn't work:
import inspect
import torch
inspect.getsource(torch.tensor)
It throws the following error:
TypeError: module, class, method, function, traceback, frame, or code object wa... | this is actually complicated. Pytorch/libtorch is a huge project, and it relies on a lot of builtin low-level functions which have been implemented in C/Cuda. Most low-level kernels (math operations for example) even have several implementations, in order to optimize differently for the CPU and the GPU etc.
So there is... | https://stackoverflow.com/questions/67077747/ |
Decode a json file properly, when get it as an input via message request | I would like to read a request, sent via curl, as given below:
curl -X POST http://127.0.0.1:8080/eval/res -v path/request.json. With the json having the following format:
{
"imgX": [{
"key": "x",
"url": "http://127.0.0.1:8080/imgs/x.png"
}],
... | To avoid problems with json responses from APIs, you can use the json lib. In particular json.loads() returns a dictionary so you don't have to convert things manually.
For example:
import json
with open('<path_to_file>/request.json','r') as f:
data = f.read()
_json = json.loads(data)
print(_json)
... | https://stackoverflow.com/questions/67078988/ |
How to load/fetch the next data batches for the next epoch, during the current epoch? | I know that since PyTorch 1.7.0 it is possible to prefetch some batches before an epoch begins. However, this does not make it possible to fetch batches while the operations within an epoch are being performed and before the next epoch begins. Based on this thread, it seems that it should be possible to use a Sampler t... | You can prefetch the next batches from iterator in a background thread.
class _ThreadedIterator(threading.Thread):
"""
Prefetch the next queue_length items from iterator in a background thread.
Example:
>> for i in bg_iterator(range(10)):
>> print(i)
""&... | https://stackoverflow.com/questions/67085517/ |
nn.DataParallel - Training doesn't seem to start | I am having a lot of problems using nn.DistributedDataParallel, because I cannot find a good working example of how to specify GPU id's within a single node. For this reason, I want to start off by using nn.DataParallel, since it should be easier to implement. According to the documentation [https://pytorch.org/docs/st... | I am making a guess here and I haven't tested it since I don't have multiple GPUs.
Since your suppose to load it to parallel first then move it to gpu
model = Model(arg)
model = torch.nn.DataParallel(model, device_ids=[1, 8, 9])
model.to(device)
You can check out here the tutorial I referenced here: https://pytorch.or... | https://stackoverflow.com/questions/67096073/ |
PyTorch: Zero all elements of vector except top k? | I am trying to create a new activation layer, let’s call it topk, that would work as follows. It will take a vector x of size n as input (result of multiplying previous layer output by weight matrix and adding bias) and a positive integer k and would output a vector topk(x) of size n whose elements are:
x... | You can use torch.topk for this:
k = 2
output = torch.randn(5)
vals, idx = output.topk(k)
topk = torch.zeros_like(output)
topk[idx] = vals
>>> topk
tensor([1.0557, 0.0000, 0.0000, 1.4562, 0.0000])
Note that while the 'values' of topk() are differentiable, the 'indices' are not (similar to how argmax is not ... | https://stackoverflow.com/questions/67099961/ |
expected np.ndarray (got DataFrame) | I wanted to find out the output_size of a convolution operation, but I am strugglin with converting my dataframe into a tensor.
output_size = torch.nn.Conv2d(3, 5, 5,stride=1, padding=3,
dilation=1, groups=1, bias=True, padding_mode='zeros')
fashion = torch.from_numpy(load_fashion)
input_ = torch.T... | I can't completely understand your problem as your code is not formatted properly in your question but the error is just an expected datatype error.
You need to convert your dataframe to a np array. Just add .values at the end of your dataframe. So if your input was a sample dataframe like so:
df = pd.DataFrame({"... | https://stackoverflow.com/questions/67110207/ |
_C.cpython-38-x86_64-linux-gnu.so: undefined symbol: _ZN6caffe28TypeMeta21_typeMetaDataInstanceIdEEPKNS_6detail12TypeMetaDataEv | What is the reason for this error and how can I fix it? I am running the code from this repo: https://github.com/facebookresearch/frankmocap
(frank) mona@goku:~/research/code/frankmocap$ python -m demo.demo_frankmocap --input_path ./sample_data/han_short.mp4 --out_dir ./mocap_output
Traceback (most recent call last):
... | I tried the solutions mentioned here, but that didn't fully solve the problem. However, when I tried solving a different error using this solution, it also solved this error for me. Use the following command:
pip install torch==1.8.0+cu111 torchvision==0.9.0+cu111 torchaudio==0.8.0 -f https://download.pytorch.org/whl/t... | https://stackoverflow.com/questions/67117097/ |
extracting subtensor from a tensor according to an index tensor | I have this tensor:
tensor([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
and I have this index tensor:
tensor([0, 1])
and what I want to get is the subtensors according to dim 1 and the corresponding indices in the index tensor, that is:
tensor([[1, 2],
[7, 8]])
tried to use torch.gather() ... | You are implicitly using the index of each value of your index tensor. They just happen to be the same as the values. If you want to walk through the first level, elements of the tensor, you can use torch.arange to construct the first level indices.
import torch
from torch import tensor
t = tensor([[[1, 2],
... | https://stackoverflow.com/questions/67123934/ |
Torch doesnt see gpu on gcloud with deep learning containers | I am trying to run some python code on kubernetes in GCloud, I am using pytorch and for the base image i am using gcr.io/deeplearning-platform-release/pytorch-gpu/.
Everything spins up fine, and my model trains but only using CPU. When i run the following
>>> import torch
>>> torch.cuda.is_available()... | The problem is that you have a NVIDIA driver that supports up to CUDA 10.1 and you installed a PyTorch built on CUDA 11.1. To solve that issue you can:
Update your NVIDIA driver to one that supports CUDA 11.1, or
Install a PyTorch compatible with CUDA 10.1 (which is compatible with your NVIDIA driver)
For the option ... | https://stackoverflow.com/questions/67125766/ |
"TextInputSequence must be str” error on Hugging Face Transformers | I’m very new to HuggingFace, I’ve come around this error “TextInputSequence must be str” on a notebook which is helping me a lot to do some practice on various hugging face models. The boilerplate code on the notebook is throwing this error (I guess) due to some changes in huggingface’s API or something. So I was wonde... | This is an issue with data , the data consists of None type or other data type except string
| https://stackoverflow.com/questions/67138037/ |
PyTorch indexing: select complement of indices | Say I have a tensor and index:
x = torch.tensor([1,2,3,4,5])
idx = torch.tensor([0,2,4])
If I want to select all elements not in the index, I can manually define a Boolean mask like so:
mask = torch.ones_like(x)
mask[idx] = 0
x[mask]
is there a more elegant way of doing this?
i.e. a syntax where I can directly pass ... | I couldn't find a satisfactory solution to finding the complement of a multi-dimensional tensor of indices and finally implemented my own. It can work on cuda and enjoys fast parallel computation.
def complement_idx(idx, dim):
"""
Compute the complement: set(range(dim)) - set(idx).
idx is a m... | https://stackoverflow.com/questions/67157893/ |
YoloV5 killed at first epoch | I'm using a virtual machine on Windows 10 with this config:
Memory 7.8 GiB
Processor Intel® Core™ i5-6600K CPU @ 3.50GHz × 3
Graphics llvmpipe (LLVM 11.0.0, 256 bits)
Disk Capcity 80.5 GB
OS Ubuntu 20.10 64 Bit
Virtualization Oracle
I installed docker for Ubuntu as described in the official documentation.
I pulled the... | The problem was, that the VM ran out of RAM. The solution was to create 16 GB of swap memory, so the machine can use the virtual harddrive as RAM.
| https://stackoverflow.com/questions/67160576/ |
Are the random transforms applied at each epoch in my Pytorch convolutional neural net? (data augmentation) | I'm new to Pytorch and I try to make a convolutional neural net to classify a set of images (personal iris recognition problem). My issue is that I have a small number of images (10 classes and 20 images per class). I tried to make data augmentation (random transforms for every epoch) but I'm not sure that these are ap... | Hi what i meant wasn't like that but the following and i cannot completely reproduce since i dont have your function AddGaussianNoise
import torchvision.transforms as T
import numpy as np
transforms = T.Compose([
T.ToPILImage(), # You need to add this to pil image
T.RandomCrop(5), T.RandomHorizontalFlip(p=0.1)... | https://stackoverflow.com/questions/67184229/ |
LSTM-CNN to classify sequences of images | I got an assignment and stuck with it while going down the rabbit hole of learning PyTorch, LSTM and cnn.
Provided the well known MNIST library I take combinations of 4 numbers and per combination it falls down into one of 7 labels.
eg:
1111 label 1 (follow a constant trend)
1234 label 2 increasing trend
4321 label 3 d... | Change your input size from 28 to 784. (784=28*28).
Input size argument is the number of features in one element of the sequence, so the number of feature of an mnist image, so the number of pixels which is width*hight of the image.
| https://stackoverflow.com/questions/67195464/ |
save model output in pytorch | dic = []
for step, batch in tqdm(enumerate(train_dataloader)):
inpt = batch[0].to(device)
msks = batch[1].to(device)
#Run the sentences through the model
outputs = model_obj(inpt, msks)
dic.append( {
'hidden_states': outputs[2],
'pooled_output': outputs[1]})
I want to save the model output in each iteration b... | First of all, you should always post the full error stacktrace. Secondly, you should move the outputs from your GPU when you want to store them to free up memory:
dic.append( {
'hidden_states': outputs[2].detach().cpu().tolist(),
'pooled_output': outputs[1].detach().cpu().tolist()
})
| https://stackoverflow.com/questions/67195895/ |
PyTorch DataLoader uses identical random transformation across each epoch | There is a bug in PyTorch/Numpy where when loading batches in parallel with a DataLoader (i.e. setting num_workers > 1), the same NumPy random seed is used for each worker, resulting in any random functions applied being identical across parallelized batches. This can be resolved by passing a seed generator to the w... | The best way I can think of is to use the seed set by pytorch for numpy and random:
import random
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
def worker_init_fn(worker_id):
torch_seed = torch.initial_seed()
random.seed(torch_seed + worker_id)
if torch_seed >= 2**30: ... | https://stackoverflow.com/questions/67196075/ |
Pytorch cosine similarity NxN elements | I have 128 vectors of embeddings
image.shape = torch.Size([128, 512])
text.shape = torch.Size([128, 512])
And I want to calculate the tensor containing the cosine similarity between all elements (i.e:
cosine.shape = torch.Size([128, 128])
Where the first row is the cosine similarity between the 1st image and all text... | The way pytorch computes cosine similarity internally is like this:
def cos_sim(A, B, dim, eps=1e-08):
numerator = torch.mul(A, B).sum(axis=dim, keepdims=True)
A_l2 = torch.mul(A, A).sum(axis=dim, keepdims=True)
B_l2 = torch.mul(B, B).sum(axis=dim, keepdims=True)
denominator = torch.max(torc... | https://stackoverflow.com/questions/67199317/ |
CUDA driver version is higher than the CUDA runtime version? | The terminal shows the error:
RuntimeError: cuda runtime error (35) : CUDA driver version is insufficient for CUDA runtime version at torch/csrc/cuda/Module.cpp:51
But my driver version (440.118.02) is sufficient for cuda9.0
Some info about my machine: cat /proc/driver/nvidia/version NVRM version: NVIDIA UNIX x86_64 K... | You can upgrade the CUDA version to 9.2 or higher. After getting the new CUDA just check driver version 440 is still compatible or not. If not upgrade that too.
Do these and then run your code and check.
NOTE: If you have installed or upgraded the Nvidia driver or CUDA recently then reboot the system once and then try.... | https://stackoverflow.com/questions/67206495/ |
pytorch Dataloader - if input data returns multiple training instances | Problem
I have the following problem:
I want to use pytorchs DataLoader (in a similar way like here) but my setup varies a bit:
In my datafolder I have images (lets call them image_total of different street situations and I want to use cropped images (called image_crop_[idx] around persons that are close enough to the ... |
the fallback would be to pre process the data, but this would not be the most efficient solution
Indeed, this could be the most simple and efficient solution. Your dataset currently has a dynamic size, which is incompatible with DataLoader which should output something of fixed size for training.
An alternative solut... | https://stackoverflow.com/questions/67209968/ |
Import TextLMDataBunch from Fastai | I am following this tutorial to build a NLP sentiment analysis model.
from fastai.text import *
This is the only import specified that includes fastai.
Unfortunately the TextLMDataBunch is undefined.
What import should I used to have this class avaialable?
I have already tried:
from fastai.text.data import TextLMDataB... | I think you are using a tutorial of fast.ai v1 with the version 2 of the fastai library so it won't work. The link you've included in your question has the documentation for the class TextMLDataBunch but if you look at the url you will see that it is for fastai1.
https://fastai1.fast.ai/text.data.html
So you have two o... | https://stackoverflow.com/questions/67211962/ |
TypeError: string indices must be integers - PyTorch | I'm trying to loop through my pre-trained CNN using the following code, it's slightly modified from PyTorch's example:
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_ep... | There is a missing enumerate:
for i, batch in enumerate(loaders[phase]): # <--- here
inputs = batch["image"].float().to(device)
labels = batch["label"].float().to(device)
| https://stackoverflow.com/questions/67220647/ |
Mismatched tensor size error when generating text with beam_search (huggingface library) | I'm using the huggingface library to generate text using the pre-trained distilgpt2 model. In particular, I am making use of the beam_search function, as I would like to include a LogitsProcessorList (which you can't use with the generate function).
The relevant portion of my code looks like this:
beam_scorer = BeamSea... | This is a known issue in the hugging face library:
https://github.com/huggingface/transformers/issues/11040
Basically, the beam scorer isn't using the max_length passed to it, but the max_length of the model.
For now, the fix is to set model.config.max_length to the desired max length.
| https://stackoverflow.com/questions/67221901/ |
Interleaving a set of channels during concatenation? | I am trying to perform a quaternion space concatenation which requires the four dimensions r,i,j,k to be concatenated. According to quaternion theory, we cannot apply the torch.cat function directly as they would mess up the components as r channels have to be concatenated with r channels and so on. I managed to perfor... | Based on the previous answer, I came up with a solution that utilizes class to compute the indices and use index_select to rearrange the concatenation. The only drawback is that the number of inputs and channels are required before execution.
import torch
from time import time
def quarternion_concat(x, dim=2):
ou... | https://stackoverflow.com/questions/67221988/ |
RuntimeError: Input type (torch.cuda.LongTensor) and weight type (torch.cuda.FloatTensor) should be the same | I'm trying to train a CNN using PyTorch's example with my own data. I have the following training loop which is identical to PyTorch:
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 ... | By default the parameters of the model are in FloatTensor datatype.
inputs = batch["image"].type(torch.cuda.FloatTensor).to(device)
labels = batch["label"].type(torch.cuda.FloatTensor).to(device)
should rectify this error or you can modify your dataloader class itself.
| https://stackoverflow.com/questions/67240639/ |
ImportError: cannot import name 'PY3' from 'torch._six' | I am testing ZED Camera with the code on https://github.com/stereolabs/zed-pytorch. While running the final command: python zed_object_detection.py --config-file configs/caffe2/e2e_mask_rcnn_R_50_C4_1x_caffe2.yaml --min-image-size 256
I get the following error:
Traceback (most recent call last):
File "zed_object_d... | For this question, the reason is that your 'torchvision' and 'pytorch' version, they didn't match. So, you need to upgrade your 'torchvision' and 'pytorch' version to the new version
pip install --upgrade torch torchvision
| https://stackoverflow.com/questions/67241289/ |
PyTorch - Efficient way to apply different functions to different 'row/column' of a tensor | Let's say I have a 2-d tensor:
x = torch.Tensor([[1, 2], [3, 4]])
Is there an efficient way to apply one function to the first 'row' [1, 2] and apply a second different function to the second row [3, 4]? (Doesn't have to be a row, could be across any dimension)
At the moment, I use the following code: Say I have my tw... | A handy tip is to slice instead of selecting to avoid the unsqueeze step. Indeed, notice how x[:1] keeps the indexed dimension compared to x[0].
This way you can perform the desired operation in a slightly shorter form:
>>> torch.vstack((f(x[:1]), g(x[1:])))
Optionally you can use vstack to not have to provid... | https://stackoverflow.com/questions/67244919/ |
How to display a video in colab, using a PyTorch tensor of RGB image arrays? | I have a tensor of shape (125, 3, 128, 128):
125 frames
3 channels (RGB)
each frame 128 x 128 size.
values in the tensor are in the range [0,1].
I want to display the video of these 125 frames, using Pytorch in Google Colab. How can I do that?
| One way to enable inline animations in Colab is using jshtml:
from matplotlib import rc
rc('animation', html='jshtml')
With this enabled, you can then plot your animation like so (note you will need to permute your image tensors to get them in PIL/matplotlib format):
import matplotlib.pyplot as plt
import matplotlib.a... | https://stackoverflow.com/questions/67261108/ |
AutoModelForSequenceClassification requires the PyTorch library but it was not found in your environment | I am trying to use the roberta transformer and a pre-trained model but I keep getting this error:
ImportError:
AutoModelForSequenceClassification requires the PyTorch library but it was not found in your environment. Checkout the instructions on the
installation page: https://pytorch.org/get-started/locally/ and f... | I was having the same issue. It was solved for me by restarting the kernel.
| https://stackoverflow.com/questions/67263288/ |
AttributeError: module 'torch.utils' has no attribute 'data' | I am trying to run my PyTorch code on a Ubuntu server, it works well on my own computer, but it failed to run on the server.
Is this because of something related to PyTorch version?
This problem seems typical but yet no solutions work.
Traceback (most recent call last):
File "train.py", line 12, in <modu... |
it worked for me...please make sure that you are using 1.7 + pytorch version
| https://stackoverflow.com/questions/67266152/ |
How to set and get confidence threshold from custom YOLOv5 model? | I am trying to perform inference on my custom YOLOv5 model. The official documentation uses the default detect.py script for inference.
Example: python detect.py --source data/images --weights yolov5s.pt --conf 0.25
I have written my own python script but I can neither set the confidence threshold during initialisation... | It works for me:
model.conf = 0.25 # confidence threshold (0-1)
model.iou = 0.45 # NMS IoU threshold (0-1)
More information:
https://github.com/ultralytics/yolov5/issues/36
| https://stackoverflow.com/questions/67280248/ |
Pytorch Tensor storages have the same id when calling the storage() method | I'm learning about tensor storage through a blog (in my native language - Viet), and after experimenting with the examples, I found something that was difficult to understand. Given 3 tensors x, zzz, and x_t as below:
import torch
x = torch.tensor([[3, 1, 2],
[4, 1, 7]])
zzz = torch.tensor([1,2,3])
#... | After searching on the Pytorch discuss forum and Stack Overflow, I see that the method data_ptr() should be used in the comparison of locations of tensors (according to the Python discuss in the question and this link) (although it is not totally correct, check the first Python discuss for a better comparison method)
A... | https://stackoverflow.com/questions/67289617/ |
Word-embedding does not provide expected relations between words | I am trying to train a word embedding to a list of repeated sentences where only the subject changes. I expected that the generated vectors corresponding the subjects provide a strong correlation after training as it is expected from a word embedding. However, the angle between the vectors of subjects is not always lar... | It's most probably the training size. Training a 128d embedding is definitely overkill. Rule of thumb from the the google developers blog:
Why is the embedding vector size 3 in our example? Well, the following "formula" provides a general rule of thumb about the number of embedding dimensions:
embedding_dim... | https://stackoverflow.com/questions/67291644/ |
Correct Validation Loss in Pytorch? | I am a bit confused as to how to calculate Validation loss? Are validation loss to be computed at the end of an epoch OR should the loss be also monitored during iteration through the batches ?
Below I have computed using running_loss which is getting accumulated over batches - but I want to see if its the correct appr... | You can evaluate your network on the validation when you want. It can be every epoch or if this is too costly because the dataset is huge it can be each N epoch.
What you did seems correct, you compute the loss of the whole validation set. You can optionally divide by its length in order to normalize the loss, so the s... | https://stackoverflow.com/questions/67295494/ |
Convert pytorch geometric data sample to its corresponding line graph | I'm trying to convert a dataset of torch geometric so that its content is represented as line graphs of the original samples. My code looks likes the following:
G = to_networkx(data,
node_attrs=['x'],
edge_attrs=['edge_attr'],
to_undirected=not directed)
line_graph = nx.l... | As noted in the previous answer, the attributes are not propagated by line_graph. Since I'm interested in preserving only the edge attributes, i.e. converting edges to nodes, my solution looks like this:
original_edge_attrs = data.edge_attr
original_edge_names = [(from_.item(), to_.item()) for from_, to_ in zip(data.ed... | https://stackoverflow.com/questions/67296269/ |
How to continue training serialized AllenNLP model using `allennlp train`? | Currently training models using AllenNLP 1.2:
allennlp train -f --include-package custom-exp /usr/training_config/mock_model_config.jsonnet -s test-mock-out
The config is very standard:
"dataset_reader" : {
"reader": "params"
},
"data_loader": {
"b... | OK, so to continue the training, one solution is to load the model from_archive. Assuming you have the serialization directory, make a model.tar.gz archive of the folder. Then, you can make a new config that is identical, except for the model key which uses from_archive:
retrain_config.json:
{
### Existing params ###... | https://stackoverflow.com/questions/67306126/ |
How to set GPU count to 0 using os.environ['CUDA_VISIBLE_DEVICES'] =""? | So I have the following GPU configured in my system:
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 461.33 Driver Version: 461.33 CUDA Version: 11.2 |
|-------------------------------+----------------------+----------------------+
| GPU Name TCC/... | To prevent your GPU from being used, set os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
| https://stackoverflow.com/questions/67311527/ |
How to use PyTorch's autograd efficiently with tensors? | In my previous question I found how to use PyTorch's autograd to differentiate. And it worked:
#autograd
import torch
from torch.autograd import grad
import torch.nn as nn
import torch.optim as optim
class net_x(nn.Module):
def __init__(self):
super(net_x, self).__init__()
self.fc1=nn.... | I believe I solved it using @ jodag advice -- to simply calculate the Jacobian and take the diagonal.
Consider the following network:
import torch
from torch.autograd import grad
import torch.nn as nn
import torch.optim as optim
class net_x(nn.Module):
def __init__(self):
super(net_x, self).__init... | https://stackoverflow.com/questions/67320792/ |
UNET with CrossEntropy Loss Function | I was trying to train UNET with input size as [3,128,128] and the corresponding mask is [1,128,128] which contains classes directly(instead of pixels it will contain class numbers - 1,2). I am trying for a two-class problem hence my mask contains 1,2 as labels. Now I send my images to the model and the dimension of the... | The documentation specifies that if the input is shape (N, C, d1, d2) then the target must be shape (N, d1, d2). Instead, your targets are shape (N, 1, d1, d2) so you need to remove the unnecessary unitary dimension.
loss = criterion(output, labels.squeeze(1))
If you're getting another error from this change then ther... | https://stackoverflow.com/questions/67322848/ |
AttributeError: 'collections.OrderedDict' object has no attribute 'predict' | Being a new guy and a beginner to deep learning and pytorch I am not sure what all inputs should I give you guys to answer my question. But I will try my best to make you guys understand my problem. I have loaded a model in pytorch using 'model= torch.load('model/resnet18-5c106cde.pth')'. But it is showing an Attribute... | I'd guess that the checkpoint you are loading stores a model state dict (the model's parameters) rather than a model (the structure of the model plus its parameters). Try:
model = resnet18(*args, **kwargs)
model.load_state_dict(torch.load(PATH))
model.eval()
where PATH is the path to the model checkpoint. You need t... | https://stackoverflow.com/questions/67337357/ |
how to convert the output of a nural network to long type while maintaining the trainability | The output of my pytorch neural network is a float64 type of data. This variable has to be used as a pixel offset and as such I need to convert it to long type.
However I have just discovered that a conversion out=out.long() switches the variable attribute ".requires_grad" to False.
How can I convert it to lo... | In general, you cannot convert a tensor to an integer-based type while maintaining it's gradient properties since converting to an integer is a non-differentiable operation. Thus, you essentially have two options:
If the data is only required as type long for inference operations that need not maintain their gradient,... | https://stackoverflow.com/questions/67338689/ |
Why is my loss not decreasing over training 10 epochs? | My hardware is a Ryzen 5000 series cpu with an nvidia rtx 3060 gpu. I'm currently working on a school assignment involving using a deep learning model (implemented in PyTorch) to predict COVID diagnosis from CT slice images. The dataset can be found at this url on GitHub: https://github.com/UCSD-AI4H/COVID-CT
I've writ... | So the issue is you're only training the first part of the classifier and not the second
# this
optimizer = torch.optim.Adam(RONANetv1.parameters(), lr=0.1)
# needs to become this
from itertools import chain
optimizer = torch.optim.Adam(chain(RONANetv1.parameters(), RONANetv2.parameters()))
and you need to incorportat... | https://stackoverflow.com/questions/67340129/ |
How to add training end callback to AllenNLP config file? | Currently training models using AllenNLP 1.2 and the commands api:
allennlp train -f --include-package custom-exp /usr/training_config/mock_model_config.jsonnet -s test-mock-out
I'm trying to execute a forward pass on a test dataset after training is completed. I know how to add an epoch_callback, but am not sure about... | I think you can create a new callback function/object that inherits from TrainerCallback and override the on_end method, and then it should work as expected if you register it the same way as you did log_metrics_to_wandb above.
| https://stackoverflow.com/questions/67342447/ |
PyTorch can't use a float type but only long | I am trying to run this very basic neural network:
import os; os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
import time
#####################################################
# ... | The negative log likelihood loss (NLLLoss) is suitable for classification problems, where the output is one out of C classes. Since the classes are discrete, your labels need to be of the long type.
In your case, in a comment, you say:
I want to create a network that simulates a quadratic function with x as input and ... | https://stackoverflow.com/questions/67345554/ |
Tensorflow and Torch on the same environment | I am working on a goat detection problem. The main model identifies "goat" (single class) on an image and each goat then cropped from the original image. The cropped image then passes through a tensorflow model (trained tensorflow.keras.applications.InceptionV3) to find the current posture of the goat (sittin... | Install tensorflow-gpu=2.6.0 and PyTorch with cudatoolkit=11.3 and its working fine with anaconda.
conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch
conda install tensorflow-gpu
| https://stackoverflow.com/questions/67353874/ |
Do we have lower performance and accuracy than when not using `pytorch.nn.Sequnetial` and if yes, why? | I was checking out this video where Phil points out to this fact that using torch.nn.Sequential is faster than not using it. I did quick google and came across this post which is not answered satisfactorily, so I am replicating it here.
Here is the code from the post with Sequential:
class net2(nn.Module):
def __in... | I'm not familiar with what kind of optimizations the python interpreter does, but I'd guess it is very limited.
But the claim that one method is more accurate than another is completely nonsense. If you look at the implementation of nn.Sequential you'll see that it does exactly the same thing you'd do anyway, you just ... | https://stackoverflow.com/questions/67357795/ |
only first gpu is allocated (eventhough I make other gpus visible, in pytorch cuda framework) | I am using cuda in pytorch framwework in linux server with multiple cuda devices.
The problem is that
eventhough I specified certain gpus that can be shown,
the program keeps using only first gpu.
(But other program works fine and other specified gpus are allocated well.
because of that, I think it is not nvidia or sys... | Have you tried something like this?
device = torch.device("cuda:0,1" if torch.cuda.is_available() else "cpu") ## specify the GPU id's, GPU id's start from 0.
model = CreateModel()
model= nn.DataParallel(model,device_ids = [0, 1])
model.to(device)
let me know about this
| https://stackoverflow.com/questions/67364827/ |
CUDA version of package not importing? | Firstly, I installed torch 1.1.0, and then I installed its' dependencies. So, I can import torch_scatter 1.2.0 however I get this error when importing torch_scatter.scatter_cuda:
import torch_scatter.scatter_cuda
ModuleNotFoundError: No module named 'torch_scatter.scatter_cuda'
I have Cuda v10 installed and I have a... | As pointed out by phd - it looks like the setup.py file of pytorch_scatter checks for and uses an available cuda installation automatically.
Also in the version you are using as seen here:
...
if CUDA_HOME is not None:
ext_modules += [
CUDAExtension('torch_scatter.scatter_cuda',
... | https://stackoverflow.com/questions/67365218/ |
ImageNet pretrained ResNet50 backbones are different between Pytorch and TensorFlow | "Obviously!", you might say... But there's one significant difference that I have trouble explaining by the difference in random initialization.
Take the two pre-trained basenets (before the average pooling layer) and feed them with the same image, you will notice that the output features don't follow the sam... | There are 2 things that differ in the implementations of ResNet50 in TensorFlow and PyTorch that I could notice and might explain your observation.
The batch normalization does not have the same momentum in both. It's 0.1 in PyTorch and 0.01 in TensorFlow (although it is reported as 0.99 I am writing it down in PyTorc... | https://stackoverflow.com/questions/67365237/ |
Why some weights of GPT2Model are not initialized? | I am using the GPT2 pre-trained model for a research project and when I load the pre-trained model with the following code,
from transformers.models.gpt2.modeling_gpt2 import GPT2Model
gpt2 = GPT2Model.from_pretrained('gpt2')
I get the following warning message:
Some weights of GPT2Model were not initialized from the... | The masked_bias was added but the huggingface community as a speed improvement compared to the original implementation. It should not negatively impact the performance as the original weights are loaded properly. Check this PR for further information.
| https://stackoverflow.com/questions/67379533/ |
What is the TensorFlow/Keras equivalent of PyTorch's `no_grad` function? | When writing machine learning models, I find myself needing to compute metrics, or run additional forward-passes in callbacks for visualization purposes. In PyTorch, I do this with torch.no_grad(), and this prevents gradients from being computed and these operations, therefore, do not influence the optimization.
How d... | The tensorflow equivalent would be tf.stop_gradient
Also don't forget, that Keras does not compute gradients when using predict (or just calling the model via __call__).
| https://stackoverflow.com/questions/67385963/ |
How to merge sequential integer values into intervals in PyTorch? | I have a 1D array:
[3, 4, 5, 6, 7, 20, 31, 32, 33, 34]
which I want to turn into a 2D interval array by merging every consecutive values into intervals:
[
[ 3, 7],
[20, 20],
[32, 34]
]
What would be a decent, possibly GPU-friendly, way to do it?
| Not sure if this is ideal, but you can try cumsum() on the differences compared to 1. Then use that to slice the original data:
# mark the consecutive blocks
blocks = torch.cat([torch.tensor([0]),(t[1:] - t[:-1]) != 1]).cumsum(dim=0)
# where the blocks shift
mask = blocks[1:] != blocks[:-1]
out = torch.cat([t[:1], t... | https://stackoverflow.com/questions/67389915/ |
Preprocessing a video in android for pytorch | What is the best way to preprocess video data in Android Kotlin, in preparation to feed into a PyTorch Android model? Specifically, I have a ready-made model in PyTorch, and I've converted it to be ready for PyTorch Mobile.
During training, the model takes in raw footage from phones and is preprocessed to (1) be greysc... | You said that your model was converted to be ready for PyTorch Mobile so I will assume that you scripted your model with TorchScript.
With TorchScript, you can write preprocessing logic using Torch operation and keep it inside the scripted model like this:
import torch
import torch.nn.functional as F
@torch.jit.script... | https://stackoverflow.com/questions/67392409/ |
Use Adam optimizer for LSTM network vs LBGFS | I have modified pytorch tutorial on LSTM (sine-wave prediction: given [0:N] sine-values -> [N:2N] values) to use Adam optimizer instead of LBFGS optimizer. However, the model does not train well and cannot predict sine-wave correctly. Since in most cases we use Adam optimizer for RNN training, I wonder how this issu... | I've just executed your code and the original code. I think the problem is you didn't train your code with ADAM long enough. You can see your training loss is still getting smaller at step 15. So I changed the number of steps from 15 to 45 and this is the figure generated after step 40:
The original code reached 4e-05... | https://stackoverflow.com/questions/67409042/ |
Does pytorch Dataset.__getitem__ have to return a dict? | EDIT: This is not about the general __getitem__ method but the usage of __getitem__ in the Pytorch Dataset-subclass, as @dataista correctly states.
I'm trying to implement the usage of Pytorchs Dataset-class.
The guide e.g here is really good, but I struggle to figure out Pytorch requirements for the return value of _... | PyTorch has no requirements on the return value of a DataSet's __getitem__ method. It can be anything, but you will commonly encounter a tensor, a tuple of tensors, a dictionary (e.g. {'features':..., 'label':...}) etc.
It is usual in 2d data to return a single tensor whose final column are the target values, but equal... | https://stackoverflow.com/questions/67416496/ |
"Numpy not Available" After installing Pytorch XLA | I am just getting started with using TPUs on kaggle with Pytorch and install it as follows -
!pip3 install mkl
!curl https://raw.githubusercontent.com/pytorch/xla/master/contrib/scripts/env-setup.py -o pytorch-xla-env-setup.py
!python3 pytorch-xla-env-setup.py --version nightly --apt-packages libomp5 libopenblas-dev
... | At least in Google Colab I was able to solve this issue by running (after installing xla):
!pip install -U numpy
Not completely sure it will help in any context
| https://stackoverflow.com/questions/67417532/ |
Use PyTorch to speed up linear least squares optimization with bounds? | I'm using scipy.optimize.lsq_linear to run some linear least squares optimizations and all is well, but a little slow. My A matrix is typically about 100 x 10,000 in size and sparse (sparsity usually ~50%). The bounds on the solution are critical. Given my tolerance lsq_linear typically solves the problems in about ... | Not easily, no.
I'd try to profile lsq_linear on your problem to see if it's pure python overhead (which can probably be trimmed some) or linear algebra. In the latter case, I'd start with vendoring the lsq_linear code and swapping relevant linear algebra routines. YMMV though.
| https://stackoverflow.com/questions/67421904/ |
How do I proceed to load a ga_instance as ".pkl" format in PyGad? | I have been trying to load the PyGad trained instance in another file, in order to make some prediction. But I have been having some problems in the loading process.
After the training phase, I saved the instance like this:
The saving function:
filename = 'GNN_CPTNet' #GNN_CPTNet.pkl
ga_instance.save(filename=filename)... | In the new script, you should define the the fitness function and all the callback functions you used in the original script.
For example, if you used only the on_generation (callback_generation) parameter, then the following functions should be defined:
def fitness_func(solution, solution_idx):
...
def callback_... | https://stackoverflow.com/questions/67424181/ |
Is it advisable to use the same torch Dataset class for training and predicting? | I have recently started using PyTorch and I liked it for its object-oriented style. However, I wonder what’s the best and advised workflow when predicting the model. I wanted to use a custom Dataset class I wrote and which I use for training and validating my model. This class is a map-style dataset, therefore I implem... | PyTorch's DataSet class is really simple. So, do not overthink it. It's not much more than a wrapper for accessing your data.
You don't have to return a tuple, not even Tensors. You can return whatever data you want. Commonly, it will be in one of those styles:
For unsupervised data: Sample or (Sample, None)
For super... | https://stackoverflow.com/questions/67445508/ |
TypeError when using torch.autograd.profiler.profile | I am trying to analyze memory consumption for my model as described here:
https://pytorch.org/tutorials/recipes/recipes/profiler_recipe.html
using these lines:
with profiler.profile(profile_memory=True, record_shapes=True) as prof:
tubes, _, _ = zip(*model(imgs, img_metas, return_loss=False))
print(prof.key_average... | You need to upgrade your version of PyTorch. Looking at the code, one can see that the profile_memory argument was added to the function signature first in PyTorch v1.6.0.
You can also see this through the documentation of torch.autograd. You can see that the argument is not present in PyTorch v1.1.0.
| https://stackoverflow.com/questions/67458728/ |
what does pytorch do for creating tensor from numpy | I am interested in what torch have done when I call torch.from_numpy. As the name indicates, it seems that PyTorch creates a Tensor instance and allocates the memory for copying the content from numpy ndarray to itself. But how does PyTorch do the memcpy work and what else has PyTorch done in the background? It seems t... | The documentation explains that
The returned tensor and ndarray share the same memory. Modifications to the tensor will be reflected in the ndarray and vice versa. The returned tensor is not resizable.
These sentences implies that there is no memcopy involved (otherwise modifications would not be reflected in one aon... | https://stackoverflow.com/questions/67465094/ |
Custom Pytorch layer to apply LSTM on each group | I have a N × F tensor with features and a N × 1 tensor with group index. I want to design a custom pytorch layer which will apply LSTM on each group with sorted features. I have mentioned LSTM with sorted group features as an example, hypothetically it can be anything which supports variable length input or sequence. P... | You can certainly parallelize the LSTM application -- the problem is indexing the feature tensor efficiently.
The best thing I could come up with (I use something similar for my own stuff) would be to list comprehend over the unique group ids to make a list of variable-length tensors, then pad them over and run the LST... | https://stackoverflow.com/questions/67471635/ |
Is a .pth file a security risk, and how can we sanitise it? | It's well-established that pickled files are [unsafe][1] to simply load directly. However, the advice on that SE post concludes that basically one should not use a pickled file if they are not sure of its provenance.
What about PyTorch machine-learning models that are stored as .pth files on, say, public repos on Gith... | As pointed out by @MobeusZoom, this is answer is about Pickle and not PyTorch format. Anyway as PyTorch load mechanism relies on Pickle behind the scene observations drawn in this answer still apply.
TL;DR;
Don't try to sanitize pickle. Trust or reject.
Quoted from Marco Slaviero in his presentation Sour Pickle at th... | https://stackoverflow.com/questions/67493095/ |
from keras.preprocessing.text import one_hot equivalent in pytorch? | I just started using pytorch for NLP. I found a tutorial that uses from keras.preprocessing.text import one_hot and converts text to one_hot representation given a vocabulary size.
For example:
The input is
vocab_size = 10000
sentence = ['the glass of milk',
'the cup of tea',
'I am a good boy']
... | PyTorch fundamentally works with Tensors, and is not designed to work with strings. You can use SK Learn's LabelEncoder to encode your words however:
from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit([w for s in sentence for w in s.split()])
onehot_repr = [le.transform(s.split()) for s in sen... | https://stackoverflow.com/questions/67503960/ |
How to make VScode launch.json for a Python module | I'm reseaching self-supervised muchine learning code.
And I have wanted to debug the code with python debugger not pdb.set_trace().
This is python command for ubuntu terminal.
python -m torch.distributed.launch --nproc_per_node=1 main_swav.py \
--data_path /dataset/imagenet/train \
--epochs 400 \
--base_lr 0.6 \
--fina... | Specify the module you want to run with "module": "torch.distributed.launch"
You can ignore the -m flag. Put everything else under the args key.
Note: Make sure to include --nproc_per_node and the name of file (main_swav.py) in the list of arguments
{
"version": "0.2.0&quo... | https://stackoverflow.com/questions/67518928/ |
PyTorch DataLoader Error: object of type 'type' has no len() | I'm quite new to programming and have now clue where my error comes from.
I got the following code to set up my dataset for training my classifier:
class cows_train(Dataset):
def __init__(self, folder_path):
self.image_list = glob.glob(folder_path+'/content/cows/train')
self.data_len = len(self.ima... | You are not creating your dataset object correctly. Currently, you do:
trainset = cows_train
This only assigns the class type to trainset. To create an object of the class, you need to use:
folder_path = '/path/to/dataset/'
trainset = cows_train(folder_path)
| https://stackoverflow.com/questions/67520509/ |
How to make code run on GPU on Windows 10? | I want to run my code run on gpu in windows 10, like for google colab, we can just change the runtime option which is pretty easy to do to shift to gpu. Is there a possibility to do the same for jupyter notebook in windows.
| You will actually need to use tensorflow-gpu to run your jupyter notebook on a gpu.
The best way to achieve this would be
Install Anaconda on your system
Download cuDNN & Cuda Toolkit 11.3 .
Add cuDNN and Cuda Toolkit to your PATH.
Create an environment in Anaconda
pip install tensorflow-gpu
pip install [jupy... | https://stackoverflow.com/questions/67521143/ |
how to use collate_fn properly in the code below? | My code is:
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
dataset = PennFudanDataset('PennFudanPed', get_transform(train=True))
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=2, shuffle=True, num_workers=4,
collate_fn=utils.collate_fn)
# For Training
images,targets = next... | Ok so I read the tutorial and it seems that it wants you to use the helper files in this repository: https://github.com/pytorch/vision/tree/master/references/detection .
In there is the utils.py which contains the collate_fn function.
So it seems that you dont have downloaded/copied this repository to integrate it into... | https://stackoverflow.com/questions/67530442/ |
Python: BERT Error - Some weights of the model checkpoint at were not used when initializing BertModel | I am creating an entity extraction model in PyTorch using bert-base-uncased but when I try to run the model I get this error:
Error:
Some weights of the model checkpoint at D:\Transformers\bert-entity-extraction\input\bert-base-uncased_L-12_H-768_A-12 were not used when initializing BertModel:
['cls.predictions.tra... | As R. Marolahy suggests, if you don't want to see this every time, I know I don't, add the following:
from transformers import logging
logging.set_verbosity_error()
| https://stackoverflow.com/questions/67546911/ |
TypeError: new(): argument 'size' must be tuple of ints, but found element of type NoneType at pos 2 when using pytorch, using nn.linear | File "C:\Users\J2\Desktop\Pytorchseries\thenn.py", line 50, in
net = Net()
TypeError: new(): argument 'size' must be tuple of ints, but found element of type NoneType at pos 2
If it helps I was following the sentdex pytorch tutorial. Any help would be appreciated. I am new to machine learning, and I was hopi... | The issue is with self._to_linear. You use it in __init__ as:
self._to_linear = None
self.convs(x)
self.fc1 = nn.Linear(self._to_linear, 512) #flattening.
The call to nn.Linear has it as a parameter. This parameter should equal the number of input features in the linear layer, and cannot be None, since the value ... | https://stackoverflow.com/questions/67547859/ |
A Problem aboud using multi-gpu with a two-stage CNN model | I design a CNN model which has two stages. First stage is generating proposals like RPN in Faster RCNN and the second feeds these proposals into the following part.
It causes error in the second step.
Accroding the below error information, it seems like the second input is not correctly assigned to the multi GPU.
Howev... | I know where I am wrong. Here’s my second stage to feed input
cls, offset = self.model([proposal, fm], stage='two')
proposal is the ROI whose shape is [N, 5], the 1th dim is the batch index. e.g. The batch size is 4, the range of index is [0,1,2,3]. And fm is the feature map.
When I use the mult-gpu like 2 gpu. the pr... | https://stackoverflow.com/questions/67557828/ |
Python - How to output a numpy array of probabilities with certain precision and remain its sum | I have a numpy array of 6 probabilities which come from pytorch softmax function.
[0.055709425,0.04365404,0.008613999,0.0022386343,0.0037478858,0.88603604]
I want to convert all 6 float numbers to string to represent a score output,
and all of them need to be rounded to a certain precision, say 4.
I used the followi... | You can round off to 2 decimal places, to reduce that error:
For example:
import numpy as np
a = np.array([0.055709425,0.04365404,0.008613999,0.0022386343,0.0037478858,0.88603604])
print(sum(a))
Output:
1.0000000241
Now:
new_array = [round(x,2) for x in a]
print(sum(new_array))
Output:
1.0
| https://stackoverflow.com/questions/67564889/ |
FileNotFoundError: [Errno 2] :No such file or directory: 'C:/Users/My_computer/Desktop/Compare/MHAN-master/AID_train/AID_train_LR/x4\\9.png' | I'm very new to python environment. I have tried to compile a super-resolution code for upscaling factor 4 using my own dataset. The low resolution RGB images are kept in "C:/Users/My_computer/Desktop/Compare/MHAN-master/AID_train/AID_train_LR/x4". The code used for image load is shown in below:
def load_img(... | 'C:/Users/My_computer/Desktop/Compare/MHAN-master/AID_train/AID_train_LR/x4\\9.png'
Your string contains a double backslash at the end of the path, that's why you can't access the directory
use a raw string like
r'yourString'
or review your os.path.join
EDIT:
Try to convert every string into a raw-String, like mention... | https://stackoverflow.com/questions/67570563/ |
After installing Pytorch cuda , torch.cuda.is_available() show false. What to do? | I have installed pytorch cuda by running this command:
conda install pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c nvidia
My cuda version is 11.2 . I am using windows 10 .
Pytorch cuda 11.2 is not available right now . (pytorch.org)
So I have install 11.1 version .
(using nvidia-smi)
Cuda version
But i... | You should not install package to your base environment. Create a separate environment with necessary tools.
Example: create env called dlearn with Python v3.7 and torch packages
conda create -n dlearn python=3.7 pytorch torchvision torchaudio cudatoolkit=11.1 -c pytorch -c nvidia
Activate and use your dlearn environm... | https://stackoverflow.com/questions/67570573/ |
How to save training weight checkpoint of model and continue training from last point in PyTorch? | I'm trying to save checkpoint weights of the trained model after a certain number of epochs and continue to train from that last checkpoint to another number of epochs using PyTorch
To achieve this I've written a script like below
To train the model:
def create_model():
# load model from package
model = smp.Unet(
... | this line:
model.load_state_dict(checkpoint['model_state_dict'])
should be like this:
model.load_state_dict(checkpoint)
| https://stackoverflow.com/questions/67571329/ |
How to update tensors matching dimensionwise vectors | Let there be two 2D tensors, A (m × c) and B (n × c). Each row vector which belongs to B also belongs to A i.e. . Additionally, row vectors in A are not unique i.e. A may have duplicate rows. However, row vectors in B are unique.
There another pair of tensors P (m × f) and Q (n × f). I am trying to do the following
for... | You can use the following mask:
for i in range(B.shape[0]):
rv = B[i]
fv = Q[i]
mask = torch.where((A == rv).all(dim=1))[0]
P[mask] = fv
| https://stackoverflow.com/questions/67582406/ |
ValueError('need at least one array to stack') | When I Processed video and its audio,I encountered an error:
Original Traceback (most recent call last):
File "/home/yzx/anaconda3/envs/pytorch/lib/python3.8/site-packages/torch/utils/data/_utils/worker.py", line 202, in _worker_loop
data = fetcher.fetch(index)
File "/home/yzx/anaconda3/envs/pytorch/lib/python... | Your issue is here:
signals = np.stack([src.signal for src in pst_sources], axis=1) # signals shape: [Len, n_signals]
It looks like pst_sources is empty, and so you are trying to stack an empty list.
| https://stackoverflow.com/questions/67584404/ |
Train on top of a Torchscript model | I currently have a Torchscript model I load via torch.jit.load. I would like to take some data I have and train on top of these weights, however I cannot find out how to train a serialised torchscript model.
| Turns out that the returned ScriptModule does actually support training: https://pytorch.org/docs/stable/generated/torch.jit.ScriptModule.html#torch.jit.ScriptModule.train
| https://stackoverflow.com/questions/67584702/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.