instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
Pip could not find a version that satisfies the requirement torch (from versions: none) | I am trying to install PyTorch on my Windows 11. I have Python 3.8.1, and pip 22.2.2. I have tried running the command py -m pip install torch, but it keeps returning the error:
ERROR: Could not find a version that satisfies the requirement torch (from versions: none)
ERROR: No matching distribution found for torch
I ... | Just came across another post that mentioned how it needs to be the 64-bit version of Python to allow installation of PyTorch.
Just installed Python 3.9.13 with the 64-bit installer, and the installation worked. So, if anyone else is running into issues, would recommend first running python in command shell and checkin... | https://stackoverflow.com/questions/74018922/ |
Resizing inputs for torch model | I'm facing with this error properly and I could not see any exact solution or a solution formula for this error. My inputs are like (48x48) and that's not matching with the input shape of the resnet101. How can I edit my input to fit to the resnet101? You can see my code below, it probably helps you to understand my pr... | You can modify the input layer of resnet so that it would accept a single-channel tensors inputs using
In [1]: model = resnet101()
In [2]: model.conv1 = nn.Conv2d(1, 64, kernel_size=(2, 2))
In [3]: model(torch.rand(10, 1, 48, 48))
Out[3]:
tensor([[-0.5015, 0.6124, 0.1370, ..., 1.2181, -0.4707, 0.3285],
[-... | https://stackoverflow.com/questions/74035005/ |
PyTorch | loss.backward() -> Missing XLA configuration | The loss is calculated from the target model created using pytorch (not TensorFlow) and when propagating, I run the code below and had trouble with the following error message.
loss.backward()
(Forward propagation can be calculated without problems.)
terminate called after throwing an instance of 'std::runtime_error'
... | I solved this problem with the command.
$ pip uninstall torch_xla
This error seemed to be caused by pytorch-ignite and torch_xla.
| https://stackoverflow.com/questions/74039694/ |
Applying pre-trained BERT model to make predictions | I have recently been given a BERT model that has been pre-trained with a mental health dataset that I have. Now all I have to do is apply the model to a larger dataset to test its performance. I am absolutely new to machine learning and am stuck in this step. I am using PyTorch and would like to continue using it. Here... | From the HuggingFace documentation here, the AutoModelForMaskedLM class uses the from_pretrained() method to instantiate one of the model classes of the library (with a masked language modeling head) from a pretrained model. This is done either by using the model_type property in the config object (either passed as an ... | https://stackoverflow.com/questions/74049942/ |
Basic IPU example crashes with ValueError: Expected a parent | I wanted to test the free IPU runtime on Paperspace, as such I made a free account and selected the HuggingFace + IPU notebook.
Afterwards I created the following very simple notebook with Pytorch Lightning to perform classification on MNIST (the simplest possible example):
!python3 -m pip install torchvision==0.11.1
!... | To make Pytorch Lightning correctly handle the dataloader in this case it must be put inside the LitClassifier Class.
!python3 -m pip install torchvision==0.11.1
!python3 -m pip install pytorch_lightning
import torch
from torch.nn import functional as F
import pytorch_lightning as pl
from torch.utils.data import Dat... | https://stackoverflow.com/questions/74053078/ |
Convert PyTorch AutoTokenizer to TensorFlow TextVectorization | I have a PyTorch encoder loaded on my PC with transformers.
I saved it in JSON with tokenizer.save_pretrained(...) and now I need to load it on another PC with TensorFlow TextVectorization as I don't have access to the transformers library.
How can I convert ? I read about the tf.keras.preprocessing.text.tokenizer_from... | Simply "tf.keras.preprocessing.text.tokenizer_from_json.()" but you may need to correct format in JSON.
Sample: The sample they using " I love cats " -> " Sticky "
import tensorflow as tf
text = "I love cats"
tokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=10000, ... | https://stackoverflow.com/questions/74061933/ |
What is the proper input dimension for torch.nn.BCEWithLogitsLoss? | I am training a binary classifier and using torch.nn.BCEWithLogitsLoss as the loss function. I am confused about the proper input dimension for the loss function. Should it be [n, 1] or [n, 2]? In the case of [n, 1], where n is the number of samples, the values for the targets would just be 0 or 1, which represents the... | The documentation tells you all you need to know.
For a prediction tensor x of shape (num_samples, num_classes), the target tensor y should of the exact same shape.
Case 1
If your number of classes is two, and they are mutually exclusive, ax of shape (num_samples,) should be contrasted with a y of shape (num_samples,) ... | https://stackoverflow.com/questions/74084813/ |
CIFAR-10 CNN using PyTorch | I'm working on CIFAR-10 dataset using PyTorch and observed some categories have low accuracy around 40-50%. Why do some categories of image were more difficult to work with?
enter image description here
| The reason for low accuracy for some classes often has to do with significant similarity with other classes. For example, cat and dog may be confused for each other fairly often by the model. Your confusion matrix shows what types of mistakes your model is making. To some extent, it is confirming this intuition that... | https://stackoverflow.com/questions/74091045/ |
What does num_labels actually do? | When training a BERT based model one can set num_labels
AutoConfig.from_pretrained(BERT_MODEL_NAME, num_labels=num_labels)
So for example if we want to have a prediction of 3 values we may use num_labels=3.
My question is what does it do internally? Is it just connecting a nn.Linear to the last embedding layer?
Thanks
| I suppose if there is a num label then the model is used for classification then simply you can go to the documentation of BERT on hugging face then search for the classification class and take a look into the code, then you will find the following:
https://github.com/huggingface/transformers/blob/bd469c40659ce76c81f69... | https://stackoverflow.com/questions/74095947/ |
Different cross entropy results from NumPy and PyTorch | My prediction is y_hat = [ 0.57,0.05,0.14,0.10,0.14] and target is
target =[ 1, 0, 0, 0, 0 ].
I need to calculate Cross Entropy loss by NumPy and Pytorch loss function.
Using NumPy my formula is -np.sum(target*np.log(y_hat)), and I got 0.5621189181535413
However, using Pytorch:
loss = nn.CrossEntropyLoss()
output = tor... | You need to apply the softmax function to your y_hat vector before computing cross-entropy loss. For example, you can use scipy.special.softmax().
>>> from scipy.special import softmax
>>> import numpy as np
>>> y_hat = [0.57, 0.05, 0.14, 0.10, 0.14]
>>> target =[1, 0, 0, 0, 0]
>&... | https://stackoverflow.com/questions/74113688/ |
How can I add reshape layer in nn.Sequential? | So I'm implementing Generator of a GAN and I need the architecture as shown as below:
The problem is when I try to reshape the output of Linear layer after BatchNorm and ReLU (in fig. Dense as they have used Tensorflow) it is throwing error as :TypeError: reshape(): argument 'input' (position 1) must be Tensor, not in... |
In nn.Sequential, torch.nn.Unflatten() can help you achieve reshape operation.
For nn.Linear, its input shape is (N, *, H_{in}) and output shape is (H, *, H_{out}). Note that the feature dimension is last. So unsqueeze_noise() is not useful here.
Based on the network structure, the arguments passed to make_gen_block... | https://stackoverflow.com/questions/74149053/ |
Torch Conv 1-D Layer outputs the same value repeated | I have a torch tensors of shape (768, 8, 22), procesed by a Conv Layer 1-D Layer. The data is already standarized. The tensor is processed by the next layer:
nn.Conv1d(input_chanels = 8, output_chanels = 1, kernel_size = 3)
The output of the layer has the right dimensions, but the output matrix has the same value repea... | I've solved this issue, it's a weird situation of torch. I just remove de Conv1dfrom the init from my network class and I defined in the forward method. By doing so, the output is no longer the same for every step.
| https://stackoverflow.com/questions/74161064/ |
How to test pytorch GPU code on a CPU machine | I want to verify on CPU machine that I've moved all tensors to CUDA device correctly. Is there a way to create a mock device that is still computed on CPU but marked to be incompatible with tensors I forget to move to this device?
Motivation: this would speed up my development cycle as I don't need to deploy code and r... | Maybe the meta device is what you need.
>>> a = torch.ones(2) # defaults to cpu
>>> b = torch.ones(2, device='meta')
>>> c = a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: Expected all tensors to be on the same device, but fo... | https://stackoverflow.com/questions/74169270/ |
How to stop logging locally but only save to wandb's servers and have wandb work using soft links? | I am having a weird issue where I change the location of all my code & data to a different location with more disk space, then I soft link my projects & data to those locations with more space. I assume there must be some file handle issue because wandb's logger is throwing me issues. So my questions:
how do I... | seems like the solution is to not log to weird places with symlinks but log to real paths and instead clean up the wandb local paths often to avoid disk quota errors in your HPC. Not my fav solution but gets it done :).
Wandb should fix this, the whole point of wandb is that it works out of the box and I don't have to ... | https://stackoverflow.com/questions/74175401/ |
count how many tensor in each tensor between 2 tensors are exactly equal | Since I have learned metric 0/1 loss for multi-label classification, and I need to create that metric
so I would like to def check that could count and return how many inside tensor between two tensors are actually matched
For Example
# Only second inside tensor are exactly equal
a = torch.tensor([[1,0,1,1], [1,0,1,1]... | I'm answering my question, Thanks to the combination of @Zwang
and @LudvigH advice,
There are many ways you can do this, subtracting one tensor from the
other then summing values and finding the non zero tensors, to simply
using python's built in == function. What have you tried? - Zwang
I tried one of his methods, a... | https://stackoverflow.com/questions/74177023/ |
Removing padding from tensor | I have a tensor like:
tensor([[ 9, -1, -1],
[ 7, -1, -1],
[ 6, 4, -1]])
What is the most efficient way to remove the padding and get something like:
[[9], [7], [ 6, 4]])
Thanks in advance for any help you can provide.
| Please consider using PackedSequence in Pytorch. It's for batches with variable-length sequences, and supported by Pytorch RNN cells. You can create a PackedSequence with torch.nn.utils.rnn.pack_padded_sequence() method. Please specify padding_value to -1 since you're using -1 for paddings.
| https://stackoverflow.com/questions/74183185/ |
how to call the subclasses within the base_class? | I have problem and need some help towards object oriented
I want to create an graph dataset and some subclasses about modifying the base_graph dataset
my question how to call the subclasses within the base_class in order to remove/add nodes to the base_graph?
class base_graph(Dataset):
def __init__(self, nodes, edg... | By "how to call Modifygraph_byAdding & Modifygraph_byDeleting" do you mean to pass instances of those classes, or using them in combination with a user-defined call operator that executes some action?
Either case, you will at least need to provide such instances, either as arguments to __getitem__, or by ... | https://stackoverflow.com/questions/74186368/ |
Pytorch automatically update my python after installed | I getting started with python, I installed pytorch on my new conda environment, but it update my python version from 3.9.13 to 3.10.6. I want to maintain the 3.9.13 version. is any thing I can do?
i had try
conda install python=3.9.13
but its failed
| Recreate the environment, specifying the Python version at creation time.
conda env remove -n foo
conda create -n foo -c pytorch python=3.9.13 pytorch
Note that Conda does not share Python across different environments, so this specification is arbitrary.
| https://stackoverflow.com/questions/74210237/ |
Functions unavailable in DiffSharp | I have successfully installed DiffSharp (along with TorchSharp, Libsharp etc.), using the following F# script:
#r "nuget: DiffSharp.Core"
#r "nuget: DiffSharp.Backends.Reference"
#r "nuget: DiffSharp.Data"
#r "nuget: DiffSharp.Backends.Torch"
#r "nuget: TorchSharp"
#r &... | I'm not sure why this is not working, but the DiffSharp installation isntructions recommend using the DiffSharp-cpu package (or one for cuda or lite version if you have LibTorch already) and that works fine for me:
#r "nuget: DiffSharp-cpu"
open DiffSharp
dsharp.config(backend=Backend.Torch, device=Device.C... | https://stackoverflow.com/questions/74216327/ |
what does os.environ['KMP_DUPLICATE_LIB_OK'] actually do? | I faced some issue while trying to use pytorch on jupyter (module not found). I used pip install but my kernel kept failing.
However after adding the following code within my jupyter notebook, I managed to use pytorch without issue.
However, may I know what does this code do? Especially KMP_DUPLICATE_LIB_OK.
Thank you!... | It sets the environment variable KMP_DUPLICATE_LIB_OK to True. This is the same thing that happens if you run export KMP_DUPLICATE_LIB_OK=True on the command line (depending on which shell you are using).
Environment variables are a kind of "ambient" input to programs that can be used to hold general informat... | https://stackoverflow.com/questions/74217717/ |
Cannot install PyTorch with Python 3.11 (Windows) | I recently upgraded to Python 3.11 and proceeded to get my usual libraries back.
I managed to install everything back without much trouble.
However I cannot get Pytorch!
I installed everything through pip which worked fine until getting to Pytorch.
I get this error: "ERROR: Could not find a version that satisfies ... | I saw this issue on github: https://github.com/pytorch/pytorch/issues/86566 it looks like PyTorch doesn't support 3.11 yet.
Apparently there's a nightly build that you can try to use, I haven't tested it though.
| https://stackoverflow.com/questions/74219480/ |
Rearrange a 5D tensor using einops | I am analyzing the implementation of the ViViT: A Video Vision Transformer. The input tensor of this model has the sahpe of (batch size, num frames, channels=3, H, W). When it comes to patch embedding, it uses the Rearrange that is imported from from einops.layers.torch import Rearrange as follows:
self.to_patch_emb... | Suppose there is an input tensor of shape (32, 10, 3, 32, 32) representing (batchsize, num frames, channels, height, width).
b t c (h p1) (w p2) with p1=2 and p2=2 decomposes the tensor to (32, 10, 3, (16, 2), (16, 2))
b t (h w) (p1 p2 c) composes the decomposed the tensor to (32, 10, 32*32=1024, 2*2*3=12)
| https://stackoverflow.com/questions/74223784/ |
Tokenizer can add padding without error, but data collator cannot | I'm trying to fine tune a GPT2-based model on my data using the run_clm.py example script from HuggingFace.
I have a .json data file that looks like this:
...
{"text": "some text"}
{"text": "more text"}
...
I had to change the default behavior of the script that used to concaten... | I managed to fix the error but I'm really unsure about my solution, details below. Will accept a better answer.
This seems to solve it:
data_collator = DataCollatorForSeq2Seq(tokenizer, model=model, padding=True)
Found in the documentation
It seems like DataCollatorWithPadding doesn't pad the labels?
My problem is abo... | https://stackoverflow.com/questions/74228361/ |
Stable Baselines3 RuntimeError: mat1 and mat2 must have the same dtype | I am trying to implement SAC with a custom environment in Stable Baselines3 and I keep getting the error in the title. The error occurs with any off policy algorithm not just SAC.
Traceback:
File "<MY PROJECT PATH>\src\main.py", line 70, in <module>
main()
File "<MY PROJECT PATH>\src\... | Change the inputs to float32 , default the loader set the type as float64.
inputs = inputs.to(torch.float32)
| https://stackoverflow.com/questions/74229178/ |
New mamba environment force torch CPU and I don't know why | When creating a new mamba (conda) environment, I only get Pytorch's CPU package. Does anyone know how to ensure/force the GPU version?
Even if, the first thing I installed is cudatoolkit it keeps getting the CPU package. I tried with version 11.6 and 11.3, nothing changed.
This is the command I used:
mamba install pyto... | The command you use is the one officially recommended by PyTorch documentation.
Failure seems to be down to a new version of Pytorch (1.13) having appeared on conda-forge recently and the GPU version seems to have some dependency problems (https://anaconda.org/pytorch/pytorch/files).
Unfortunately, there does not seem ... | https://stackoverflow.com/questions/74234628/ |
How to split dataset by label or each set of data; Pytorch | I have a dataset on apple images and their sugar level.
I took 6 photos of one apple for the dataset.
So an apple has 6 photos & its sugar level.
I want to split the dataset into train and validation.
I want apple images of the whole(6 photos in one set) to go into the train or validation set.
I don't know how to s... | You could simply find the apple IDs and split by those instead. This could then be passed into a dataset class so that they are split across apple ids, rather than the standard approach of splitting randomly across the rows of the df.
apple_df = pd.read_csv(...)
apple_ids = apple_df['apple'].unique() #drop_duplicates()... | https://stackoverflow.com/questions/74267976/ |
Cannot import name 'rank_zero_only' from 'pytorch_lightning.utilities.distributed' | I am using VQGAN+CLIP_(Zooming)_(z+quantize_method_with_addons).ipynb Google Repository and when I click the cell "Loading of libraries and definitions"
It sent an error :
ImportError Traceback (most recent call last)
<ipython-input-6-fe8fafeed45d> in <module>
24... | pytorch_lightning has recently released a new version which will throw this error (version 1.8.0.post1 released on November 2nd 2022).
https://pypi.org/project/pytorch-lightning/#history
Just install an older version of pytorch_lightning and it will work.
In my system, I ran "pip install pytorch-lightning==1.6.5&q... | https://stackoverflow.com/questions/74289972/ |
Package requirements 'tensorflow~=2.10.0', 'transformers~=4.22.1', 'TorchCRF~=1.1.0' are not satisfied | I am using PyCharm 2022.2.3 (Professional Edition), Python 3.11.0 (have any problem in compatible between this version of Python with PyTorch?) , Windows 11 x64.
Microsoft Windows [Version 10.0.22621.674]
(c) Microsoft Corporation. All rights reserved.
C:\Users\donhu>python
Python 3.11.0 (main, Oct 24 2022, 18:26:4... | For PyCharm, take a look at https://www.jetbrains.com/help/pycharm/managing-dependencies.html#populate_dependency_files
After you've set it up, you can click Install requirement.
Open a project with the requirements file specified, a notification bar is displayed on top of any Python or requirements file opened in Edi... | https://stackoverflow.com/questions/74322227/ |
Pytorch newbie, non linear regression not converging | First im new to pytorh and DL, I want to create a simple non linear regression model, but apparently is not converging, i tried to change some hyperparams without sucess. This is the code, i guess im making wrong something obvius.
import torch
x1 = torch.arange(1,600,1, dtype=torch.float32).view(-1,1)
... | Possible solutions:
input normalization
batch normalization
decrease learning rate
change MSELoss to L1Loss (more stable with large errors)
change optimizer, e.g. use Adam
etc
An example:
import torch
x1 = torch.arange(1,600, 1, dtype=torch.float32).view(-1, 1)
y1 = x1*x1
model = torch.nn.Sequential(
torch.nn.B... | https://stackoverflow.com/questions/74338863/ |
How to free GPU memory in Pytorch CUDA | I am using Colab and Pytorch CUDA for my deep learning project and faced the problem of not being able to free up the GPU. I have read some related posts here but they did not work with my problem. Please guide me on how to free up the GPU memory.
Thank you in advance
| Try this:
torch.cuda.empty_cache()
or this:
with torch.no_grad():
torch.cuda.empty_cache()
| https://stackoverflow.com/questions/74349915/ |
How to convert list of dimension 0 tensors, each attached with gradient, to a dimension 1 tensor with only one gradient? | I'm trying to make some adjustments to some pre-existing code, and can get a list that looks like the following:
[tensor(0.5209, grad_fn=<SqueezeBackward0>), tensor(0.5572, grad_fn=<SqueezeBackward0>), tensor(0.7117, grad_fn=<SqueezeBackward0>), tensor(0.5730, grad_fn=<SqueezeBackward0>), tensor... | Using torch.hstack, you can put all tensors into a large one with one grad_fn.
tensors = [...] # some tensors with grad_fn
torch.hstack(tensors) # grad_fn is CatBackward0
| https://stackoverflow.com/questions/74351376/ |
Gradient is always zero in autograd.grad() | I implemented a custom loss function, which looks like this:
However, the gradient of this function is always zero and I don't understand why.
The code for the objective function:
def objective(p, output):
x,y = p
a = minA
b = minB
r = 0.1
XA = 1/2 -1/2 * torch.tanh(100*((x - a[0])**2 + (y - a[1])**2 - (r +... | Tanh is a bounded function and converges quite quickly to 1. Your XA and XB points are defined as
XA = 1/2 - 1/2 * torch.tanh(100*(z1 + z2 - z0))
XB = 1/2 - 1/2 * torch.tanh(100*(z3 + z4 - z0))
Since z1 + z2 - z0 and z3 + z4 - z0 are rather close to 1, you will end up with an input close to 100. This means the tanh wi... | https://stackoverflow.com/questions/74352495/ |
Expanding a non-singleton dimension in PyTorch, but without copying data in memory? | Say that we have a tensor s of size [a,b,c] that is not necessarily contiguous, and b>>1.
I want to expand (but not copy) it in the second dimension for n times to get a tensor of size [a,nb,c].
The issue is that I cannot find a way to do this without explicitly copying data in memory.
The ways I know to do the o... | I don't think this is possible, and here is a minimal example to illustrate my point.
Consider a torch.Tensor [1, 2, 3], which has size (3,). If we want to expand it without performing a copy, we would create a new view of the tensor. Imagine for example that we want to create a view that contains twice the values of t... | https://stackoverflow.com/questions/74355156/ |
W&B won't finish the process | I'm using pytorch_ligthning and wandb to conduct some experiments. The problem is that training will silently crash before finishing in the following way:
Epoch 997/1000
0.087
Epoch 998/1000
0.080
wandb: Waiting for W&B process to finish... (success).
Epoch 999/1000
0.108
This is how the code looks like:
w... | Engineer from W&B here! The fact that you get this message wandb: Waiting for W&B process to finish... (success). before the actual 1000th epoch, this means there is some error happening there. Are you training on multiple GPUs and could you also share the console log in case there is any
| https://stackoverflow.com/questions/74373442/ |
PyTorch Dataloader for multiple files with sliding window | I am working on a problem where I have multiple CSVs files and I need to read those multiple CSVs one by one with a sliding window. Let’s assume that, one CSV file is having 330 data points and the window size is 32 so we should be having (10*32 = 320) and the last 10 points will be discarded.
I started making a datase... | I propose the following workaround. According to this, the getitem function retrieves a specific window which belongs to a csv file and not the file itself. Towards this direction, find_num_of_windows computes the number of windows occur for a given csv file. The len(self) function will return the sum of the windows of... | https://stackoverflow.com/questions/74375033/ |
PyTorch different between ones_tensor = torch.ones((2, 3,)) and ones_tensor = torch.ones(2, 3)? | In PyTorch, what is different between
ones_tensor = torch.ones((2, 3,))
and
ones_tensor = torch.ones(2, 3)
?
| There's no difference between the two. As stated in the documentation,
size (int...) – a sequence of integers defining the shape of the output tensor. Can be a variable number of arguments or a collection like a list or tuple.
If you test it, they both produce the same tensor with the same shape.
tensor([[1., 1., 1.]... | https://stackoverflow.com/questions/74377393/ |
how does one fix when torch can't find cuda, error: version libcublasLt.so.11 not defined in file libcublasLt.so.11 with link time reference? | I get this error with a pytorch import python -c "import torch":
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/afs/cs.stanford.edu/u/brando9/ultimate-utils/ultimate-utils-proj-src/uutils/__init__.py", line 13, in <module>
import to... | I don't know why this works but this worked for me:
source cuda11.1
# To see Cuda version in use
nvcc -V
pip3 install torch==1.9.1+cu111 torchvision==0.10.1+cu111 torchaudio==0.9.1 -f https://download.pytorch.org/whl/torch_stable.html
but if you look through the git issue these might also work:
conda install -y -c pyt... | https://stackoverflow.com/questions/74394695/ |
Pytorch inverse FFT (ifft) with amplitude and phase | To use the amplitude and phase, I use the below function to extract:
def calculate_fft(x):
fft_im = torch.fft.fft(x.clone()) # bx3xhxw
fft_amp = fft_im.real**2 + fft_im.imag**2
fft_amp = torch.sqrt(fft_amp)
fft_pha = torch.atan2(fft_im.imag, fft_im.real)
return fft_amp, fft_pha
After I modifying t... | def inverse_fft(fft_amp, fft_pha):
imag = fft_amp * torch.sin(fft_pha)
real = fft_amp * torch.cos(fft_pha)
fft_y = torch.complex(real, imag)
y = torch.fft.ifft(fft_y)
return y
This may work.
| https://stackoverflow.com/questions/74398041/ |
Convolutional layer: does the filter convolves also trough the nlayers_in or it take all the dimensions? | In the leading DeepLearning libraries, does the filter (aka kernel or weight) in the convolutional layer convolves also across the "channel" dimension or does it take all the channels at once?
To make an example, if the input dimension is (60,60,10) (where the last dimension is often referred as "channel... | It should be (5, 5, 10, 5). Conv2d operation is just like Linear if you ignore the spatial dimensions.
From TensorFlow documentation [link]:
Given an input tensor of shape batch_shape + [in_height, in_width, in_channels] and a filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels], th... | https://stackoverflow.com/questions/74415536/ |
optimizer got an empty parameter list while using adam | I was creating conv nets for cifar100 and code is give below but I have encounted the error mentioned in the title while initializing optimizer.
Code for model
class CNN(nn.Module):
def __init__(self,k):
super(CNN,self).__init__()
#Convolutional layer
conv1=nn.Conv2d(3,32,kernel_size=3,padding='same')
... | Your submodules must be registered as attributes of your parent nn.Module:
class CNN(nn.Module):
def __init__(self,k):
super(CNN,self).__init__()
# convolutional layer
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding='same')
self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding='... | https://stackoverflow.com/questions/74422830/ |
Cannot run the following code in Python terminal | From the following page (https://github.com/Babelscape/rebel/blob/main/setup.sh) I got the following code.
#!/bin/bash
# setup conda
source ~/miniconda3/etc/profile.d/conda.sh
# create conda env
read -rp "Enter environment name: " env_name
read -rp "Enter python version (e.g. 3.7) " python_version... | This is a Bash script. You only can run it in a Bash Shell.
| https://stackoverflow.com/questions/74430138/ |
Is it safe to do a ToTensor() data transform before a ColorJitter and RandomHorizotnalFlip and other data augmentation techniques in PyTorch? | I am seeing that the ToTensor is always at the end https://github.com/pytorch/examples/blob/main/imagenet/main.py:
train_dataset = datasets.ImageFolder(
traindir,
transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
... | One reason why people usually use PIL format instead of tensor to perform image preprocessing is related to the resizing algorithms and especially downsizing. As pointed out in this paper,
The Lanczos, bicubic, and bilinear implementations by PIL (top row) adjust the antialiasing filter width by the downsampling facto... | https://stackoverflow.com/questions/74451955/ |
The saved information in the .json file of the torch profiler | I have profiled my model using the torch profiler:
from torch.profiler import profile, record_function, ProfilerActivity
import torch
with profile(activities=[
ProfilerActivity.CPU, ProfilerActivity.CUDA], record_shapes=True) as prof:
with record_function("model_inference"):
model(input)
profi... | You can open the json with chrome. Maybe this will help you to understand the data.
From the documentation:
The checkpoint can be later loaded and inspected under chrome://tracing URL.
| https://stackoverflow.com/questions/74453433/ |
FileNotFoundError: scipy.libs | I'm trying to build an exe file using cx_Freeze.
but when I run the resulting file I get an error:
FileNotFoundError: ..\build\exe.win-amd64-3.8\lib\scipy.libs
please tell me how to fix this problem?
I run the following code:
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["t... | I had this exact problem, this is only a short term fix but if you search for 'scipy.libs' in your python install location 'site-packages' folder (or virtual environment if you're using one) and copy/paste it into the libs folder in your build it should solve the issue.
I'll edit my answer if I come across the root cau... | https://stackoverflow.com/questions/74454338/ |
TypeError: __init__() got multiple values for argument 'dim' | I am doing testing on two trained models. In first, I am getting below error during testing so I have changed torch.logsoftmax class to nn.LogSoftmax.
Code
from torch.utils.data import Dataset, DataLoader
import pandas as pd
from torchvision import transforms
from PIL import Image
import torch
import torch.nn as nn
fro... | nn.LogSoftMax is a module that has to be instantiated first and then called (which is when its forward method is executed). Try this instead:
entropy1 = -torch.sum(torch.softmax(pred1[:, :10], dim=1) * nn.LogSoftmax(dim=1)(pred1[:, :10]), dim=-1, keepdim=True)
Instead, you can also use the functional form of this modu... | https://stackoverflow.com/questions/74469400/ |
How to train real-time LSTM with input and output of varying length? | I have the data of banner clicks by minute.
I have the following data: hour, minute, and was the banner clicked by someone in that minute. There are some other features (I omitted them in the example dataframe). I need to predict will be any clicks on banner for all following minutes of this hour.
For example I have da... | An RNN (or LSTM) will return an output for every input, as well as the final hidden state (and cell state for LSTM). So one possible solution: Pad your input of future minutes with with a different token and use an embedding layer with 3 embeddings (0, 1, 2 where 2 represents unseen value). For example, at timestep 3 t... | https://stackoverflow.com/questions/74482446/ |
Cannot load Pytorch model in Pytorch mobile | I attempt to load a model into an android app using the pytorch mobile flutter plugin which is just a wrapper for the android pytorch package, but when I attempt to load the model I get the following debug statement
E/PyTorchMobile( 8111): assets/models/fullap.pt is not a proper model
E/PyTorchMobile( 8111): com.facebo... | file not found: archive/constants.pkl
Make sure you've set the right path of the model.
| https://stackoverflow.com/questions/74484748/ |
About roboflown's assist function | Annotated in roboflow and trained in YOLOv5(https://github.com/ultralytics/yolov5).
I annotated the model in roboflow and trained it in YOLOv5.
After that, I want to do label assist using the custom model I learned, but I can't do it. What should I do?
| Use the dataset version you generated to train in YOLOv5 to use Roboflow Train: https://docs.roboflow.com/train - once your Training Job is complete, you’ll have access to Model-Assisted Labeling (Label Assist): https://docs.roboflow.com/annotate/model-assisted-labeling
Your workspace comes with 3 free Roboflow Train c... | https://stackoverflow.com/questions/74498428/ |
Object Detection with YOLOV7 on custom dataset | I am trying to predict bounding boxes on a custom dataset using transfer learning on yolov7 pretrained model.
My dataset contains 34 scenes for training, 2 validation scenes and 5 test scenes. Nothing much happens on the scene, just the camera moves 60-70 degree around the objects on a table/flat surface and scales/til... | I would suggest you thoroughly review your dataset, to start.
Check the class distributions.
How many classes do you have, and what are the counts of the objects of these classes in the training set?
What are the counts in the validation set? Are the ratios approximately similar or different?
Is any class lacking exa... | https://stackoverflow.com/questions/74507437/ |
How to stop a layer updating in pytorch? | class DR(nn.Module):
def __init__(self, orginal, latent_dims):
super(DR, self).__init__()
self.latent_dims=latent_dims
self.linear1 = nn.Linear(orginal, 1000)
self.linear2 = nn.Linear(1000, 2000)
self.linear3 = nn.Linear(2000, latent_dims)
def forward(self, x):... | What appears like an underused feature of PyTorch is that the requires_grad, which is meant to disable inference caching for gradient computation can be called on torch.Tensor (as an in place and out of place operation) but also on nn.Module (in place).
In your case, you can simply write in two lines:
model.linear1.req... | https://stackoverflow.com/questions/74513017/ |
ValueError: Using a target size (torch.Size([16])) that is different to the input size (torch.Size([13456, 1])) is deprecated | My code: https://colab.research.google.com/drive/1qjfy2OsHYewhHDej-W83CMNercB7o7r8?usp=sharing
the error: ValueError: Using a target size (torch.Size([16])) that is different to the input size (torch.Size([13456, 1])) is deprecated. Please ensure they have the same size.
the dataset consists of 2 folders: 0 and 1, and ... | The original code is intended for 64 x 64 images, not 512 x 512 ones. To fix the problem, you have to either downsize the images to 64 x 64 or modify the discriminator and the generator.
| https://stackoverflow.com/questions/74513451/ |
Extracting features from a pretrained model using hook function | I want to extract features from some of the layers from a pretrained model. For this aim, I am using thi pretrained model from here. I removed some of the final layers and for loading the pretrained weights, I use strict=False.
The architecture of the model is as follows:
Net(
(blocks): ModuleList(
(0): ResNetBas... | Looking at the link you provided, the function create_r2plus1d() returns the following
return Net(blocks=nn.ModuleList(blocks))
Your object self.r2plus1d is already a Net instance, so your line
self.r2plus1d.Net.blocks[1].register_forward_hook(get_activation('ResBlock1'))
is basically like calling Net twice.
You pro... | https://stackoverflow.com/questions/74535731/ |
How to use AWS Sagemaker with newer version of Huggingface Estimator? | When trying to use Huggingface estimator on sagemaker, Run training on Amazon SageMaker e.g.
# create the Estimator
huggingface_estimator = HuggingFace(
entry_point='train.py',
source_dir='./scripts',
instance_type='ml.p3.2xlarge',
instance_count=1,
role=role,
transformer... | You can use the Pytorch estimator and in your source directory place a requirements.txt with Transformers added to it. This will ensure 2 things
You can use higher version of pytorch 1.12 (current) compared to 1.10.2 in the huggingface estimator.
Install new version of HuggingFace Transformers library.
To achieve thi... | https://stackoverflow.com/questions/74548143/ |
Using a target size (torch.Size([80670, 1])) that is different to the input size (torch.Size([80670])) | I want to implement GCN with my own dataset (from Pytorch geometric tutorial). I copied my notebook below.
It is working when I use the original implementation, However, if I want to use custom data then it gives the below error:
My notebook
Original implementation
I used Load CSV from pyG and tried to incorporate it i... | You can use edge_label = edge_label.squeeze()
it will remove the extra dimension
| https://stackoverflow.com/questions/74550503/ |
What is Pytorch equivalent of Pandas groupby.apply(list)? | I have the following pytorch tensor long_format:
tensor([[ 1., 1.],
[ 1., 2.],
[ 1., 3.],
[ 1., 4.],
[ 0., 5.],
[ 0., 6.],
[ 0., 7.],
[ 1., 8.],
[ 0., 9.],
[ 0., 10.]])
I would like to groupby the first column and store the 2nd column as ... | You can use this code:
import torch
x = torch.tensor([[ 1., 1.],
[ 1., 2.],
[ 1., 3.],
[ 1., 4.],
[ 0., 5.],
[ 0., 6.],
[ 0., 7.],
[ 1., 8.],
[ 0., 9.],
[ 0., 10.]])
result = [x[x[:,0]==i][:,1] for i in x[:,0].unique()]
output
[tensor([... | https://stackoverflow.com/questions/74564843/ |
Why are Pytorch transform functions not being differentiated with autograd? | I have been trying to write a set of transforms on input data. I also need the transforms to be differentiable to compute the gradients. However, gradients do not seem to be calculated for the resize, normalize transforms.
from torchvision import transforms
from torchvision.transforms import ToTensor
resize = transfo... | Trying to reproduce your error, what I get when backpropagating the gradient from normalized is:
RuntimeError: grad can be implicitly created only for scalar outputs
What this error means is that the tensor you are calling backward onto should be a scalar and not a vector or multi-dimensional tensor. Generally you wo... | https://stackoverflow.com/questions/74577705/ |
Why PyTorch BatchNorm1D gives "batch_norm" not implemented for 'Long'" error while normalizing Integer type tensor? | I am trying to learn some functions in Pytorch framework and was stuck due to below error while normalizing a simple integer tensor. Could someone please help me with this.
Here is the sample code to reproduce the error -
import torch
import torch.nn as nn
#Integer type tensor
test_int_input = torch.randint(size = [3,... | Your input tensor should be a floating point:
>>> batchnorm1D(test_int_input.float())
tensor([[-5.9605e-08, -1.3887e+00, -9.8058e-01, 2.6726e-01, 1.4142e+00],
[-1.2247e+00, 4.6291e-01, 1.3728e+00, -1.3363e+00, -7.0711e-01],
[ 1.2247e+00, 9.2582e-01, -3.9223e-01, 1.0690e+00, -7.0711e-01]],... | https://stackoverflow.com/questions/74598178/ |
Taking mean of all rows in a numpy matrix grouped by values based on another numpy matrix | I have a matrix A of size NXN with float values and another boolean matrix B of size NXN
For every row, I need to find the mean of all values in A belonging to indices where True is the corresponding value for that index in matrix B
Similarly, I need to find the mean of all values in A belonging to indices where False ... | I would say your start is good
true_mat = np.where(B, A, 0)
false_mat = np.where(B, 0, A)
But we want to divide by the number of Trues or Falses, respectively, so...
true_sum = np.sum(B, axis = 1) #sum of Trues per row
false_sum = N-true_sum # if you don't have N given, do N=A.shape[0]
true_mean = np.sum(true... | https://stackoverflow.com/questions/74610101/ |
Is it possible to perform quantization on densenet169 and how? | I have been trying to performing quantization on a densenet model without success. I have been trying to implement pytorch post training static quantization. Pytorch has quantized versions of other models, but does not have for densenet. Is it possible to quantize the densenet architecture.
I have searched for tutorial... | Here's how to do this on DenseNet169 from torchvision:
from torch.ao.quantization import QuantStub, DeQuantStub
from torch import nn
from torchvision.models import densenet169, DenseNet169_Weights
from tqdm import tqdm
from torch.ao.quantization import HistogramObserver, PerChannelMinMaxObserver
import torch
# Wrap ba... | https://stackoverflow.com/questions/74612146/ |
Why when the batch size increased, the epoch time will also increasing? | Epoch time means the time required to train for an epoch.
From my point of view, when the batch size increased, the epoch time will reduce. But actually I observed that when the batch size increased, the epoch time would reduce at first as we expect, but then increase. The relationship between batch size and epoch is l... | As you already noticed, there are many factors that may affect epoch-time/batch-time.
Some of these factors may be specific to your machine's configuration. In order to get an accurate answer, you'll need to have a more detailed breakdown of the running time. One way of doing so would be using a profiler.
Try and be mo... | https://stackoverflow.com/questions/74637151/ |
Why does StableDiffusionPipeline return black images when generating multiple images at once? | I am using the StableDiffusionPipeline from the Hugging Face Diffusers library in Python 3.10.2, on an M2 Mac (I tagged it because this might be the issue). When I try to generate 1 image from 1 prompt, the output looks fine, but when I try to generate multiple images using the same prompt, the images are all either bl... | Apparently it is indeed an Apple Silicon (M1/M2) issue, of which Hugging Face is not yet sure why this is happening, see this GitHub issue for more details.
| https://stackoverflow.com/questions/74642594/ |
Locating tags in a string in PHP (with respect to the string with tags removed) | I want to create a function that labels the location of certain HTML tags (e.g., italics tags) in a string with respect to the locations of characters in a tagless version of the string.
(I intend to use this label data to train a neural network for tag recovery from data that has had the tags stripped out.)
The magic ... | I think I've got something. How about this:
function label_italics($string) {
return preg_replace(['/<i>/', '/<\/i>/', '/[^#]/', '/##0/', '/#0/'],
['#', '#', '0', '2', '1'], $string);
}
see: https://3v4l.org/cKG46
Note that you need to supply the string with the tags in it.
How... | https://stackoverflow.com/questions/74671399/ |
BGR to RGB for CUB_200 images by Image.split() | I am creating a PyTorch dataset and dataloader from CUB_200. When reading the images as pill, I need to change the BGR channels to RGB and I use the following code:
def _read_images_from_list(imagefile_list):
imgs = []
mean=[0.485, 0.456, 0.406]
std= [0.229, 0.224, 0.225]
Transformations = transforms.Comp... | I would strongly recommend you use skimage.io to load your images, not opencv. It opens the images in RGB format by default, removing your shuffling overhead, but if you want to convert BGR to RGB you can use this:
import numpy as np
img = np.arange(27).reshape(3,3,3)
b = img[:,:,0]
g = img[:,:,1]
r = img[:,:,2]
rgb ... | https://stackoverflow.com/questions/74679922/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.