instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
RuntimeError: expected scalar type Float but found Double | My code is as follows:
net = nn.Linear(54, 7)
optimizer = optim.SGD(net.parameters(), lr=lr, momentum=0)
logloss = torch.nn.CrossEntropyLoss()
for i in range(niter):
optimizer.zero_grad()
y_2 = torch.from_numpy(np.array(y, dtype='float64'))
X_2 = torch.from_numpy(np.array(X, dtype='float64'))
outputs = ... | You need to cast your tensors to float32, either with dtype='float32' or calling float() on your input tensors.
| https://stackoverflow.com/questions/69516366/ |
StopIteration Error occurs during training while running the train.py file | I am trying to run a code from github. The file is called train.py. It is supposed to run a Neural Network for training on a dataset. However, I get the following error
(QGN) ubuntu@ip-172-31-13-114:~/QGN$ python train.py
Input arguments:
id ade20k
arch_encoder resnet50
arch_decoder QGN_dense_resn... | TL;DR
Your args.epoch_iters is larger than the number of batches in loader_train. Python raises StopIteration error when you ask for more batches than there actually are.
When you iterate over some pythonic collection of elements (e.g., list, tuple, DataLoader...) python needs to know when it reaches the end of that co... | https://stackoverflow.com/questions/69520913/ |
When to put pytorch tensor on GPU? | I'm experimenting with running neural network on GPU using pytorch, and my data have some unusual shape so I use Dataset and DataLoader to generate data batch. My code runs fine on CPU but I'm a little confused on when is the right timing to put the data on GPU:
My data size is small enough to be put all together on G... | Let me clear up a thing. at the time of passing the data through the model, both your model and the data(that specific batch) have to be on the same device.
To automate your code to work on both GPU and non-GPU environments you might use this line.
device = torch.device('cuda') if torch.cuda.is_available() else torch.d... | https://stackoverflow.com/questions/69545355/ |
No CUDA GPUs are available | i get this error from the method during the model training process. i am using the google colab to run the code. the google colab dont have any GPU. Is their any other way i can make the code run without requiring cuda cpu.
How can i fix this error ?
def train_model(model, train_loader, val_loader, epoch, loss_function... | Just remove the line where you create your torch.device() and remove all the .to(device) functions where you use it. Then you also don't need to write .cpu().detach() also. You can simply write predict.numpy() as such. When you write device = torch.device("cuda") you are creating a GPU device and you are then... | https://stackoverflow.com/questions/69549094/ |
What does a single "||" mean in pytorch-geometric documents? | For example the "||" (\Vert) in https://pytorch-geometric.readthedocs.io/en/latest/modules/nn.html#torch_geometric.nn.conv.GATConv
| That documentation page includes a link to an arxiv paper that includes the following (bottom of page three)...
where represents transposition and || is the concatenation operation.
So yes, || is the concatenation operator.
| https://stackoverflow.com/questions/69549292/ |
Get the value at a specific index in PyTorch | I have a ground truth label array for size 5.
y=tensor([958, 85, 244, 182, 294])
I have the output for scores array of shape : [5,1000]
scores = tensor([[ 1.0406, 1.1808, 4.4227, ..., 4.6864, 8.0145, 5.2128],
[ 6.9101, 4.6083, 6.9259, ..., 9.7415, 9.6305, 9.3974],
[ 7.6097, 4.0396, ... | Yes, you can do it by using your y array as an index:
scores[torch.arange(5), y]
| https://stackoverflow.com/questions/69549324/ |
torchaudio: Error opening '_sample_data\\steam.mp3': File contains data in an unknown format | I'm new to torch audio and i'm following the this tutorial step by step. I'm having a problem loading an mp3 audio using torchaudio.info(path).
Here is my code:
metadata = torchaudio.info(SAMPLE_MP3_PATH)
print(metadata)
Here is the error that i'm getting:
..
RuntimeError: Error opening '_sample_data\\steam.mp3': Fil... | torchaudio.info will call its backend to show the information.
If you use it in windows, and the backend is Soundfile, then this problem will occur. Because Soundfile does not support mp3 format.
You can use the below code to see the available formats.
import soundfile as sf
sf.available_formats()
| https://stackoverflow.com/questions/69553112/ |
Distributing CUDA runtime to customers but it's too big | At my company, we are building software that we need to push to customers when we update software (It's being pushed to custom hardware).
We have a GPU on that custom hardware that is fixed, but sometimes, we might need to upgrade the CUDA and CUDNN runtime if we upgrade things in our software (such as libtorch).
The p... | https://pytorch.org doesn't advertize it, but there is a static version of libtorch available (replace 'shared' with 'static' in the URL).
Link against those libraries instead. Your binary will be a bit bigger (depending on how much of the library your code is using), but on the plus side you'll be saving 1.2GB there, ... | https://stackoverflow.com/questions/69560957/ |
What is the difference edge_weight and edge_attr in Pytorch Geometric | I want to handle weighted undirected graphs in Pytorch Geometric.
The node features are 50 dimensional. I found that this can be handled by the x attribute of the torch_geometric.data.data class.
The weights of the edges are scalar values.
We found out that edge_attr and edge_weight are the attributes to handle edges.
... | The difference between edge_weight and edge_attr is that edge_weight is always one-dimensional (one value per edge) and that edge_attribute can be multi-dimensional. You can check the cheatsheet for the support of the models.
| https://stackoverflow.com/questions/69565890/ |
Number of neuron in CNN architecture | I am using a certain CNN architecture, however, I am not sure how to calculate the exact number of neuron I have in it.
self.conv1 = nn.Conv2d(in_channels=1, out_channels=16,
kernel_size=(7, 7), padding=(1, 1),
stride=(2, 2))
self.conv2 = nn... | One quick way to get the total count is to
Fetch all parameters with nn.Module.parameters;
Convert the generator to a flattened tensor with torch.nn.utils.parameters_to_vector;
Find the total number of elements with torch.Tensor.numel.
Which corresponds to:
>>> p2v(model.parameters()).numel()
44936
Having i... | https://stackoverflow.com/questions/69572575/ |
How to Convert a Linear Model to Conv1 in Pytorch? | I am new to Pytroch and I cannot transform Keras models that I have in my mind in to it.
I have a really simple linear model in Pytorch as follows:
class linear_model(nn.Module):
def __init__(self, output, activation=nn.ReLU):
super(linear_model, self).__init__()
self.net = nn.Sequential(
... | The data you are passing is that of single-point data. The difference between data of shape [B,N,L] for 1D tensors and [B,N] for single-point tensors is critical for the application of N-D convolutions (in this case B is batch size, L is sequence length, and N is feature depth).
To solve this for your case, just add a ... | https://stackoverflow.com/questions/69589971/ |
(with cpu)Pytorch: IndexError: index out of range in self. (with cuda)Assertion `srcIndex < srcSelectDimSize` failed. How to solve? | Today I get the following error when I use BERT with Pytorch and cuda: /pytorch/aten/src/ATen/native/cuda/Indexing.cu:702: indexSelectLargeIndex: block: [234,0,0], thread: [0,0,0] Assertion srcIndex < srcSelectDimSize failed.
Epoch [1/100]
Iter: 0, Train Loss: 1.1, Train Acc: 39.06%, Val Loss: 1.0, Val ... | I have resolved it!!!
By printing out the maximum input_ids each batch
for i, (trains, labels) in enumerate(train_iter):
print("train max input:", torch.max(trains[0]))
print("train min input:", torch.min(trains[0]))
print("train max label:", torch.max(... | https://stackoverflow.com/questions/69596496/ |
Pytorch required_grad=False does not freeze network parameters when running on GPU | I'm trying to freeze a layer of a toy model when training using Pytorch. In the following code, when I run the code on CPU, the layer isn't updated. (Please see the code line print("%.8f" % np.max(np.abs(before -after)))). However, when I run the code on GPU, the layer is updated. What is wrong with my implem... | It seems it's not CPU / GPU acting differently, but it is about .to('cpu') function in your toNP function.
If given tensor is on GPU, it returns copied tensor on cpu, while it returns given original object when the given tensor is already on CPU.
Please refer more on this site.
To clarify, I've added print function to ... | https://stackoverflow.com/questions/69624788/ |
Exporting PyTorch Lightning model to ONNX format not working | am using Jupyter Lab to run. It has pre-installed tf2.3_py3.6 kernel installed in it. It has 2 GPUS in it.
PyTorch Lightning Version (e.g., 1.3.0): '1.4.6'
PyTorch Version (e.g., 1.8): '1.6.0+cu101'
Python version: 3.6
OS (e.g., Linux): system='Linux'
CUDA/cuDNN version: 11.2
How you installed PyTorch (conda, pip, sour... | Cuz at onnx conversion, the model output must be tensor, not list, tuple, or dict. You can check your forward of model.
| https://stackoverflow.com/questions/69648338/ |
Challenge in replacing SelfAttention with ImageLinearAttention in Vision Transformer | When I am replacing ImageLinearAttention with SelfAttention in Vision Transformer, with the code as follows, I get a RuntimeError. The code for ImageLinearAttention is from https://github.com/lucidrains/linear-attention-transformer/blob/master/linear_attention_transformer/images.py except I removed number of channels a... | Looks like image self attention works on 4 dimensional inputs of shape (batch, dim, height, width) suited for images and self attention works on 3 dimensional inputs of shape (batch, sequence length, dim) suited for NLP tasks. Maybe the input has to be reshaped before feeding to self attention.
| https://stackoverflow.com/questions/69653756/ |
Batching irregularities with data loader | I have some data in .txt files and an instance formed by two lines which both have 100 elements in them. First line defines the problem and the second line defines the solution. Even though it is not a great idea I tried to use a supervised setting among the data. However, I am facing problems with batching. I have add... | You haven't shown how you defined your dataloader, but assuming you are wrapping load_dataset with a torch.utils.data.DataLoader and setting batch_size=5.
If you set your batch size to 5, then you will have 5 "problems" and the corresponding 5 "solutions" in a single batch. Each having 100 component... | https://stackoverflow.com/questions/69665818/ |
clang: error: unsupported option '-fopenmp' (SparseConvNe build error) | Thank you first for your help and time. I am trying to run and build SparseConvNet (https://github.com/facebookresearch/SparseConvNet)on my Mac, however, I get the following error after running bash develop.sh on my terminal:
running develop
running egg_info
creating sparseconvnet.egg-info
writing sparseconvnet.egg-inf... | I'm unsure about the error you received after adjusting the setub.py file (may be due to changing the compiler version being called), but your original error seems to relate to the MacOS version of clang not natively supporting fopenmp. A solution for this was posted here:
Enable OpenMP support in clang in Mac OS X (si... | https://stackoverflow.com/questions/69689502/ |
Input to nn.Linear(in_features=16*4*4, out_features=100) | I am performing a CNN on the MNIST dataset with the following model:
class ConvNet(nn.Module):
def __init__(self, mode):
super(ConvNet, self).__init__()
# Define various layers here, such as in the tutorial example
# self.conv1 = nn.Conv2D(...)
#First Convolution Kayer
#input size (28,28), ou... | Your classifier's input is shaped (10, 16, 4, 4), discarding the first dimension which corresponds to the batch size, you end up with 16*4*4 elements. So this is correct, but the shape isn't: you need to flatten the spatial dimension before feeding the tensor to fc1. You can do using nn.Flatten:
class ConvNet(nn.Module... | https://stackoverflow.com/questions/69692406/ |
Error: Some NCCL operations have failed or timed out | While running a distributed training on 4 A6000 GPUs, I get the following error:
[E ProcessGroupNCCL.cpp:630] [Rank 3] Watchdog caught collective operation timeout: WorkNCCL(OpType=BROADCAST, Timeout(ms)=1800000) ran for 1803710 milliseconds before timing out.
... | Following two have solved the issue:
Increase default SHM (shared memory) for CUDA to 10g (I think 1g would have worked as well). You can do this in docker run command by passing --shm-size=10g. I also pass --ulimit memlock=-1.
export NCCL_P2P_LEVEL=NVL.
Debugging Tips
To check current SHM,
df -h
# see the row for sh... | https://stackoverflow.com/questions/69693950/ |
GPU is not available for Pytorch | I installed Anaconda, CUDA, and PyTorch today, and I can't access my GPU (RTX 2070) in torch. I followed all of installation steps and PyTorch works fine otherwise, but when I try to access the GPU either in shell or in script I get
>>> import torch
>>> torch.cuda.is_available()
False
>>> tor... | If you use conda, try to update conda. It works for me to install PyTorch 1.10 with CUDA 10.2.
| https://stackoverflow.com/questions/69694093/ |
How to split folder with images into train, val and test? | I am using colab and I have a folder with images. How to split them into three folders with images with random splitting? I want there to be 0.8 in train, 0.1 in val and 0.1 in test. I tried splitfolders library:
splitfolders.ratio("content/data", output="output", seed=1337, ratio=(.8, .1, .1), grou... | Try this in your computer.
I'm using this code in my project
import splitfolders
#### input dataset that want to split
input_folder = 'D:/Raw_DS'
output_folder= 'D:/Splitted_DS'
splitfolders.ratio(input_folder, output= output_folder, seed=1337, ratio = (0.8, 0.1, 0.1))
| https://stackoverflow.com/questions/69701114/ |
test_train_split ValueError: Found input variables with inconsistent numbers of samples: [200000, 6] | I've looked at a couple of other posts with this issue, and I cannot figure out what I'm getting wrong here.
I have X_data, and Y_data, and they both have the shape (200000,6). Sample data output from them looks like this:
X_data:
(200000, 6)
[[ 0.00237987 0.00237987 -0.00075756 -0.00221595 -0.00368199 0.00019625]
[... | It seems like the first column of your Y_data matrix is the label for your x data, (I'm not sure what the other 5 columns in your Y_train represent). You are currently getting the first row, which isn't correct (note the size is 6 but you would like one y-value for each x input). So the code I think you want is
X_train... | https://stackoverflow.com/questions/69702046/ |
Torch not compiled with CUDA enabled - reinstalling pytorch is not working | My code which I'm trying to run gives me an error: AssertionError: Torch not compiled with CUDA enabled.
I was trying to search for an solution to this problem and I found a lot of solutions saying the same. Just use code:
conda install pytorch torchvision cudatoolkit=10.2 -c pytorch
And then it should work, since prev... | Seems you have the wrong combination of PyTorch, CUDA, and Python version, you have installed PyTorch py3.9_cpu_0 which indicates that it is CPU version, not GPU. What I see is that you ask or have installed for PyTorch 1.10.0 which so far I know the Py3.9 built with CUDA 11 support only. See list of available (compile... | https://stackoverflow.com/questions/69735619/ |
DCGAN understanding generator update step | Here is some DCGAN example in Pytorch:
https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html#training
I wonder why we don't zero discriminator gradients before we update generator? (I added line in original code # netD.zero_grad() # Q: why we don't do this?)
Is it because gradients accumulate in some separat... |
.. gradients accumulate in some separate variable ..
Yes. That is correct. They are two storages (read "variables") - one for parameters and another for its gradients.
.. don't affect gradients calculation in generator ..
Also correct. Let's look at the computation graph for the relevant part
(x) ----->... | https://stackoverflow.com/questions/69739482/ |
Issue plotting a simple tensor with Torch | Just beginning to use Pyorch, and I am trying to plot a very simple, 1-D array Tensor onto a histogram with Matplotlib.
torch.manual_seed(8436)
a = torch.Tensor(1000)
a.normal_(0, 2.) #This will fill our array with a normal distribution
plt.hist(a);
However, the result is strange..., and just consists of a bunc... | ok, it seems to me that here is the reason:
cbook._reshape_2D is used to preprocess the data coming into plt.hist . in 3.4.3 it returns a list of arrays with only one element each, which obviously produces the wrong image above.
in 3.2.2 , however, it returns a list with one 1D array, basically a NumPy version of the ... | https://stackoverflow.com/questions/69741863/ |
RuntimeError: "nll_loss_forward_reduce_cuda_kernel_2d_index" not implemented for 'Int': Pytorch | So, I was trying to code a chatbot using Pytorch following this tutorial.
Code: (Minimal, Reproducible one)
tags = []
for intent in intents['intents']:
tag = intent['tag']
tags.append(tag)
tags = sorted(set(tags))
X_train = []
X_train = np.array(X_train)
class ChatDataset(Dataset):
def __init__(self):
... | In my case, I solved this problem by converting the type of targets to torch.LongTensor before storing the data into the GPU as follows:
for inputs, targets in data_loader:
targets = targets.type(torch.LongTensor) # casting to long
inputs, targets = inputs.to(device), targets.to(device)
...
...
... | https://stackoverflow.com/questions/69742930/ |
How to apply torchvision transformations to zip file | I was trying to download CelebA data set and apply transformation to it via code:
from torchvision import transforms
from torchvision.datasets import CelebA
celeba_transforms = transforms.Compose([
transforms.CenterCrop(140),
transforms.Resize([64, 64]),
transforms.ToTensor()
])
CelebA(root='path',
... | According to documentation from pytorch:
download (bool, optional) – If true, downloads the dataset from the internet and puts it in root directory. If dataset is already downloaded, it is not downloaded again.
you can set download to false and then it will still perform the transformations on the local dataset.
| https://stackoverflow.com/questions/69753849/ |
How to design a joint loss function with two component with the aim of minimizing the first loss but maximizing the second loss? | I'm trying to do an experiment where there're two subtasks and the aim is to reduce the error rate of the 1st task and increase the error rate of the second task at the same time.
This setting may be similar with that of multi-task learning or adversarial learning.
And now my designed loss function is as follows:
total... | First, let me explain why your loss will not work and will sharply drop to the negatives.
total_loss = loss1 - alpha*loss2
You want to minimize loss1 and maximize loss2, and subsequently combined the two opposing objectives into a single total_loss.
And then you are most likely training your model/system while minimiz... | https://stackoverflow.com/questions/69763161/ |
Linear Regression in PyTorch | It's a simple regression problem. But no matter how much I try, I can't get the answer I want. I'm guessing the weight should be 32 (4 * 8) but, the code returns 25. Why is that?
This is my full source code:
import torch
import torch.nn as nn
import torch.optim as op
X = torch.FloatTensor([[1., 2.],[2., 4.],[3., 6.]]... | You are trying to approximate y = x1*x2 but are using a single linear layer i.e. a purely linear model. Ultimately, what happens is you are learning weights a and b such that y = a*x1 + b*x2. However, this model cannot approximate the distribution of x1, x2 -> x1*x2.
| https://stackoverflow.com/questions/69769799/ |
Runtime Error: mat1 and mat2 shapes cannot be multiplied in pytorch | I'm new to deep learning and I have created a model using the code below for the prediction of plant disease
class CNN_Model(nn.Module):
def __init__(self):
super(CNN_Model, self).__init__()
self.cnn_model = nn.Sequential(
nn.Conv2d(3, 16, 3),
nn.ReLU(),
nn.MaxPool2d(2, 2),
... | The size mismatch error is shown as 32x119072 and 800x300. The first shape refers to the input tensor, while the second is the parameter of the layer. If you look into your model definition you will see that it matches the first fully connected layer, the one following the flatten. Indeed, nn.Linear(800, 300) was expec... | https://stackoverflow.com/questions/69778174/ |
Huggingface giving pytorch index error on sentiment analysis task | I am trying to run sentiment analysis on a dataset of millions of tweets on the server. I am calling a API prediction function that takes a list of 100 tweets and iterate over the test of each tweet to return the huggingface sentiment value, and writes that sentiment to a solr database. However, after the process of fe... | As @Quang Hoang mentioned in the comment, it seems the problem is due to the length of your input tweet. Fortunately, you are able to determine the behavior of the tokenizer in pipeline class and truncate longer tweets explicitly. In addition, it's possible to set any other argument for pipeline elements.
MODEL_CHECKPO... | https://stackoverflow.com/questions/69796828/ |
Is there any way to create a tensor with a specific pattern in Pytorch? | I'm working with linear transformation in the form of Y=Q(X+A), where X is the input tensor and Y is the output, Q and A are two tensors to be learned. Q is an arbitrary tensor, therefore I can use nn.Linear. But A is a (differentiable) tensor that has some specific pattern, as a short example,
A = [[a0,a1,a2,a2,a2],
... | This looks like a Toeplitz matrix. A possible implementation in PyTorch is:
def toeplitz(c, r):
vals = torch.cat((r, c[1:].flip(0)))
shape = len(c), len(r)
i, j = torch.ones(*shape).nonzero().T
return vals[j-i].reshape(*shape)
In your case with a0 as 0, a1 as 1 and a2 as 2:
>>> toeplitz(torch.... | https://stackoverflow.com/questions/69809789/ |
Pip install from source without building a wheel | I have a Python package that includes large PyTorch model checkpoints. I try including those in my setup.py as
package_data = {'mypackage': ['model_weights/*', 'model_weights/sequential_models*']},
Now the problem is whenever I try to install from the source via pip install mypackage/ --no-cache-dir I get a MemoryErro... | You can run
$ pip install mypackage/ --no-cache-dir --no-binary=mypackage
to skip wheel building (assuming mypackage is actually your distribution name - this is what you pass as name to setup() function).
| https://stackoverflow.com/questions/69810109/ |
Is there a way to compute a circulant matrix in Pytorch? | I want a similar function as in https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.circulant.html to create a circulant matrix using PyTorch. I need this as a part of my Deep Learning model (in order to reduce over-parametrization in some of my Fully Connected layers as suggested in https://arxiv.org/abs... | You can make use of unfold to extract sliding windows. But to get the correct order you need to flip (later unflip) the tensors, and first concatenate the flipped tensor to itself.
circ=lambda v:torch.cat([f:=v.flip(0),f[:-1]]).unfold(0,len(v),1).flip(0)
| https://stackoverflow.com/questions/69820726/ |
what is equivalent to torch.load() in tensorflow? | I want to know if there is any way to see the parameters of models in tensorflow. there is a command in pytorch i.e. torch.load('/filepath').
| Provided that you already have a model saved at MODEL_PATH, this should do the trick:
model = tf.keras.models.load_model(MODEL_PATH)
model.summary()
Check this out for more info on saving and loading models.
| https://stackoverflow.com/questions/69825651/ |
Can't install Pytorch in Pycharm terminal, Python 3.10 .win 10 | I go to pytorch site and take this
pip3 install torch==1.10.0+cu113 torchvision==0.11.1+cu113 torchaudio===0.10.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html
I have windows 10 ,Python version is 3.10 ,CUDA version is 11.5
And I get this error
ERROR: Could not find a version that satisfies the re... | Check out the official issue on Pytorch's Github repository.
I've tried your exact command on python 3.9.5 and it works. I believe the issue is that PyTorch is not supported by python 3.10 yet.
Downgrading to any 3.9 version of Python should solve your problem.
| https://stackoverflow.com/questions/69826153/ |
How can I read pytorch model file via cv2.dnn.readNetFromTorch()? | I am able to save a PyTorch custom model? (it can work any PyTorch version above 1.0)
However, I am not able to read the saved model. I am trying to read it via cv2.dnn.readNetFromTorch() so as to use the model in Opencv framework (4.1.0).
I saved the PyTorch model with different methods as follows to see whether this ... | OpenCV documentation states can only read in torch7 framework format. There is no mention of .pt or .pth saved by pytorch.
This post mentions pytorch does not save as .t7.
.t7 was used in Torch7 and is not used in PyTorch. If I’m not mistaken
the file extension does not change the behavior of torch.save.
An alternate... | https://stackoverflow.com/questions/69838994/ |
libtorch throws c10::error after build on Windows 10 (VS2019) | I've tried to build libtorch on Windows 10 using VS 2019 without CUDA and Python. Independent if I compile it with or without MKL, a simple test program crashes directly after start. After building the debug version, libtorch throws a c10:error in a function called torchCheckFail.
The function seems to complain about A... | I encountered the same exact error with the same environment.
A solution that worked for me was to take a release version of pytorch and not a non-release one (i.e. a release version + some commits).
Hope it helps.
| https://stackoverflow.com/questions/69839674/ |
Is it possible to train ONNX models developed in tensorflow and pytorch with C++? | I wonder if its possible to use tensorflow and pytorch models converted to onnx models to train them with the C++ Api like it is done in e.g. https://gist.github.com/asimshankar/5c96acd1280507940bad9083370fe8dc with a tensorflow model. I just found examples for inference with onnx. The idea is to be able to prototype w... | ONNX's GitHub page suggests that it can be used for inference, but it doesn't seem reasonable to be able to train all models with it (from the development perspective).
Currently we focus on the capabilities needed for inferencing (scoring).
Although there are some difficulties, such as always writing backpropagation... | https://stackoverflow.com/questions/69853476/ |
Finding out distance between output of two Convolutional Neural Network (CNN) i.e Siamese Network | I am trying to build a simple Siamese neural network for usage in Human re-identification.
For that, I have used MTCNN (https://github.com/timesler/facenet-pytorch) for face detection and official pytorch implementation of arcface algorithm (https://github.com/deepinsight/insightface/tree/master/recognition/arcface_tor... | I've tried and got fully enjoied Elasticsearch with standard dlib face vectors (128x1)... ES can store and search&compare such kind vectors super fast and accurate.
I've used somthing like this to creat a ES index:
from elasticsearch import Elasticsearch
es = Elasticsearch([{'host': ELASTIC_HOST, 'port': ELASTIC_P... | https://stackoverflow.com/questions/69895999/ |
Linear decay as learning rate scheduler (pytorch) | I have read about LinearLR and ConstantLR in the Pytorch docs but I can't figure out, how to get a linear decay of my learning rate. Say I have epochs = 10 and lr=0.1 then I want to linearly reduce my learning-rate from 0.1 to 0 (or any other number) in 10 steps i.e by 0.01 in each step.
| The two constraints you have are: lr(step=0)=0.1 and lr(step=10)=0. So naturally, lr(step) = -0.1*step/10 + 0.1 = 0.1*(1 - step/10).
This is known as the polynomial learning rate scheduler. Its general form is:
def polynomial(base_lr, iter, max_iter, power):
return base_lr * ((1 - float(iter) / max_iter) ** power)
... | https://stackoverflow.com/questions/69899602/ |
Does model evaluation during training affect final accuracy in PyTorch? | During a simple training loop for PyTorch a strange effect was observed.
If the evaluation function is called or not seems to have effects on the final performance of the model.
We train on the CIFAR10 using a very simple MLP model and Adam with 10 training epochs.
We try two Main loops:
After the end of each training... | The observed difference would be due to variance because of stochasticity in the optimization algorithm. The evaluation you perform has no effect on the model's weights.
Also in the link you provided, you are re-initializing a SimpleMLP on both experiments. Since the module's weights get instantiated randomly the infer... | https://stackoverflow.com/questions/69899685/ |
How to use django rest api to do inference? | I was trying to build a website with Django rest API as the backend. when given a string Its gives the score from 1 to 10 for negativity.
The frontend part of the website was built using next.js. Previously I have made the same app without Django rest API by doing all inference in the views.py file. Now I am using Rest... | I do it the following way:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET', 'POST'])
def snippet_list(request):
"""
List all code snippets, or create a new snippet.
"""
if request.method == 'GET':
# if yo... | https://stackoverflow.com/questions/69907801/ |
What is the proper way to use pytorch and matplotlib with MKL on Windows? | Is there any clear instruction on how to actually make this work?
The error message I get is:
Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.
It seems, there are only workarounds, such as to opt out from MKL altogether (not to mention, say, nomkl is not available on Windows) or
i... | If you have conda and pip installed on your machine. Please try installing by creating a new conda environment. You could try the below steps (which I have validated from my end) to install matplotlib and pytorch (with mkl).
conda create -n myenv
conda activate myenv
conda install pytorch torchvision torchaudio cpuonl... | https://stackoverflow.com/questions/69912244/ |
Pytorch Conv1D gives different size to ConvTranspose1d | I am trying to build a basic/shallow CNN auto-encoder for 1D time series data in pytorch/pytorch-lightning.
Currently, my encoding block is:
class encodingBlock(nn.Module):
def __init__(self):
super().__init__()
self.conv1d_1 = nn.Conv1d(1, 64, kernel_size=32)
self.relu = nn... | 1. Regarding input and output shapes:
pytorch's doc has the explicit formula relating input and output sizes.
For convolution:
Similarly for pooling:
For transposed convolution:
And for unpooling:
Make sure your padding and output_padding values add up to the proper output shape.
2. Is there a better way?
Transpos... | https://stackoverflow.com/questions/69915792/ |
PyTorch with CUDA and Nvidia card: RuntimeError: CUDA error: all CUDA-capable devices are busy or unavailable, but torch.cuda.is_available() is True | Problem:
I occasionally get the following CUDA error when running PyTorch scripts with CUDA on an Nvidia GPU, running on CentOS 7.
If I run:
python3 -c 'import torch; print(torch.cuda.is_available()); torch.randn(1).to("cuda")'
I get the following output:
True
Traceback (most recent call last):
File &qu... | When I'm outside of Python and run nvidia-smi, it shows a process running on the GPU, despite the fact that I cancelled execution of the PyTorch script:
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.27.04 Driver Version: 460.27.04 CUDA Version: 11.2 |
|------... | https://stackoverflow.com/questions/69919854/ |
How to split dataset into two considering fixed seed to ensure reproducibility in PyTorch? | I am working on one of my University assignment and there is one sub-task which says. Split the data in two (Train and Validation) while using using a fixed seed to ensure reproducibility. I have wrote some code which is working fine but I want to know whether it is the correct way or not?
torch.manual_seed(0)
mnist_t... | According to PyTorch's docs:
Completely reproducible results are not guaranteed across PyTorch releases, individual commits, or different platforms. Furthermore, results may not be reproducible between CPU and GPU executions, even when using identical seeds.
However, there are some steps you can take to limit the numbe... | https://stackoverflow.com/questions/69919918/ |
PyTorch: module 'torch' has no attribute 'gradient' | PyTorch seems to have a serious bug leading to the error message
AttributeError: module 'torch' has no attribute [some torch function]
In my case, I try to use torch.gradient link.
I am using Python version 3.8.5 and tried the PyTorch Versions 1.6.0, 1.7.0, 1.7.1 , 1.8, 1.9.0 for CPU. (The newest version has another b... | The same happened to me. What I did was to create a new conda environment and reinstall PyTorch according to https://pytorch.org/
| https://stackoverflow.com/questions/69919938/ |
Why VAE loss doesn’t converge to zero? | I’m using a Variational Autoencoder and this is my implementation for the loss function:
class VariationalAutoencoder(nn.Module):
# ...some functions...
def gaussian_likelihood(self, x_hat, logscale, x):
scale = torch.exp(logscale)
mean = x_hat
dist = torch.distributions.Normal(mean, sc... | Loss for VAE can be negative. It has a log-likelihood - which can be negative. There is nothing wrong in that.
| https://stackoverflow.com/questions/69926777/ |
How to randomly set a variable number of elements in each row of a tensor in PyTorch | I want to create a zero-one matrix of dimension (n, n). The ones should be placed randomly, with a cap on the number of ones in each row. Let us say I have a list of length n that has the value of cap for each of the n rows. How can I do this in PyTorch?
My question is similar to this previous question. The only change... | As explained by @Marcel in the comments above, you can first set the first m values to value k then index by permuted indices in order to get a shuffle tensor:
>>> n = 10; m = 3; k = 1
>>> x = torch.zeros(n, n)
>>> x[:, :m] = k
tensor([[1., 1., 1., 0., 0., 0., 0., 0., 0., 0.],
[1., 1... | https://stackoverflow.com/questions/69931610/ |
Implementation of multitask "nested" neural network | I am trying to implement a multitask neural network used by a paper but am quite unsure how I should code the multitask network because the authors did not provide code for that part.
The network architecture looks like (paper):
To make it simpler, the network architecture could be generalized as (For demo I changed t... | This is actually a common pattern. It would be solved by code like the following.
class Network(nn.Module):
def __init__(self, ...):
self.encoder = DrugTargetInteractiongNetwork()
self.mlp1 = ClassificationMLP()
self.mlp2 = PairwiseMLP()
def forward(self, data_a, data_b):
a_encoded = self... | https://stackoverflow.com/questions/69935341/ |
RuntimeError: CUDA error: initialization error when calling torch.distributed.init_process_group using torch multiprocessing | I created a pytest fixture using decorator to create multiple processes (using torch multiprocessing) for running model parallel distributed unit tests using pytorch distributed. I randomly encountered the below CUDA initialization error all of a sudden (when I was trying to fix some unit tests logic). Since then, all ... | Not sure how much its useful now but we were getting this error when running yolox script command
https://github.com/Megvii-BaseDetection/YOLOX
python -m yolox.tools.train -n yolox-s -d 8 -b 64 --fp16 -o [--cache]
However when we removed the --cache parameter the error was resolved.
Another issue we encountered was scr... | https://stackoverflow.com/questions/69935635/ |
How to fix RuntimeError: Bool type is not supported by dlpack | I have been using the following code to get the default Cora dataset provided by DGL, but the following error suddenly occurred today.
The code was runned in CoLab (python 3.7 and Pytorch backend). I believed this is a error from the DGL update (since it had worked all the time before). However, I just wonder if there ... | It seems that an error is from torch update to 1.10.0. Reinstalling torch to 1.9.1 works for me. You can reinstall torch in colab as follows:
!pip install dgl==0.6.1
!pip install torch==1.9.1
import dgl
cora = dgl.data.CoraGraphDataset()
| https://stackoverflow.com/questions/69937348/ |
What are the in_features and out_features supposed to be? | torch.nn.Linear(in_features, out_features, bias=True, device=None, dtype=None)
I have a dataset of [914,19] shape. should my in_features be 914? And I want to predict 5 different values so should my output feature be 5?
class NeuralNetwork(nn.Module):
def __init__(self):
super(NeuralNetwork, self).__init__(... | Your input data is shaped (914, 19), assuming 914 refers to your batch size here, then the in_features corresponds to 19. This can be read as a tensor containing 914 19-feature-long input vectors.
In this case, the in_features of linear1 would be set to 19.
| https://stackoverflow.com/questions/69939180/ |
what does mask_fill in pytorch do here | I have tensor named "k1" which is in shape 3,1,1,9 and also have p1 tensor in shape of 3,7,9,9 and I wanna know what does the line below do?
p1 = p1 .masked_fill(k1== 0, float("-1e30"))
| As the documentation page describes it:
Tensor.masked_fill(mask, value)
Fills elements of self tensor with value where mask is True. The shape of mask must be broadcastable with the shape of the underlying tensor.
In your case it will place in p1 the value of float("-1e30") at the positions where k1 is equ... | https://stackoverflow.com/questions/69956001/ |
The same output value whatever is the input value for a Pytorch LSTM regression model | My dataset looks like the following:
on the left, my inputs, and on the right the outputs.
The inputs are tokenized and converted to a list of indices, for instance, the molecule input:
'CC1(C)Oc2ccc(cc2C@HN3CCCC3=O)C#N'
is converted to:
[28, 28, 53, 69, 28, 70, 40, 2, 54, 2, 2, 2, 69, 2, 2, 54, 67, 28, 73, 33, 68, 69... | Your LSTM_regr returns the last hidden state regardless of the true sequence length. That is, if your true sequence is of length 3, x is of length 100, and the output is the last hidden state after processing 97 padding elements.
You should compute the loss for the prediction that matches the true length of each sequen... | https://stackoverflow.com/questions/69964929/ |
RuntimeError: CUDA error: no kernel image is available for execution on the device after model.cuda() | I am working on this model:
class Model(torch.nn.Module):
def __init__(self, sizes, config):
super(Model, self).__init__()
self.lstm = []
for i in range(len(sizes) - 2):
self.lstm.append(LSTM(sizes[i], sizes[i+1], num_layers=8))
self.lstm.append(torch.nn.Linear(sizes[-2]... | I checked the latest torch and torchvision version with cuda from the given link. Stable versions list: https://download.pytorch.org/whl/cu113/torch_stable.html
Below versions solved the error,
pip install torch==1.11.0+cu113 torchvision==0.12.0+cu113 -f https://download.pytorch.org/whl/torch_stable.html
Reference: #49... | https://stackoverflow.com/questions/69968477/ |
About np.einsum | I don't understand how the following code realizes the transformation of dimensions? The shape of C is [2, 3, 3, 4]. How to realize the following matrix operation without einsum function?
import numpy as np
a = np.random.randint(0, 10, (2,3,4))
b = np.random.randint(0, 10, (3, 6, 4))
c = np.einsum('bld,hid-> blhd', ... | You can find more details in about einstein notation wikipedia
This means that you have indices b,l,h,i,d
this will iterate the indices to cover all the inputs and build the input
I will use capital letters for the arrays here to distinguish from the indices.
C[b,l,h,d] += A[b,l,d] * B[h,i,d]
The shape of the output c... | https://stackoverflow.com/questions/69972030/ |
Why does torch.utils.save_image overwrite saved images in my folder? | I am trying an adversarial attack on 10 images and I need to save all the perturbed images in a folder. So, I used torch.utils.save_image in pytorch which works pretty fine. I expect all the images to be saved in the folder but instead, they are being overwritten and the last image seen is the only image saved. I have ... | So I figured out how to solve it myself.
I noticed that variable count in attack() will not increase no matter how. Instead, I set count = 1 outside attack() and did global count inside same attack(). This way, value of count can change and will not remain thesame everytime attack_all() calls the function attack().
| https://stackoverflow.com/questions/69973075/ |
How do I load a yolov5l model with custom weights into torch in python? | I have trained a yolov5l model for object detection and classification. I want to use the exported weights to identify images in a program I am creating. I am having trouble finding much of anything on how to use .pt weights in a python program.
I believe I use the "torch.load" method from the pytorch library... | You should use torch.load_state_dict() method to load your trained parameters to your model in addition to torch.load().
There are some issues with your torch.load() method. You should provide your path parameter as a either string or os.PathLike object. (These are written in the docs).
I am going to provide a simple c... | https://stackoverflow.com/questions/69977082/ |
RuntimeError: PytorchStreamReader failed locating file data.pkl: file not found | I have been trying to train some data using a model that utilizes src+img. When running the training script, I'm running into an error namely: RuntimeError: PytorchStreamReader failed locating file data.pkl: file not found
the .pkl file in this should have been the pickled .pt file.
First I figured that maybe I did not... | This issue has been resolved. the .pt file was heavily corrupted. After deleting the corrupt .pt file and re-running the preprocess script and consequently training script, I did not get the error anymore.
| https://stackoverflow.com/questions/69979034/ |
What is the difference between cuda.amp and model.half()? | According to https://pytorch.org/blog/accelerating-training-on-nvidia-gpus-with-pytorch-automatic-mixed-precision/
We can use:
with torch.cuda.amp.autocast():
loss = model(data)
In order to casts operations to mixed precision.
Another thing is that we can use model.half() to convert all the model weights to ... | If you convert the entire model to fp16, there is a chance that some of the activations functions and batchnorm layers will cause the fp16 weights to underflow, i.e., become zero. So it is always recommended to use autocast which internally converts the weights to fp32 in problematic layers.
model.half() in the end wil... | https://stackoverflow.com/questions/69994731/ |
How to save png images with OpenCV | I am trying to use OpenCV to convert the results of the model I trained into a png image. My output has 4 channels, and I am not sure how to convert these 4 channels to png.
# Load the model
model = CNNSEG()
model.load_state_dict(torch.load(PATH))
model.eval()
for iteration, sample in enumerate(test_data_loader):
... | You would want to split your image into two essentially and then save them individually.
import numpy as np
import cv2
img = np.ones((2,4,96,96),dtype=np.uint8) #creating a random image
img1 = img[0,:,:,:] #extracting the two separate images
img2 = img[1,:,:,:]
img1_reshaped = img1.transpose() #reshaping them to the... | https://stackoverflow.com/questions/69996609/ |
need help in modifying code to access YOLOv5 for CPU | I am trying to implement a object detection program with Pytorch , OpenCV and YOLOv5 that detect the objects and the type of object from a YouTube video . However, while running, the output console shows that the YOLO version the program is trying to run is for CUDA . I wish to use the YOLO for CPU to implement the pro... | From your __init__ it shows that you give the system the option to choose CUDA if it is available. You can force it to run on cpu by stating self.device = 'cpu' on line 23. Then when calling self.model.to(self.device) on line 48, the model is sent to cpu.
| https://stackoverflow.com/questions/69999605/ |
pytorch RNN loss does not decrease and validate accuracy remains unchanged | I'm training a model using Pytorch GRU on a text-classification task (output dimension is 5). My network is implemented like the codes below.
class GRU(nn.Module):
def __init__(self, model_param: ModelParam):
super(GRU, self).__init__()
self.embedding = nn.Embedding(model_param.vocab_size, model_p... | Now I found that loss does not drop down mainly because weight decay set in optimizer is to high.
optimizer = SGD(model.parameters(), lr=learning_rate, weight_decay=0.9)
So I fixed this and changed weight decay to be 5e-5.
optimizer = SGD(model.parameters(), lr=learning_rate, weight_decay=5e-5)
This time the loss of ... | https://stackoverflow.com/questions/70006954/ |
PyTorch and torch_scatter were compiled with different CUDA versions on Google Colab despite attempting to specify same version | I'm installing pytorch geometric on Google colab. I've done this lots of times before and had no issues but it has suddenly stopped working. I've not changed my code since it worked. Here is how I install it:
!pip install torch==1.8.1 torchvision torchtext
import torch; print(torch.__version__); print(torch.version.cud... | you could try to specify the latest wheel version provided by the link you use: https://pytorch-geometric.com/whl/torch-1.8.1+cu102.html (for November 22nd 2021 it is 2.0.8):
pip install torch-scatter==2.0.8 -f https://data.pyg.org/whl/torch-1.8.1+cu102.html
It looks like the latest torch-scatter version in Google Col... | https://stackoverflow.com/questions/70008715/ |
How to use tensor cores in pytorch and tensorflow? | I am using a Nvidia RTX GPU with tensor cores, I want to make sure pytorch/tensorflow is utilizing its tensor cores. I noticed in few articles that the tensor cores are used to process float16 and by default pytorch/tensorflow uses float32. They have introduced some lib that does "mixed precision and distributed t... | Mixed Precision is available in both libraries.
For pytorch it is torch.cuda.amp, AUTOMATIC MIXED PRECISION PACKAGE.
https://pytorch.org/docs/stable/amp.html
https://pytorch.org/docs/stable/notes/amp_examples.html.
Tensorflow has it here, https://www.tensorflow.org/guide/mixed_precision.
| https://stackoverflow.com/questions/70013685/ |
tensorflow 2.4.1 requires six~=1.15.0, but you have six 1.16.0 which is incompatible | Iam getting this error:-
[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
104 1m 15s tensorflow 2.4.1 requires six~=1.15.0, but you have six 1.16.0 which is incompatible.[
when i try t... | after installing all dependencies, install six 1.15.0
pip install -r requirements.txt
then run
pip install six~=1.15.0
or
pip install six==1.15.0
| https://stackoverflow.com/questions/70014599/ |
Best way to import CSV data in a python tensor for machine learning? | I want to import a csv data file in python in order to create a neural network down the road (with pytorch). The file has 4 columns and around 1000 rows with first row as titles. Which is the best way to do this?
| Just use pandas.
In particular what you need is the read_csv function.
import pandas as pd
...
dataframe = pd.read_csv("/location/file.csv")
Check out the pandas references for more details.
| https://stackoverflow.com/questions/70025566/ |
Pandas: Unexpected behavior for apply function with torch.tensor() | I confused of the behavior of the panda.apply() function. I want to convert a column containing a list of int to a troch.tensor. Here is some sample code showing the behavior:
df_test = pd.DataFrame([3,3,3], columns=['value'])
df_test.value = df_test.value.apply(lambda x: [y for y in range(x)])
print(df_test)
# Output:... | The reason is that apply function converts implicitly a tensor to list because the type of df_test.value[0] is a list. When you convert a tensor to a list, here is a result:
print(df_test.value[0]) # list
x = torch.tensor([1,2,3])
print(list(x)) # convert a tensor to a list
[tensor(1), tensor(2), tensor(3)]
You ... | https://stackoverflow.com/questions/70031998/ |
How to convert from tensor to float | I am having a list of tensors I want to convert to floating points how can I do it. I have tried using .item but it is not working. I am getting ValueError: only one element tensors can be converted to Python scalars.
tensor([[12.1834, 4.9616, 7.7913],
[ 8.9394, 8.5784, 9.3691],
[ 9.4475, 8.9766, ... | You just need to cast Tensor constant to numpy object,then can access by index.
result.numpy()[0]
| https://stackoverflow.com/questions/70043645/ |
Pytorch - IndexError: index out of range in self | I am working on building a LSTM based seq2seq sentence - slots solution.
For instance:
Input sentence: My name is James Bond
Output Slot: O O O B-name I-name
I'm unable to figure out the reason for the below error:
IndexError: index out of range in self
> <ipython-input-37-19283c592e18>(12)<module>()
... | The vocabulary size for the Embedding layer is 1148: Embedding(1148, 560) but in the inputs you have index 1150. Maybe it is the source of your problem?
| https://stackoverflow.com/questions/70052109/ |
How to build neural network in this structure?with different nodes connects to different number of nodes in next layer | I only know how to use the built-in network like RNN of LSTM in PyTorch. But they tend to deal with every node in the previous layer that will give information to all nodes in the next layer.
I want to do something different but don't know how to code it myself. Like in this figure: the node a maps to all [d, e, f] th... | When you have a layer that looks like Fully-Connected layer but with custom connectivity, use a mask with proper structure.
Let's say x = [a, b, c] is your 3-dim input and W denotes the connectivity matrix.
>> x
tensor([[0.1825],
[0.9598],
[0.2871]])
>> W
tensor([[0.7459, 0.4669, 0.9687],
... | https://stackoverflow.com/questions/70055054/ |
loss.backward() no grad in pytorch NN | The code gives an error in loss.backward()
Error is:
untimeError: element 0 of tensors does not require grad and does not have a grad_fn
for epoch in range(N_EPOCHS):
model.train()
for i,(im1, im2, labels) in enumerate(train_dl):
i1 = torch.flatten(im1,1)
i2 = torch.flatten(im2,1)
inp = ... | With additional info given by OP in the comment, the correct approach here is just removing the line
y_ = (y_>0.5).float()
| https://stackoverflow.com/questions/70056774/ |
Select and MSELoss for two torch tensors | I have two torch tensors:
predictions = tensor([[33, 34, 7, 5, 5, 23, 22, 1, 3, 5, 23, 1],
[14, 1, 22, 7, 5, 11, 7, 33, 3, 12, 25, 22],
[33, 1, 14, 12, 23, 22, 12, 2, 3, 12, 23, 14],
[23, 34, 34, 3, 5, 25, 12, 11, 2, 23, 23, 13]])
labels = tensor([[-100, -100, -100, -100, -100... | In Short
# convert to float
predictions = predictions.to(torch.float)
labels = labels.to(torch.float)
# pick the right entries
reduced_predictions = predictions[labels != -100]
reduced_labels = labels[labels != -100]
# initialaize loss_fn
torch.nn.MSELoss()(reduced_predictions, reduced_labels)
# Note ^ c... | https://stackoverflow.com/questions/70058203/ |
Create a Image stack in PyTorch | I have a Bx3xHxW image tensor in PyTorch and wish to create a Bx3FxHxW image stack of this image where F=64.
The image stack is formed by shifting the original image right. That is if the original image is to be shifted by 2 pixels to the right, the two left-most columns in new image will be 0 and the third-last column... | Torch (as well as numpy) provides torch.roll function, by padding with zeros first, rolling and then slicing the result you can achieve your right shift.
Here's a numpy version:
import numpy as np
X = np.random.rand(4,3,28,28)
Z = np.zeros((4,3,28,28))
XZ = np.concatenate([X,Z],axis=-1)
res = []
shift = 2
F = 28//shi... | https://stackoverflow.com/questions/70064110/ |
Understanding torch.nn.LayerNorm in nlp | I'm trying to understanding how torch.nn.LayerNorm works in a nlp model. Asuming the input data is a batch of sequence of word embeddings:
batch_size, seq_size, dim = 2, 3, 4
embedding = torch.randn(batch_size, seq_size, dim)
print("x: ", embedding)
layer_norm = torch.nn.LayerNorm(dim)
print("y: ",... | Pytorch layer norm states mean and std calculated over last D dimensions. Based on this as I expect for (batch_size, seq_size, embedding_dim) here calculation should be over (seq_size, embedding_dim) for layer norm as last 2 dimensions excluding batch dim.
A similar question and answer with layer norm implementation ca... | https://stackoverflow.com/questions/70065235/ |
Best practice for controlling Pytorch's neural network layers' number and size? | I'm looking for best practices for controlling/adjusting the number of layers and also their sizes in Pytorch neural networks in general.
I have a configuration file in which I specify values for particular experiment variables. Additionally, I'd like to have an option in this file to determine the number and size of P... | I use the following snippet for this task:
import torch.nn as nn
num_inputs = 10
num_outputs = 5
hidden_layers = (128, 256, 128)
activation = nn.ReLU
layers = (
num_inputs,
*hidden_layers,
num_outputs
)
network_architecture = []
for i in range(1, len(layers)):
network_architecture.append(nn.Linear(la... | https://stackoverflow.com/questions/70065838/ |
Couldn't load the Pytorch optimised model in android | This is the error I'm getting in android while loading the model.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.example.cataractdetectionapp/com.android.example.cataractdetectionapp.InferenceActivity}:
com.facebook.jni.CppException: Could not run 'aten::empty_strided' with arguments f... | The solution to this error was simple. The error was because the model was saved with the Runtime being GPU. So, I loaded the native PyTorch model again in the CPU environment and saved it for Lite Interpreter and it is successfully loading in the android app.
| https://stackoverflow.com/questions/70081406/ |
Dicom data training failed by pytorch | I've got a problem about training the Pytorch models. I'm trying to train my Pytorch model using dicom data and nifti GT However, the size of the weight file is ridiculously small because model training is not performed normally.
I used network model Unet++
I think there is a problem with the data loader. But I can't f... | Depending on what modality your images are, this might possibly be due to not converting the image data into the correct, clinically relevent, machine/vendor independent, units prior to any ML training 0-1 normalization.
Typically in dicom files, the actual raw data values aren't that - they need processing...
For inst... | https://stackoverflow.com/questions/70091655/ |
Does albumentations normalize mask? | When I pass an image and a mask to albumentations.Normalize(mean, std).
How would I go about incorporating this?
Should I just add it manually in dataset?
Grateful for any tips you have!
| Edited:
Normalization works for three-channel images. If your mask image is grayscale image then probably you need to stack(image= np.stack((img,)*3, axis=-1))
it and make three channel image then apply albumentations's Normalization function. Official function for A.Normalize() is as following which deals with RGB ima... | https://stackoverflow.com/questions/70094632/ |
NameError: name '_C' is not defined | When running a Python project using torch==1.4.0 I got the error in the title. I am using Linux and not using any kind of IDE or notebook.
There are other questions about this, but they were all in Jupyter notebooks or on Windows.
| What happened is that the version of libffi I was using was too new. It looks like libffi recently upgraded to version 8, but something (Torch?) required v7. v7 not being present caused some kind of import to fail silently rather than given a clear error, resulting in the error in the title.
I was able to fix this by i... | https://stackoverflow.com/questions/70107055/ |
How can I change self attention layer numbers and multihead attention head numbers in my model with Pytorch? | I working on sarcasm dataset and my model like below:
I first tokenize my input text:
PRETRAINED_MODEL_NAME = "roberta-base"
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(PRETRAINED_MODEL_NAME)
import torch
from torch.utils.data import Dataset, DataLoader
MAX_LEN = 100
th... | The short answer is: You can't.
You are using a pretrained model:
model = AutoModelForSequenceClassification.from_pretrained(PRETRAINED_MODEL_NAME).to(device)
You can't easily change the pretrained model. It is possible to change pretrained models, but that is definitely not straightforward. You can download different... | https://stackoverflow.com/questions/70112800/ |
Failed to install Pytorch Snippets and Librosa in VScode - Apple M1 | I anticipate I'm not an expert in informatics. I used to run PyTorch snippets for some deep learning on my old MacBook Pro (2015), but now I have Apple's last Pro, and have troubles with installing packages in VScode. Two of these packages give me trouble: PyTorch snippets and Librosa. PyTorch Snippets can be installed... | There is a fix described in
https://github.com/numba/llvmlite/issues/693#issuecomment-909501195
arch -arm64 brew install llvm@11
LLVM_CONFIG="/opt/homebrew/Cellar/llvm@11/11.1.0_2/bin/llvm-config" arch -arm64 pip install llvmlite
| https://stackoverflow.com/questions/70117868/ |
why and when to use torch.cuda.Stream() | I found torch.cuda.Stream() is manually defined in some open source code.
self.input_stream = torch.cuda.Stream()
self.model_stream = torch.cuda.Stream()
self.output_stream = torch.cuda.Stream()
On torch page, it says
You normally do not need to create one explicitly: by default, each device uses its own “... | Streams are sequences of cuda kernels. Operations in different streams may run in parallel. I don't believe they have to use them. They are are just making the code more parallel and thus hopefully faster.
| https://stackoverflow.com/questions/70128833/ |
How to concatenate a 0-D tensor into a 3-D tensor in PyTorch? | I have the following tensor:
X = torch.randn(30,1,2) # [batch_size, dim_1, dim_2]
t = torch.Tensor([0])
I am trying to concatenate the t tensor into X tensor that results [30,1,3] tensor. However, I tried couple of methods even with torch.stack. I still have not figured out how to do this properly. I tried both and... | You can't concatenate the two described tensors, the shape of tensor X is [30, 1 , 2], which means it has 30 positions in the first dimension, 1 position in the second dimension, and 2 positions in the last dimension, totalling 30*1*2 = 60 elements. A tensor of shape [30,1,3] has 90 elements, meaning you need to add 30... | https://stackoverflow.com/questions/70131674/ |
PyTorch Lightning auto_scale_batch_size='power' does not show results | I am very new to Deep Learning, and am converting an existing project into a Pytorch Lightning one following this tutorial.
I want to try the automatic batch size finder. So I added the requested flag to the Trainer :
trainer = pl.Trainer(default_root_dir=model_dir,
auto_scale_batch_size='power')
... | My bad, I missed something in the video that I later found in the doc. I was calling trainer.fit(model) instead of trainer.tune(model). Now it is working great!
| https://stackoverflow.com/questions/70135432/ |
Problem encountered in MMDetection. KeyError: 'mask_detectionDataset is not in the dataset registry' | I tried to train my model with MMdetection, however, error like "KeyError: 'mask_detectionDataset is not in the dataset registry'" keep showing.
I've added my dataset to init.py in \mmdetection\mmdet\datasets. And use @DATASETS.register_module(), but problem doesn't solved.
When I try to run init.py directly ... | maybe add a custom_imports key in your config?
custom_imports = dict(
imports=['mmdet.datasets.mask_detectionDataset'],
allow_failed_imports=False)
| https://stackoverflow.com/questions/70136275/ |
Import error while launching PyTorch Lightning project on Colab TPU | I followed this guide to launch my PyTorch Lightning project on Google Colab TPU. So I installed
!pip install cloud-tpu-client==0.10 https://storage.googleapis.com/tpu-pytorch/wheels/torch_xla-1.9-cp37-cp37m-linux_x86_64.whl
Then
!pip install pytorch-lightning
Then I
!pip install torch torchvision torchaudio
!pip i... | Actually the same problem has also been described and the suggested solution did work for me.
So in the details they suggest to downgrade PyTorch to 1.9.0+cu111 (mind the +cu111) after installing torch_xla.
Consequently here are the steps I followed to launch my Lightning project on Google Colab with TPU :
!pip install... | https://stackoverflow.com/questions/70136356/ |
WSL2 Pytorch - RuntimeError: No CUDA GPUs are available with RTX3080 | I have been struggling for day to make torch work on WSL2 using an RTX 3080.
I Installed the CUDA-toolkit version 11.3
Running nvcc -V returns this :
nvcc -V
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2021 NVIDIA Corporation
Built on Sun_Mar_21_19:15:46_PDT_2021
Cuda compilation tools, release 11.3, V11.3... | In my case, I solved this issue by linking /usr/lib/wsl/lib/libcuda.so.1 to the libcuda.so in your wsl2 CUDA location. See https://github.com/microsoft/WSL/issues/5663
After reboot, pytorch can find the GPU.
(I found the warning " /usr/lib/wsl/lib/libcuda.so.1 is not a symbolic link" during the apt-get upgrad... | https://stackoverflow.com/questions/70148547/ |
Counting number of occurrences in PyTorch Tensor. (Tensor is too big for Numpy) | Is there any smart way to count the number of occurrences of each value in a very Large PyTorch Tensor? Tensor Size is 11701*300=3510300 or maybe increase or decrease.
TORCH.BINCOUNT, TORCH.UNIQUE and TORCH.UNIQUE_CONSECUTIVE are not useful so far.
BINCOUNT returns a different number of elements every time. Unique is a... | Actually the problem is how you read the output. The output of torch.bincount is a tensor of size max(input)+1, that means it covers all bins of size 1 from zero to max(input). Therefore, in the output tensor from the first element you see how many 0, 1, 2, ..., max(input) are there in your non-negative integral array.... | https://stackoverflow.com/questions/70156074/ |
How to clean garbage from CUDA in Pytorch? | I teached my neural nets and realized that even after torch.cuda.empty_cache() and gc.collect() my cuda-device memory is filled. In Colab Notebooks we can see the current variables in memory, but even I delete every variable and clean the garbage gpu-memory is busy.
I heard it's because python garbage collector can't w... | You can do this:
import gc
import torch
gc.collect()
torch.cuda.empty_cache()
| https://stackoverflow.com/questions/70174653/ |
How do you prevent the tensorboard logger in pytorch lightning from logging the current epoch? | When creating a new tensorboard logger in pytorch lightning, the two things that are logged by default are the current epoch and the hp_metric. I was able to disable the hp_metric logging by setting default_hp_metric=False but I can't find anything to disable the logging of the epoch. I've searched in the lightning.py,... | In Short
You can disable automatically writing epoch variable by overwriting tensorboard logger.
from pytorch_lightning import loggers
from pytorch_lightning.utilities import rank_zero_only
class TBLogger(loggers.TensorBoardLogger):
@rank_zero_only
def log_metrics(self, metrics, step):
metrics.pop('epo... | https://stackoverflow.com/questions/70183125/ |
How can I get labels from data generator? | I try to generate data for my conditional VAE and I need labels, but after generating data when I want to get labels I got this error:
def gen_batch(BATCH_SIZE):
labels = torch.randint(0, 8, (BATCH_SIZE,)).long().to(device)
theta = (np.pi/4) * labels.float().to(device)
centers = torch.stack((torch.cos(theta... | The exception was raised, because the data_gen() is a generator function, and such a function returns only a single object called a generator object, which cannot be unpacked like you tried to do. A generator object is an iterator that generates and returns data on demand and for that iterators support a special method... | https://stackoverflow.com/questions/70183245/ |
How to easily convert a PyTorch dataloader to tf.Dataset? | How can we convert a pytorch dataloader to a tf.Dataset?
I spied this snippet:-
def convert_pytorch_dataloader_to_tf_dataset(dataloader, batch_size, shuffle=True):
dataset = tf.data.Dataset.from_generator(
lambda: dataloader,
output_types=(tf.float32, tf.float32),
output_shapes=(tf.TensorSha... | For your data in h5py format, you can use the script below. name_x is the features' name in your h5py and name_y is your label's file name. This method is memory efficient and you can feed the data batch by batch.
class Generator(object):
def __init__(self,open_directory,batch_size,name_x,name_y):
self.open_direc... | https://stackoverflow.com/questions/70189513/ |
PyTorch PPO implementation for Cartpole-v0 getting stuck in local optima | I have implemented PPO for Cartpole-VO environment. However, it does not converge in certain iterations of the game. Sometimes it gets stuck in local optima. I have implemented the algorithm using the TD-0 advantage i.e.
A(s_t) = R(t+1) + \gamma V(S_{t+1}) - V(S_t)
Here is my code:
def running_average(x, n):
N = n
... | If you remove the "-" (the negative marker) in line:
loss_r = -torch.min(ratio*delta_batch, clipped)
The score will then start to steadily increase over time. Before this fix you had negative loss which would increase over time. This is not how loss should work for neural networks. As gradient descent works ... | https://stackoverflow.com/questions/70191012/ |
NotADirectoryError: [Errno 20] Not a directory when trying to load in Zip file on Google Colab | I'm trying to experiment on Google Colab with CNNs and GANs using the CelebA dataset. I'm trying to load in the data in PyTorch using ImageFolder like so:
# Loading in data
dataroot = "/content/drive/MyDrive/Colab_Notebooks/celeba/img_align_celeba.zip"
dataset = dset.ImageFolder(root = dataroot,
... | Zip files aren't folders. Try unzipping first although you'll need to cd to the folder first - so something like this.
!cd /content/drive/MyDrive/Colab_Notebooks/celeba
Then unzip
!yes|unzip -q img_align_celeba.zip -d img_align_celeba
Then this should work.
dataroot = '/content/drive/MyDrive/Colab_Notebooks/celeba/i... | https://stackoverflow.com/questions/70228305/ |
Validation losses increasing after a few epochs | I'm building a small CNN model to predict plant crop disease with the Plant Village Dataset. It consists of 39 classes of different species with and without diseases.
CNN model
class CropDetectCNN(nn.Module):
# initialize the class and the parameters
def __init__(self):
super(CropDetectCNN, self).__init... | You are facing the phenomenon of "overfitting" when your validation loss goes up after decreasing. You should stop training at that point and try to use some tricks to avoid overfitting.
Getting different predictions might happen when your gradients keep updating during inference so try explicitly "stop&... | https://stackoverflow.com/questions/70232816/ |
How can I define a mask function based on the values of a list in Pytorch | I want to mask a tensor based on its values. In the following function if I pass a range (second part) it works, but I want to have a list with various values prompt_ids (3, 8, 9, 30). But it doesn't work and throws error.
RuntimeError: Boolean value of Tensor with more than one value is ambiguous
The function:
def... | In pytorch 1.10 there is an isin function that returns a boolean array based on the condition that elements of first array are in the second array. For versions lower than it, you can implement it as follows:
def isin(ar1, ar2):
return (ar1[..., None] == ar2).any(-1)
| https://stackoverflow.com/questions/70234204/ |
Simplify pytorch einsum | Consider the following pytorch snippet:
X = torch.einsum("rij, sij -> rs", A, A)
Y = torch.einsum("rij, sij -> rs", B, B)
Z = torch.einsum("rij, sij -> rs", C, C)
torch.einsum("ij, ij, ij -> ", X, Y, Z)
which performs the following summation
Is it possible to formul... | You can make it more succinct but I don’t see much room for actual performance optimisation:
X = torch.einsum("rij, sij", A, A)
Y = torch.einsum("rij, sij", B, B)
Z = torch.einsum("rij, sij", C, C)
torch.einsum("ij, ij, ij", X, Y, Z)
| https://stackoverflow.com/questions/70237535/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.