instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
What is the difference between `.zero_grad()` and `.zero_grad`? | I am working on neural network and I find that, with *.grad_zero() I get loss function values properly and also converge to zero. Where, with *.grad_zero (with out bracket) gives loss function values in 5 digits. (13,564.23). So, what is the difference between them? Why "()" important in FPP. Thank you.
| optimizer.zero_grad is a function, so you need to call it with parentheses. If you don't use the parentheses, you are just referencing the function object but never calling it.
| https://stackoverflow.com/questions/63455304/ |
Proper Usage of PyTorch's non_blocking=True for Data Prefetching | I am looking into prefetching data into the GPU from the CPU when the model is being trained on the GPU. Overlapping CPU-to-GPU data transfer with GPU model training appears to require both
Transferring data to GPU using data = data.cuda(non_blocking=True)
Pin data to CPU memory using train_loader = DataLoader(..., pi... | I think where you are off is that output = model(images) is a synchronization point. It seems the computation is handled by a different part of a GPU. Quote from official PyTorch docs:
Also, once you pin a tensor or storage, you can use asynchronous GPU
copies. Just pass an additional non_blocking=True argument to a
t... | https://stackoverflow.com/questions/63460538/ |
What is the right calculation of epoch loss in training? | I am reading Pytorch official tutorial for fine tuning and I am faced with one problem and that is calculation of loss in each epoch.
Before this , I calculate loss for batch of data, accumulate these batch losses and find mean of these values as loss of epoch. But in that example, the calculation is as follow:
for inp... | Yes the code snippet adds multiplication of batch size with batch mean error. If you want to calculate true summation. You can use
torch.nn.CrossEntropyLoss(reduction = "sum")
which will give you the sum of errors for the batch. Then you can directly sum for each batch as follows:
running_loss += loss.item()... | https://stackoverflow.com/questions/63463952/ |
AttributeError: module 'torch.utils' has no attribute 'tensorboard' | I tried to use tensorboard in torch.utils, but it says "module 'torch.utils' has no attribute 'tensorboard'".
My torch version is "1.6.0+cu101"
PS C:\Users\kelekelekle> python
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 01:54:44) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", ... | You have to install tensorboard via:
pip install tensorboard
(or a-like). Given that is done, you should import tensorboard module from torch.utils package:
from torch.utils import tensorboard
tensorboard.SummaryWriter("foo")
Or you can import SummaryWriter directly:
from torch.utils.tensorboard import Sum... | https://stackoverflow.com/questions/63466204/ |
Vectorized way to apply a 3-dimension mask to RGB in pytorch | I have a HxWx3 tensor representing an RGB image and a HxWx3 mask (boolean) tensor as input.
It is assumed that for each (i,j) in the mask tensor there's exactly one true value (that is exactly one of R\G\B is on).
I want to apply the mask to the image to result in a HxW (or HxWx1) tensor V where V[i,j]='the matching R\... | Assuming that for each i,j only a single R/G/B value is retained, you can simply do:
(X*mask).sum(axis=2)
This should give you your desired (HxW) output.
| https://stackoverflow.com/questions/63467616/ |
TypeError: reshape(): argument 'input' (position 1) must be Tensor, not numpy.ndarray | I am a high school student who doesn't having much experience in using PyTorch and LIME. I'm having a lot of trouble with my image shape. Initially my image shape was (3,224,224), however the LIME algorithm only works with images that are in this shape(...,...,3). As a result, I tried transposing the image earlier. It ... | use this command to convert numpy.ndarray to tensor
img = torch.from_numpy(img).float() #use appropriate name of variable
| https://stackoverflow.com/questions/63473971/ |
How can torchaudio.transform.Resample be called without __call__ function inside? | if sample_rate != sr:
waveform = torchaudio.transforms.Resample(sample_rate, sr)(waveform)
sample_rate = sr
I was wondering how this Resamle works in there. So took a look at the docs of torchaudio. I thought there would be __call__ function. Because Resample is used as a function. I mean that Resample... | Here's simple similar demonstrates of how forward function works in PyTorch.
Check this:
from typing import Callable, Any
class parent:
def _unimplemented_forward(self, *input):
raise NotImplementedError
def _call_impl(self, *args):
# original nn.Module _call_impl function contains lot more co... | https://stackoverflow.com/questions/63480624/ |
Export pytorch model parameters into separate files according to layer hierarchy | Is it possible to export the trained parameters of a Pytorch model into separate binary files (float32/64, not text) under a folder hierarchy reflecting the layers defined by the model's architecture?
I wish to examine a sizeable pretrained model without the framework overhead and also split the checkpoint into managea... | There is no direct way to do this, but it should take only a few lines of code. For example, consider I have a model of the following structure:
class ConvBlock(nn.Module):
def __init__(self, C_in, C_out, kernel, pool):
super().__init__()
self.conv = nn.Conv2d(C_in, C_out, kernel)
self.relu ... | https://stackoverflow.com/questions/63490419/ |
Index tensor must have the same number of dimensions as input tensor error encountered when using torch.gather() | I'm very new to PyTorch, and I have encountered the "Index tensor must have the same number of dimensions as input tensor" error when running my neural network. It happens with I call an instance of torch.gather(). Could someone help me understand torch.gather() and explain the cause of this error?
Here is th... | Torch.gather is described here. If we take your code, this line
torch.gather(qval, 3, action.view(-1,1,1,1))
is equivalent to
act_view = action.view(10,1,1,1)
out = torch.zeros_like(act_view)
for i in range(10):
for j in range(1):
for k in range(1):
for p in range(1):
out[... | https://stackoverflow.com/questions/63493193/ |
GPU support for TensorFlow & PyTorch | Okay, so I've worked on a bunch of Deep Learning projects and internships now and I've never had to do heavy training. But lately I've been thinking of doing some Transfer Learning for which I'll need to run my code on a GPU. Now I have a system with Windows 10 and a dedicated NVIDIA GeForce 940M GPU. I've been doing a... | First of all unfortunately 940M is a kinda weak GPU for training. I suggest you use Google colab for faster training but of course, it would be faster than the CPU. So here my answers to your four questions.
1-) Yes if you install the requirements correctly, then you can run on GPU. You can manually place your data to ... | https://stackoverflow.com/questions/63499994/ |
Getting the weight of a Layer | I've been working on the MNIST data set using PyTorch and I am having trouble in accessing the weights and biases that is generated in my code.
This is my code
from torch import nn
import torch.nn.functional as F
class Neural(nn.Module):
def __init__(self):
super().__init__()
self.hidden1 = nn... | You should access weights of a layer via its name, so it will be
print (model.hidden1.weight, model.hidden1.bias)
| https://stackoverflow.com/questions/63510021/ |
The result is not fixed after setting random seed in pytorch | def setup_seed(seed):
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed) # cpu
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = True
I set random seed when run the code, but I can not get fixed result with pytorch. Be... | I think the line torch.backends.cudnn.benchmark = True causing the problem. It enables the cudnn auto-tuner to find the best algorithm to use. For example, convolution can be implemented using one of these algorithms:
CUDNN_CONVOLUTION_FWD_ALGO_GEMM,
CUDNN_CONVOLUTION_FWD_ALGO_FFT,
CUDNN_CONVOLUTION_FWD_... | https://stackoverflow.com/questions/63515991/ |
torch transform.resize() vs cv2.resize() | The CNN model takes an image tensor of size (112x112) as input and gives (1x512) size tensor as output.
Using Opencv function cv2.resize() or using Transform.resize in pytorch to resize the input to (112x112) gives different outputs.
What's the reason for this? (I understand that the difference in the underlying imple... | Basically torchvision.transforms.Resize() uses PIL.Image.BILINEAR interpolation by default.
While in your code you simply use cv2.resize which doesn't use any interpolation.
For example
import cv2
from PIL import Image
import numpy as np
a = cv2.imread('videos/example.jpg')
b = cv2.resize(a, (112, 112))
c = np.array(I... | https://stackoverflow.com/questions/63519965/ |
Is this a right way to descrease size of my docker images? | I am running a deep learning model in Docker container which needs pytorch and Azure ML service.
AML requirement is Ubuntu 18.04 (which by default has only python3.6 and only way to install python3.7+ is from the source from what i was able to find)
transformers in pytorch have a requirement of python 3.7+
and i need p... | Installing runtime dependencies via CMD is not a typical way to reduce Docker image size. As the OP noted, this imposes a cost in container startup.
There are a few changes that can be made to the Dockerfile to reduce image size.
Use a base image that has miniconda installed but not cuda/cudnn. The OP installs pytorch... | https://stackoverflow.com/questions/63521958/ |
Understanding Memory Usage by PyTorch DataLoader Workers | When running a PyTorch training program with num_workers=32 for DataLoader, htop shows 33 python process each with 32 GB of VIRT and 15 GB of RES.
Does this mean that the PyTorch training is using 33 processes X 15 GB = 495 GB of memory? htop shows only about 50 GB of RAM and 20 GB of swap is being used on the entire ... |
Does this mean that the PyTorch training is using 33 processes X 15 GB = 495 GB of memory?
Not necessary. You have a worker process (with several subprocesses - workers) and the CPU has several cores. One worker usually loads one batch. The next batch can already be loaded and ready to go by the time the main process... | https://stackoverflow.com/questions/63522955/ |
How to get the file name of image that I put into Dataloader in Pytorch | I use pytorch to load images like this:
inf_data = InfDataloader(img_folder=args.imgs_folder, target_size=args.img_size)
inf_dataloader = DataLoader(inf_data, batch_size=1, shuffle=True, num_workers=2)
And then:
with torch.no_grad():
for batch_idx, (img_np, img_tor) in enumerate(inf_dataloader, start=1):
... | The DataLoader basically can not get the name of the file. But in Dataset, which is the InfDataloader in the question mentioned above, you can get the name of file from the tensor.
class InfDataloader(Dataset):
"""
Dataloader for Inference.
"""
def __init__(self, img_folder... | https://stackoverflow.com/questions/63529916/ |
Pytorch: Lower the parameters in U-net model | can anyone give me some tips on how i would be able to lower the amount of parameters in the following U-net implementation. I'm having trouble with over-fitting on my training data and i would like to lower the parameters in order to see if it improves the validation data accuracy.
Layers:
First2D
layers = [
n... | One way to decrease the number of parameters is to decrease the number of channels in the convolution. You wouldn't be able to change the number of model input and output channels, because they depend on the data, but you can change the number of intermediate channels.
Remember that the output of one layer is the input... | https://stackoverflow.com/questions/63531538/ |
Unexpected Standard exception from MEX file (pytorch model forward) | When I call mex api from Matlab, I got an unexpected standard exception.
I exported 2 pytorch DNN models to 'A.pt' and 'B.pt' files.
And I implemented c++ functions that load models from the '.pt 'files and run models (forward).
The c++ implementation works fine, I can get proper results from the models.
I built the lo... | From Mr. Cris Luengo's comments, I solved this problem by copying all libtorch dlls into Matlab's own bin folder. There are several duplicated files but I overwrote them. I'm not sure it is safe or not, so may be backup of previous dlls is good choice. Thank you Mr. Cris Luengo.
| https://stackoverflow.com/questions/63533029/ |
KeyError when enumerating over dataloader - why? | I am writing a binary classification model that consists of audio files of 40 participants and classifies them according to whether they have a speech disorder or not. The audio files have been divided into 5 second segments and to avoid subject bias, I have split the training/testing/validation sets such that a subjec... | As @Abhik-Banerjee commented nicely, resetting the index of the dataframes before using them in the data loader did the trick for me:
train, val = train.reset_index(drop=True), val.reset_index(drop=True)
See https://discuss.pytorch.org/t/keyerror-when-enumerating-over-dataloader/54210/20 for a very helpful discussion ... | https://stackoverflow.com/questions/63545434/ |
rllib - obtain TensorFlow or PyTorch model output from checkpoint | I'd like to use the rllib trained policy model in a different code where I need to track which action is generated for specific input states. Using a standard TensorFlow or PyTorch (preferred) network model would provide that flexibility but I can't find clear documentation on how to produce a usable dat or H5 file fro... | The easiest way to get the weights from a checkpoint is to load it again with rllib and then save it with the Tensorflow/Pytorch commands.
If you have a keras TF model you can simply call:
model.save('my_model.h5') # creates a HDF5 file
| https://stackoverflow.com/questions/63548115/ |
Pytorch inference CUDA out of memory when multiprocessing | To fully utilize CPU/GPU I run several processes that do DNN inference (feed forward) on separate datasets. Since the processes allocate CUDA memory during the feed forward I'm getting a CUDA out of memory error. To mitigate this I added torch.cuda.empty_cache() call which made things better. However, there are still o... | From my experience of parallel training and inference, it is almost impossible to squeeze the last bit of the GPU memory. Probably the best you can do is to estimate the maximum number of processes that can run in parallel, then restrict your code to run up to that many processes at the same time. Using semaphore is th... | https://stackoverflow.com/questions/63549736/ |
How to compute the uncertainty of a Monte Carlo Dropout neural network with PyTorch? | I am trying to implement Bayesian CNN using Mc Dropout on Pytorch, the main idea is that by applying dropout at test time and running over many forward passes, you get predictions from a variety of different models. I need to obtain the uncertainty, does anyone have an idea of how I can do it Please
This is how I defin... | You can compute the statistics, such as the sample mean or the sample variance, of different stochastic forward passes at test time (i.e. with the test or validation data), when the dropout is enabled. These statistics can be used to represent uncertainty. For example, you can compute the entropy, which is a measure of... | https://stackoverflow.com/questions/63551362/ |
How do I limit using one CPU per python processes launched via gnu parallel? | If I run this script
$ seq 1 4 | taskset -c 0-3 parallel -j4 -u <my_bash_script.sh>
Then each python process contained in the <my_bash_script.sh> runs on multiple cpus instead of one. The python function use both numpy and pytorch. So the option taskset -c 0-4 impose the max number of CPUs but it doesn't g... | Use jobslot:
$ seq 1 4 | parallel -j4 -u taskset -c {%} <my_bash_script.sh>
Jobslot is built for this: Imagine you have a lot more than 4 jobs. If you then give every 4th job to cpu 4, then you risk that every 4th job is shorter than the others. In which case cpu 4 will be idling even if there are more jobs to b... | https://stackoverflow.com/questions/63551993/ |
How do I install **Pytorch** with conda? Is anaconda.org down temporarily? | I just installed Anaconda and now I'm trying to install pytorch via conda install pytorch torchvision cudatoolkit=10.2 -c pytorch. But I'm getting the error message
Collecting package metadata (current_repodata.json): failed
CondaHTTPError: HTTP 503 SERVICE UNAVAILABLE: BACK-END SERVER IS AT CAPACITY for url <https... | The answer to your problem is in your question itself . The last paragraph says that :
A 500-type error (e.g. 500, 501, 502, 503, etc.) indicates the server failed to
fulfill a valid request. The problem may be spurious, and will resolve itself if you
try your request again. If the problem persists, consider notifyin... | https://stackoverflow.com/questions/63559006/ |
Does the loss of a model reflect its accuracy? | So these are my loss per 75 epochs:
Epoch: 75, loss: 47382825795584.000000
Epoch: 150, loss: 47382825795584.000000
Epoch: 225, loss: 47382825795584.000000
Epoch: 300, loss: 47382825795584.000000
Epoch: 375, loss: 47382825795584.000000
Epoch: 450, loss: 47382825795584.000000
Epoch: 525, loss: 47382825795584.000000
Epoch... | Loss is only meaningful relatively (i.e. for comparison). Multiply your loss function by 10 and your loss is 10 times bigger on the same model. This doesn't tell you anything.
But using the same loss function, if model_1 gives a loss 10x smaller than model_2, then chances are model_1 will have better accuracy (although... | https://stackoverflow.com/questions/63559314/ |
AzureML SDK not working with PyTorch 1.5? | Has anyone got PyTorch 1.5 to work with the AzureML SDK (versions 1.11 and 1.12)? torch.cuda.is_available() returns False even on GPU-enabled machines. Exactly the same setup works fine (is_available() is True) with PyTorch 1.3, 1.4 and 1.6. Any pointers welcome. These are the (possibly) relevant parts of my Conda envi... | This is a known issue with PyTorch 1.5 and CUDA and is acknowledged by PyTorch in this GitHub issue.
They haven't provided an official solution to the issue, but they recommend either updating old GPU-drivers or making sure you have a CPU-enabled version of PyTorch installed. Since you're not experiencing this problem ... | https://stackoverflow.com/questions/63564551/ |
CNN + RNN architecture for video recognition | I am trying to replicate the ConvNet + LSTM approach presented in this paper using pytorch. But I am struggling to find the correct way to combine the CNN and the LSTM in my model. Here is my attempt :
class VideoRNN(nn.Module):
def __init__(self, hidden_size, n_classes):
super(VideoRNN, self).__init__()
sel... | I finally found the solution to make it works. Here is a simplified yet complete example of how I managed to create a VideoRNN able to use packedSequence as an input :
class VideoRNN(nn.Module):
def __init__(self, n_classes, batch_size, device):
super(VideoRNN, self).__init__()
self.batch = bat... | https://stackoverflow.com/questions/63567352/ |
I am getting a ValueError: All bounding boxes should have positive height and width | Hey I am getting the error
ValueError: All bounding boxes should have positive height and width. Found invaid box [264.0, 632.0, 264.0, 633.3333740234375] for target at index 2.
Epoch 1/1
Mini-batch: 1/1220 Loss: 0.1509
Mini-batch: 101/1220 Loss: 0.1201
Mini-batch: 201/1220 Loss: 0.1103
Mini-batch: 301/1220 Loss: 0.109... | This is happening because of resize transform applied in fasterRCNN in detection module. If you are explicitly applying a resize operation, the bounding box generated coordinates will change as per the resize definition but if you haven't applied a resize transform and your image min and max size is outsider (800,1333)... | https://stackoverflow.com/questions/63572304/ |
path problem : NameError: name '__file__' is not defined | import os.path as osp
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.datasets import MNISTSuperpixels
import torch_geometric.transforms as T
from torch_geometric.data import DataLoader
from torch_geometric.utils import normalized_cut
from torch_geometric.nn import (NNConv, gracl... | In notebook, you need to use double quoted "__file__" as in osp.realpath("__file__") instead of osp.realpath(__file__)
Sourced from: https://queirozf.com/entries/python-working-with-paths-the-filesystem#-nameerror-name-'file'-is-not-defined
| https://stackoverflow.com/questions/63583062/ |
how to implement ResNet50 in PyTorch? | I learn NN in Coursera course, by deeplearning.ai and for one of my homework was an assignment for ResNet50 implementation by using Keras, but I see Keras is too high-level language) and decided to implement it in the more sophisticated library - PyTorch. I recorded it, but something went wrong. May someone, please, sa... | Your class does not have any parameters, so .parameters() will give you an empty list.
You have to actually create the individual layers and store them in variables.
Right now all you do is call
X = torch.nn.Conv2d(in_channels=X.shape[0], out_channels=F1, kernel_size=1, stride=1, padding=0)(X)
Which creates an tempora... | https://stackoverflow.com/questions/63591609/ |
Artifacts in StyleGAN generated images | I've written my own implementation of StyleGAN (paper here https://arxiv.org/abs/1812.04948), using PyTorch instead of Tensorflow, which is what the official implementation uses. I'm doing this partly as an exercise in implementing a scientific paper from scratch.
I have done my best to reproduce all the features menti... | I've been working with StyleGAN for a while and I couldn't guess the reason with such little information..
One possible reason is the effect of the truncation trick, this makes the results to represent an average face but with higher quality or deviate it to obtain results variability but with possibility of added arte... | https://stackoverflow.com/questions/63594267/ |
Cannot import torch module | I cannot seem to properly install pytorch on my computer, so here is the background of what I have done:
I had already installed python on my computer and it worked. I used it in Eclipse, using pyDev, so I don't know if that could be the problem. Now I want to install pytorch, so I installed anaconda and entered the co... | Open command prompt or terminal and type:
pip3 install pytorch
If it says pip isn't installed then type: python -m pip install -U pip
Then retry importing Pytorch module
| https://stackoverflow.com/questions/63600423/ |
What is the goal of Variable using pytorch? | I have this code :
from torch.autograd import Variable
d_real_data = Variable(d_sampler(d_input_size))
But I wonder what is the difference between Variable(d_sampler(d_input_size)) and d_sampler(d_input_size)
I think it is two tensors but the values are different. So I was wondering what is the goal of this function V... | Variable() was a way to to use autograd with tensors. This is now deprecated and should not be used anymore. Tensors now work fine with autograd if the requires_grad flag is set to true.
From the official docs
The Variable API has been deprecated: Variables are no longer
necessary to use autograd with tensors. Autogr... | https://stackoverflow.com/questions/63612498/ |
How to calculate the median of a masked tensor along an axis? | I have tensor X of floats of dimensions n x m and a tensor Y of booleans of dimensions n x m. I want to calculate values such as the mean, median and max of X, along one of the axes, but only considering the values in X which are true in Y. Something like X[Y].mean(dim=1). This is not possible because X[Y] is always a ... | This is the best I have so far on this:
outs = []
for x, y in zip(X, Y): # X, Y could be permuted to loop over desired axis
out = torch.median(torch.masked_select(x, y))
outs.append(out)
torch.tensor(outs)
Would really appreciate if someone has better solution.
| https://stackoverflow.com/questions/63621694/ |
pytorch: How do I properly initialize Tensor without any entries? | What I am doing right now is this:
In [1]: torch.Tensor([[[] for _ in range(3)] for _ in range(5)])
Out[1]: tensor([], size=(5, 3, 0))
This works fine for me, but is there maybe a torch function that does this that I am missing?
Thanks in advance!
Edit:
My use case is this:
I use this to aggregate... | This can be another way depending on your usecase.
alpha = torch.tensor([])
In[5]: alpha[:,None,None,None]
Out[5]: tensor([], size=(0, 1, 1, 1))
Otherways:
torch.tensor([[[[]]]]) #tensor([], size=(1, 1, 1, 0))
torch.tensor([[[[],[]]]]) #tensor([], size=(1, 1, 2, 0))
| https://stackoverflow.com/questions/63622972/ |
Error in training opennmt - caffe2_detectron_ops.dll not found | I have torch 1.6 and python 3.8. When training OpenNMT, it throws the following error -
OSError: [WinError 126] The specified module could not be found. Error loading "C:\Users\Girish\AppData\Local\Programs\Python\Python38\lib\sitepackages\torch\lib\caffe2_detectron_ops.dll" or one of its dependencies.
I chec... | https://github.com/pytorch/pytorch/issues/35803#issuecomment-725285085
This answer worked for me.
Just deleting "caffe2_detectron_ops.dll" from the path ("C:\Users\Girish\AppData\Local\Programs\Python\Python38\lib\sitepackages\torch\lib\caffe2_detectron_ops.dll")
| https://stackoverflow.com/questions/63629075/ |
Loading a converted pytorch model in huggingface transformers properly | I converted a pre-trained tf model to pytorch using the following function.
def convert_tf_checkpoint_to_pytorch(*, tf_checkpoint_path, albert_config_file, pytorch_dump_path):
# Initialise PyTorch model
config = AlbertConfig.from_json_file(albert_config_file)
print("Building PyTorch model from configur... | I think you could try using
model = AlbertModel.from_pretrained
instead of
model = TFAlbertModel.from_pretrained
in the VectorizeSentence definition.
AlbertModel is the name of the class for the pytorch format model, and TFAlbertModel is the name of the class for the tensorflow format model.
I'm not sure exactly what... | https://stackoverflow.com/questions/63648380/ |
Why is the implementation of cross entropy different in Pytorch and Tensorflow? | I am going through the documentation of Cross Entropy in Pytorch and Tensorflow. I understand that they are modifying the naive implementation of Cross Entropy to solve for the potential numeric over/underflows. However, I am unable to understand as to how these modifications are helping at all.
The implementation of C... | Answering here by combining answers from the comment section for the benefit of the community.
Since you have addressed the issue of numeric overflow in PyTorch, that is handled by subtracting the max value like below(from here).
scalar_t z = std::exp(input_data[d * dim_stride] - max_input);
Coming to TensorFlow's imp... | https://stackoverflow.com/questions/63657247/ |
How To Use The First Layers Of Model In PyTorch | I have uploaded a certain model
from efficientnet_pytorch import EfficientNet
model = EfficientNet.from_pretrained(model)
And I can see the model:
print(model.state_dict())
The model contains quite a few layers, and I want to take only the first 50. Please tell me how I can do this.
| I think this should do the trick:
model = nn.Sequential(*list(model.classifier.children())[:50])
| https://stackoverflow.com/questions/63676050/ |
Pytorch: Mask dilation / extension | I wonder how to extend / dilate binary mask in pytorch? i.e. it should be something like cv2.dilate from opencv.
| For rectangular neighborhoods, dilation is the same as max pooling.
See nn.MaxPool2d for implementation details.
| https://stackoverflow.com/questions/63687067/ |
calculating accuracy for Monte carlo Dropout on pytorch | I have found an implementation of the Monte carlo Dropout on pytorch the main idea of implementing this method is to set the dropout layers of the model to train mode. This allows for different dropout masks to be used during the different various forward passes.
The implementation illustrate how multiple predictions f... | Accuracy is the percentage of correctly classified samples. You can create a boolean array that indicates whether a certain prediction is equal to its corresponding reference value, and you can get the mean of these values to calculate accuracy. I have provided a code example of this below.
import numpy as np
# 2 forw... | https://stackoverflow.com/questions/63691865/ |
Is there a many to many convolution in Pytorch? is this a thing? | I have been thinking about convolutions recently. There are common 3by3 convs, where (3,3) kernel's information is weighted and aggregated to supply information to a single spatial point on the output. There are also 3 by 3 upconvs, where a single spatial point on the input supplies weighted information to a 3 by 3 out... | You can combine pixel shuffle and averaging to get what you want.
for example, if you want 3x3 -> 3x3 mapping with in_channels to out_channels:
from torch import nn
import torch.nn.functional as nnf
class ManyToManyConv2d(nn.Module):
def __init__(in_channels, out_channels, in_kernel, out_kernel):
self.out_ke... | https://stackoverflow.com/questions/63692522/ |
Mesh-R-CNN Data with Colab and Pytorch3D | While using the Mesh-R-CNN demo on Google Colab:
https://github.com/facebookresearch/meshrcnn
on the demo.py file I get this message
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-24-202aa0a6d1de> in <module>()
17
18 # required so that .register() calls... | Since it was colab it was missing the "! cd" on the previous import of MeshRCNN
| https://stackoverflow.com/questions/63697929/ |
How torch.distributed.launch assign data to each GPU? | When our batch size is 1 or 2 and we have 8 GPUs, how torch.distributed.launch assign data to each GPUs? I converted my model to torch.nn.parallel.DistributedDataParallel,
model = DistributedDataParallel(model,
device_ids=[args.local_rank],
output_device=a... | They don't. Unlike Dataparallel, the batch size you set is per-GPU. When you have 8 GPUs with batch size 1, you have an effective batch size of 8.
| https://stackoverflow.com/questions/63720392/ |
PyTorch GPU out of memory | I am running an evaluation script in PyTorch. I have a number of trained models (*.pt files), which I load and move to the GPU, taking in total 270MB of GPU memory. I am using a batch size of 1. For every sample, I load a single image and also move it to the GPU. Then, depending on the sample, I need to run a sequence ... | Try adding torch.cuda.empty_cache() after the del
| https://stackoverflow.com/questions/63725858/ |
Fluctuating loss during training for text binary classification | I'm doing a finetuning of a Longformer on a document text binary classification task using Huggingface Trainer class and I'm monitoring the measures of some checkpoints with Tensorboard.
Even if the F1 score and accuracy is quite high, I have perplexities about the fluctuations of training loss.
I read online a reason ... | I will first tell you the reason for the fluctuations and then a possible way to solve it.
REASON
When you train a network, you calculate a gradient that would reduce the loss. In order to do that, you need to backpropagate the loss. Now, ideally, you compute the loss based on all of the samples in your data because th... | https://stackoverflow.com/questions/63743557/ |
Correct way of normalizing and scaling the MNIST dataset | I've looked everywhere but couldn't quite find what I want. Basically the MNIST dataset has images with pixel values in the range [0, 255]. People say that in general, it is good to do the following:
Scale the data to the [0,1] range.
Normalize the data to have zero mean and unit standard deviation (data - mean) / std... | Euler_Salter
I may have stumbled upon this a little too late, but hopefully I can help a little bit.
Assuming that you are using torchvision.Transform, the following code can be used to normalize the MNIST dataset.
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('./data', train=True
t... | https://stackoverflow.com/questions/63746182/ |
About cosine similarity, how to choose the loss function and the network(I have two plans) | Sorry I have no clue, I don't know where to find a solution.
I'm using two networks to construct two embeddingsοΌI have binary target to indicate whether embeddingA and embeddingB "match" or not(1 or -1).
The dataset like this:
embA0 embB0 1.0
embA1 embB1 -1.0
embA2 embB2 1.0
...
I hope to use cosine similari... | In response to the comment thread.
The objective or pipeline seems to be:
Receive two embedding vectors (say, A and B).
Check whether these two vectors are "similar" or not (using cosine similarity).
Label is 1 if they're similar, and -1 otherwise (I recommend changing this to 0 or 1 rather than -1 and 1).
... | https://stackoverflow.com/questions/63750215/ |
Partial derivatives of Gaussian Process wrt features | Given a Gaussian Process Model with multidimensional features and scalar observations, how do I compute derivatives of the output wrt to each input, in GPyTorch or GPFlow (or scikit-learn)?
| If I understand your question correctly, the following should give you what you want in GPflow with TensorFlow:
import numpy as np
import tensorflow as tf
import gpflow
### Set up toy data & model -- change as appropriate:
X = np.linspace(0, 10, 5)[:, None]
Y = np.random.randn(5, 1)
data = (X, Y)
kernel = gpflow.k... | https://stackoverflow.com/questions/63753078/ |
How can I get argmaxed torch tensor excluding certain index? | I wonder if I can get torch.argmax of my input excluding certain index.
For example,
target = torch.tensor([1,2])
input = torch.tensor([[0.1,0.5,0.2,0.2], [0.1,0.5,0.1,0.3]])
I want to get the maximum value in input excluding the index on the target, so that the result would be
output = torch.tensor([[0.2],[0.5]])
| You can try this
Set negative infy to the target indices in temp tensor
Then use torch.max or torch.argmax
tmp_input = input.clone()
tmp_input[range(len(input)), target] = float("-Inf")
torch.max(tmp_input, dim=1).values
tensor([0.2000, 0.5000])
torch.max(tmp_input, dim=1).indices
tensor([3, 1])
torch.ar... | https://stackoverflow.com/questions/63772663/ |
TypeError: If no scoring is specified, the estimator passed should have a 'score' method | I have been working with a PyTorch neural network for a while now. I decided I wanted to add a permutation feature importance scorer, and this started to cause some issues.
I get" TypeError: If no scoring is specified, the estimator passed should have a 'score' method. The estimator <class 'skorch.net.NeuralNet... | From the docs:
NeuralNet still has no score method. If you need it, you have to implement it yourself.
This is the problem. The NeuralNet has no score method, as the error says. And the documentation says that "you have to implement it yourself". You can check that looking at the source-code too.
| https://stackoverflow.com/questions/63788527/ |
Questions about Batch Normalization in Pytorch | Recently when I use the BN in the PyTorch, I have several questions.
Based on the BN2d documentation in PyTorch, when inferencing(evaluation), it will automatically use the mean and variance (running estimate when training) for BN layer. However, my first question is that when we save out the model after training, doe... | I get the answers from my senior classmates, and I think it's useful for others. (If you have different points, feel free to comment)
When we save out the whole model, it will contain the running mean and variance for the BN layers. These two parameters are not learnable (not updated in backward process, but updated i... | https://stackoverflow.com/questions/63799763/ |
What is the correct way to implement gradient accumulation in pytorch? | Broadly there are two ways:
Call loss.backward() on every batch, but only call optimizer.step() and optimizer.zero_grad() every N batches. Is it the case that the gradients of the N batches are summed up? Hence to maintain the same learning rate per effective batch, we have to divide the learning rate by N?
Accumulat... | You can use PytorchLightning and you get this feature of the box, see the Trainer argument accumulate_grad_batches which you can also pair with gradient_clip_val, more in docs.
| https://stackoverflow.com/questions/63815311/ |
What is the machine precision in pytorch and when should one use doubles? | I am running experiments on synthetic data (e.g. fitting a sine curve) and I get errors in pytorch that are really small. One if about 2.00e-7. I was reading about machine precision and it seems really close to the machine precision. How do I know if this is going to cause problems (or if perhaps it already has e.g. I ... | I think you misunderstood how floating points work. There are many good resources (e.g.) about what floating points are, so I am not going into details here.
The key is that floating points are dynamic. They can represent the addition of very large values up to a certain accuracy, or the addition of very small values u... | https://stackoverflow.com/questions/63818676/ |
pytorch dataloader default_collate argument use with to(device) | Ive been trying to integrate the to(device) inside my dataloader using to(device) as seen in https://github.com/pytorch/pytorch/issues/11372
I defined it on FashionMNIST in the following way:
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
batch_size = 32
trainset = datasets.FashionMNIST('~/.pyt... | The fashion mnist dataset returns a tuple of img and target, where the img is tensor and target is int value for class.
Now, your dataloader takes batch size samples from dataset class to get list of samples. Note, this list of samples is now, List[Tuple[Tensor, int]](using typing annotation here). Then it calls, colla... | https://stackoverflow.com/questions/63827178/ |
HParams in Tensorboard, Run IDs and naming | I'm using SummaryWriter.add_hparams(params, values) to log hyperparameters during training of my Seq2Seq model. My runs are named with a timestamp like 2020-09-10 14-50-27. In the HParams tab in Tensorboard, everything looks fine, but the HParam Trial IDs are different; they have another string of numbers attached like... | As Aniket mentioned there is not enough in your issue description to be entirely sure what the issue is.
However, if you are using Pytorch, I suspect you may be referring to the behaviour also reported in this issue. The add_hparams method creates a new subfolder with current timestamp when called, which is 1599742915.... | https://stackoverflow.com/questions/63830848/ |
Trying to access subset of mnist dataset in pytorch [equal samples from each class] | Trying to access subset of mnist dataset in pytorch [equal samples from each class] but getting this error
prng = RandomState(42)
random_permute = prng.permutation(np.arange(0, 6000))[0:3000]
indx = np.concatenate([np.where(np.array(mnist_data.targets) == classe)[0][random_permute] for classe in range(0,10)])
--------... | MNIST dataset does not have a uniform distribution of targets. You are getting this error because class 0 in MNIST contains 5923 samples.
nums = [0]*10
for i in range(60000):
nums[(int(mnist_data.targets[i]))] += 1
print(nums)
This will print [5923, 6742, 5958, 6131, 5842, 5421, 5918, 6265, 5851, 5949].
| https://stackoverflow.com/questions/63851063/ |
no CUDA-capable device is detected at /pytorch/aten/src/THC/THCGeneral.cpp:47 in Google Colab | I have been using their algorithm for days and I tried several, but none of them gave me this error until now.
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-5-dbd18151b569> in <module>()
... | You have not enabled GPU on your notebook, enable it in Runtime > Change runtime.
| https://stackoverflow.com/questions/63855269/ |
Saving Model State and Load in Google Colab | I have 500 epochs in total to train . But it is taking 8 minutes per epoch to be completed in google colab. Can any one help me how can I save my Model state after a Particular number of epoch completion and start the training again from where I left in google Colab ??
| If you want to save the model to google drive after certain number of epochs in pytorch you can do so by using
first mount google drive
from google.colab import drive
drive.mount('/content/gdrive')
Then the run the cell in colab and authenticate. Now google drive should be mounted.
Now set the path to be
PATH = F"... | https://stackoverflow.com/questions/63879856/ |
how initialize a torch of matrices | Hello I m trying to create a tensor that will have inside N matrices of n by n size. I tried to initialize it with
Q=torch.zeros(N, (n,n))
but i get the following error
zeros(): argument 'size' must be tuple of ints, but found element of type tuple at pos 2
Also I want to fill it later with random matrices with integ... | N matrices of n x n size is equivalent to three dimensional tensor of shape [N, n, n]. You can do it like so:
import torch
N = 32
n = 10
tensor = torch.randint(0, 10, size=(N, n, n))
No need to fill it with zeros to begin with, you can create it directly.
You can also iterate over 0 dimension similar to what you did:... | https://stackoverflow.com/questions/63884811/ |
RuntimeError: Expected 3-dimensional input for 3-dimensional weight [64, 512, 1], but got 2-dimensional input of size [4, 512] instead | Hello below is the pytorch model I am trying to run. But getting error. I have posted the error trace as well. It was running very well unless I added convolution layers. I am still new to deep learning and Pytorch. So I apologize if this is silly question. I am using conv1d so why should conv1d expect 3 dimensional in... | You should learn how convolutions work (e.g. see this answer) and some neural network basics (this tutorial from PyTorch).
Basically, Conv1d expects inputs of shape [batch, channels, features] (where features can be some timesteps and can vary, see example).
nn.Linear expects shape [batch, features] as it is fully conn... | https://stackoverflow.com/questions/63885053/ |
How to train deeplabv3 on custom dataset on pytorch? | I am trying to do image segmentation and I got to know the Google work of DeepLabv3.
This is the reference to the paper:
https://arxiv.org/abs/1706.05587
Chen, L.C., Papandreou, G., Schroff, F. and Adam, H., 2017. Rethinking atrous convolution for semantic image segmentation. arXiv preprint arXiv:1706.05587.
This archi... |
Write custom Dataloader class which should inherit Dataset class and implement at least 2 methods __len__ and __getitem__.
Modify the pretrained DeeplabV3 head with your custom number of output channels.
from torchvision.models.segmentation.deeplabv3 import DeepLabHead
from torchvision.models.segmentation import d... | https://stackoverflow.com/questions/63892031/ |
Pytorch: How to concatenate lists within a tensor? | I have a tensor of size (2, b, h) and I want to change it to the following size: (b, 2*h), where the corresponding lists are concatenated, for example:
a = torch.tensor([[[1, 2, 3], [4, 5, 6], [4, 4, 4]],
[[4, 5, 6], [7, 8, 9], [5, 5, 5]]])
I want:
b = tensor([[1, 2, 3, 4, 5, 6],
[4, 5, 6... | Use permute first to change order of dimensions, then contiguous to prevent strides within the permuted tensor and finally use view to reshape the tensor.
b = a.permute(1,0,2).contiguous().view(a.shape[1],-1)
| https://stackoverflow.com/questions/63909009/ |
How to create a copy of nn.Sequential in torch? | I am trying to create a copy of a nn.Sequential network. For example, the following is the easiest way to do the same-
net = nn.Sequential(
nn.Conv2d(16, 32, 3, stride=2),
nn.ReLU(),
nn.Conv2d(32, 64, 3, stride=2),
nn.ReLU(),
)
net_copy = nn.Sequential(
nn.Conv2d(16, 32, 3, ... | Well, I just use torch.load and torch.save with io.BytesIO
import io, torch
# write to a buffer
buffer = io.BytesIO()
torch.save(model, buffer) #<--- model is some nn.module
print(buffer.tell()) #<---- no of bytes written
del model
# read from buffer
buffer.seek(0) #<--- must see to origin every time befo... | https://stackoverflow.com/questions/63913170/ |
LayerNorm inside nn.Sequential in torch | I am trying to use LayerNorm inside nn.Sequential in torch. This is what I am looking for-
import torch.nn as nn
class LayerNormCnn(nn.Module):
def __init__(self):
super(LayerNormCnn, self).__init__()
self.net = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1),
... | The original layer normalisation paper advised against using layer normalisation in CNNs, as receptive fields around the boundary of images will have different values as opposed to the receptive fields in the actual image content. This issue does not arise with RNNs, which is what layer norm was originally tested for. ... | https://stackoverflow.com/questions/63914843/ |
Using sigmoid output for cross entropy loss on Pytorch | Iβm trying to modify Yolo v1 to work with my task which each object has only 1 class. (e.g: an obj cannot be both cat and dog)
Due to the architecture (other outputs like localization prediction must be used regression) so sigmoid was applied to the last output of the model (f.sigmoid(nearly_last_output)). And for clas... |
MSE loss is usually used for regression problem.
For binary classification, you can either use BCE or BCEWithLogitsLoss. BCEWithLogitsLoss combines sigmoid with BCE loss, thus if there is sigmoid applied on the last layer, you can directly use BCE.
The GT mentioned in your case refers to 'multi-class' classification... | https://stackoverflow.com/questions/63914849/ |
Get Predictions from Trained Pytorch Model | I am using transfer learning to fine tune an inception_v3 model. After I train the model and store the best version off I am attempting to use it to generate predictions for my test set. Below is an example of my attempt on one image.
img_test=Image.open("img.png")
#Perform same transformations to image that... | As the error said, it seem that the input of the model (your img_test) is in the cpu.
Try to move the image to cuda before send it through your pre-trained model:
device = torch.device('cuda' if torch.cuda.is_available())
img_test = img_test.to(device)
| https://stackoverflow.com/questions/63921487/ |
How to retain 2D (or more) shape when using pytrorch masked_select | Suppose I have the following two matching shape tensors:
a = tensor([[ 0.0113, -0.1666, 0.5960, -0.0667], [-0.0977, -0.1984, 0.5153, 0.0420]])
selectors = tensor([[ True, True, False, False], [ True, False, True, False]])
When using torch.masked_select to find the values in a that match True indices in selectors ... | As @jodag pointed out, for general inputs, each row on the desired masked result might have a different number of elements, depending on how many True values there are on the same row in selectors. However, you could overcome this by allowing trailing zero padding in the result.
Basic solution:
indices = torch.masked_f... | https://stackoverflow.com/questions/63928630/ |
Non-deterministic behavior for training a neural network on GPU implemented in PyTorch and with a fixed random seed | I observed a strange behavior of the final Accuracy when I run exactly the same experiment (the same code for training neural net for image classification) with the same random seed on different GPUs (machines). I use only one GPU. Precisely, When I run the experiment on one machine_1 the Accuracy is 86,37. When I run ... | This is what I use:
import torch
import os
import numpy as np
import random
def set_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
os.environ['PYTHON... | https://stackoverflow.com/questions/63939096/ |
requires_grad = False seems not working in my case | I received a Cannot insert a Tensor that requires grad as a constant. Consider making it a parameter or input, or detaching the gradient error with tensor W.
W has the size of (10,10) and grad_fn=<DivBackward0>. The error happens at the second line
def muy(self, x):
V = torch.tensor(self.W - self.lambda_ * to... | V = torch.tensor(self.W - self.lambda_ * torch.eye(self.ENCODING_DIM), requires_grad=False)
What you are trying to do here doesn't make much sense. torch.tensor(value) can only be created if the value is scalar (e.g. Python's 5), while you are trying to fit torch.Tensor there.
What you should do is simply this:
V = se... | https://stackoverflow.com/questions/63944967/ |
Retrieve elements from a 3D tensor with a 2D index tensor | I am playing around with GPT2 and I have 2 tensors:
O: An output tensor of shaped (B, S-1, V) where B is the batch size S is the the number of timestep and V is the vocabulary size. This is the output of a generative model and is softmaxed along the 2nd dimension.
L: A 2D tensor shaped (B, S-1) where each element is th... | For reference, I based my answer on this Medium article.
Essentially, your answer lies in torch.gather, assuming that both of your tensors are just regular torch.Tensors (or can be converted to one).
import torch
# Specify some arbitrary dimensions for now
B = 3
V = 6
S = 4
# Make example reproducible
torch.manual_se... | https://stackoverflow.com/questions/63950303/ |
Moving a tensor to cuda device cause illegal memory access in Pytorch | I am trying the following snippet in Colab but causes the following error.
Is it wrong to move a tensor object to Cuda device?.
import torch
a = torch.Tensor(torch.randn(5,5,5))
# a.device("cuda")
device = torch.device("cuda")
class abc(torch.nn.Module):
def __init__(self):
super().__ini... | This works for me on Google colab:
import torch
a = torch.randn(5,5,5)
a = a.to("cuda") # or just a = torch.randn((5,5,5), device='cuda')
class abc(torch.nn.Module):
def __init__(self):
super().__init__()
self.w1 = torch.nn.Linear(5,5)
def forward(self,x):
return self.w1(x)
m... | https://stackoverflow.com/questions/63951247/ |
How to avoid overfitting in deep learning when features are binary in nature | I am constructing a deep learning model using 2048 bits of binary fingerprints (0 and 1's) for some 2000 samples to predict their outputs (positive (1) OR negative(0)). The feature data is quite sparse i.e. lots of zeros and rare 1's.
I have used 'binary cross entropy' but my validation accuracy doesn't increase more t... | If you want to do a binary classification, binary crossentropy is the loss function you are looking for.
Achieving a well generalizing model includes more than just the right loss function choice (Preprocessing Data, Finding a proper Network Architecture, Finding the right hyper parameter choice, ...).
You can find a d... | https://stackoverflow.com/questions/63956262/ |
PyTorch: How to check if some weights are not changed during training? | How can I check if some weights are not changed during training in PyTorch?
As I understand one option can be just dump model weights at some epochs and check if they are changed iterating over weights, but maybe there is some simpler way?
| There can be two ways around this:
First
for name, param in model.named_parameters():
if 'weight' in name:
temp = torch.zeros(param.grad.shape)
temp[param.grad != 0] += 1
count_dict[name] += temp
This step comes in after your loss.backward() step in t... | https://stackoverflow.com/questions/63962561/ |
Pytorch Multi-GPU Issue | I want to train my model with 2 GPU(id 5, 6), so I run my code with CUDA_VISIBLE_DEVICES=5,6 train.py. However, when I printed torch.cuda.current_device I still got the id 0 rather than 5,6. But torch.cuda.device_count is 2, which semms right. How can I use GPU5,6 correctly?
| It is most likely correct. PyTorch only sees two GPUs (therefore indexed 0 and 1) which are actually your GPU 5 and 6.
Check the actual usage with nvidia-smi. If it is still inconsistent, you might need to set an environment variable:
export CUDA_DEVICE_ORDER=PCI_BUS_ID
(See Inconsistency of IDs between 'nvidia-sm... | https://stackoverflow.com/questions/63967302/ |
Process stuck when training on multiple nodes using PyTorch DistributedDataParallel | I am trying to run the script mnist-distributed.py from Distributed data parallel training in Pytorch. I have also pasted the same code here. (I have replaced my actual MASTER_ADDR with a.b.c.d for posting here).
import os
import argparse
import torch.multiprocessing as mp
import torchvision
import torchvision.transfor... | I met a similar problem. And the problem is solved by
sudo vi /etc/default/grub
Edit it:
#GRUB_CMDLINE_LINUX="" <----- Original commented
GRUB_CMDLINE_LINUX="iommu=soft" <------ Change
sudo update-grub
Reboot to see the change.
Ref: https://github.com/pyt... | https://stackoverflow.com/questions/63968082/ |
Why am I getting calculated padding input size per channel smaller than kernel size? | I have the following model but its returning an error. Not sure why. I have tried googling but not found anything so far. My input is an numpy array of 6 by 6.
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 16, kernel_size=(3,3), stride=1, padding=0)
s... | Here is what you may do and I used the padding=1 as proposed by Szymon Maszke. This padding is added to the convolution and to maxpooling.
import numpy
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Con... | https://stackoverflow.com/questions/63971920/ |
How to install PyTorch with pipenv and save it to Pipfile and Pipfile.lock? | Iβm currently using Pipenv to maintain the Python packages used in a specific project. Most of the downloads Iβve tried so far have worked as intended; that is, I enter pipenv install [package] and it installs the package into the virtual environment, then records the package information into both the Pipfile and Pipfi... | When you use pipenv run pip install <package>, that skips the custom pipenv operations of updating the Pipfile and the Pipfile.lock. It is basically equivalent to doing a plain pip install <package> as if you did not have/use pipenv.
The only way to also update the Pipfile's is to use pipenv install.
Unfort... | https://stackoverflow.com/questions/63974588/ |
Using trained BERT Model and Data Preprocessing | When using a pre-trained BERT embeddings from pytorch (which are then fine-tuned), should the text data fed into the model be pre-processed like in any standard NLP task?
For instance, should stemming, removing low frequency words, de-captilisation, be performed or should the raw text simply be passed to `transformers... | I think preprocessing will not change your output predictions. I will try to explain for each case you mentioned -
stemming or lemmatization :
Bert uses BPE (Byte- Pair Encoding to shrink its vocab size), so words like run and running will ultimately be decoded to run + ##ing.
So it's better not to convert running int... | https://stackoverflow.com/questions/63979544/ |
CNN model is overfitting to data after reaching 50% accuracy | I am trying to identify 3 (classes) mental states based on EEG connectome data. The shape of the data is 99x1x34x34x50x130 (originally graph data, but now represented as a matrix), with respectably represent [subjects, channel, height, width, freq, time series]. For the sake of this study, can only input a 1x34x34 imag... | I have some suggestions, what I would try, maybe you've already done it:
increase the probability of dropout, that could decrease overfitting,
I did not see or I missed it but if you don't do it, shuffle all the samples,
there is not so much data, did you thought about using other NN to generate more data of the class... | https://stackoverflow.com/questions/63983710/ |
How to find the mean and the covariance of a 2d activation map (pytorch) | I have a tensor of shape [h, w], which consists of a normalized, 2-dimensional activation map. Considering this to be some distribution, I want to find the mean and the covariance within this activation map in pytorch. Is there an efficient way to do that?
| You can use the following code, where activation_map is a tensor of shape (h,w), with non-negative elements, and is normalised (activation_map.sum() is 1):
activation_map = torch.tensor(
[[0.2, 0.1, 0.0],
[0.1, 0.2, 0.4]])
h, w = activation_map.shape
range_h = torch.arange(h)
range_w = torch.arange(w)
idxs = ... | https://stackoverflow.com/questions/63991646/ |
How to specify different layer sizes in Pytorch LSTM/GRU/RNN | so I know how to work with LSTMs in general with Pytorch. But it bugs me, that you can only specify ONE hidden_size for all your layers in the LSTM. Like this:
lstm = nn.LSTM(input_size=26, hidden_size=128, num_layers=3, dropout=dropout_chance, batch_first=True)
So for all three layers, the size will be 128. But is th... | Actually, it depends on the shape of your input and you can see How to decide input and hidden layer dimension to torch.nn.RNN?. Also, you have to understand what is the input and the output because there are different ways to deal with the input and the output. In the A Beginnerβs Guide on Recurrent Neural Networks w... | https://stackoverflow.com/questions/63996218/ |
Is there any way to get torch.mode over multidimensional tensor | is there any way torch.mode can be applied over multiple dimensions
for example
import numpy as np
import torch
x = np.random.randint(10, size=(3, 5))
y = torch.tensor(x)
lets say y has
[[6 3 7 3 0]
[2 5 7 9 7]
[6 1 4 6 3]]
torch.mode should return a size 3 tensor [3,7,6]
without using a loop
| Use the dimension attribute in torch to select which dimension should be reduced using mode operator.
torch.mode(y, dim = 1)[0]
Will give you the desired answer.
| https://stackoverflow.com/questions/64001903/ |
How can I assign a list to a torch.tensor? | Assume that I have a list [(0,0),(1,0),(1,1)] and another list [4,5,6] and a matrix X with size is (3,2). I am trying to assign the list to the matrix like X[0,0] = 4, X[1,0] = 5 and X[1,1] = 6. But it seems like I have a problem of assigning a list to tensor
x = torch.zeros(3,2)
indices = [(0,0),(1,0),(1,1)]
value = [... | In general, the answer to "how do I change a list to a Tensor" is to use torch.Tensor(list). But that will not solve your actual problem here.
One way would be to associate the index and value and then iterate over them:
for (i,v) in zip(indices,values) :
x[i] = v
| https://stackoverflow.com/questions/64015076/ |
Why is Loss of SGD for a dataset is not matching the pytorch code with the scratch python code for linear regression? | I'm trying to implement Multiple Linear regression on the wine dataset. But when I compare the results of Pytorch with scratch code of Python the losses are not coming same.
My Scratch Code:
Functions:
def yinfer(X, beta):
return beta[0] + np.dot(X,beta[1:])
def cost(X, Y, beta):
sum = 0
m = len(Y)
for i in r... | There were a couple of tweaks necessary to the code. I also had to create data and an optimizer, which you hadn't provided. With the changes below, both methods produce a learning function.
Of course optimal hyperparameters such as alpha or iterations might be different between the two approaches, and you might need to... | https://stackoverflow.com/questions/64016054/ |
Getting an error(cannot import name 'BertPreTrainedModel') while importing classification model from simpletransformers | Getting the following error while trying to import the classificationmodel from simpletransformers.
ImportError Traceback (most recent call last)
<ipython-input-1-29f08e6c2d87> in <module>()
----> 1 from simpletransformers.classification import ClassificationModel, Classif... | In this github issue the problem was an old version of simpletransformers. To get the latest version do pip install --upgrade simpletransformers. Maybe even do this for the transformers package as well.
| https://stackoverflow.com/questions/64020998/ |
implement dropout layer using nn.Sequential() | I am trying to implement a Dropout layer using pytorch as follows:
class DropoutLayer(nn.Module):
def __init__(self, p):
super().__init__()
self.p = p
def forward(self, input):
if self.training:
u1 = (np.random.rand(*input.shape)<self.p) / self.p
u1 *= u1
... | In the forward function of your DropoutLayer, when you enter the elsebranch, there is no return. Therefore the following layer (flatten) will have no input. However, as emphasized in the comments, that's not the actual problem.
The actual problem is that you are passing a numpy array to your Flatten layer. A Minimal co... | https://stackoverflow.com/questions/64032525/ |
Force installing torchvision 0.4.2 when I am forced to use pytorch 1.3.1 due to hardware constraints (ppc64le IBM) | I am in a weird scenario were I am forced to use torch 1.3.1 (due to hardware see: https://public.dhe.ibm.com/ibmdl/export/pub/software/server/ibm-ai/conda/#/). I read from the pytorch docs that it's corresponding version of torchvision is 0.4.1 (https://pypi.org/project/torchvision/):
Installation
We recommend Anacon... | For all details check (https://github.com/IBM/powerai/issues/268).
Make sure you have the right conda channel prepended:
conda config --prepend channels https://public.dhe.ibm.com/ibmdl/export/pub/software/server/ibm-ai/conda/#/
then install the powerai wmlce that you want e.g. 1.7.0 (most recent as of this writing):
... | https://stackoverflow.com/questions/64033543/ |
Why does requires_grad turns from true to false when doing torch.nn.conv2d operation? | I have Unet network which takes in MRI images of the brain, where the goal is to segment white substance in the brain. The images has the shape 256x256x183 (reshaped to 183x256x256) (FLAIR and T1 images). The problem I am having is that before sending the input to the Unet network, I have requires_grad=True on my pytor... | The training code is fine and the input doesn't need a gradient at all, if you just want to train and update the weights.
The real problem is this line here
with torch.set_grad_enabled(is_train == "train"):
So you want to disable the gradients if you are not training. The thing is is_train is a bool (judgin... | https://stackoverflow.com/questions/64034471/ |
undefined symbol: THPVariableClaload_textures.cpython-37m-x86_64-linux-gnu.so: undefined symbol: THPVariableClass | Do you know how I could fix this? I am trying to use https://github.com/benjiebob/SMALViewer/issues/3 repo however I get error on neural_renderer port:
$ python smal_viewer.py
Traceback (most recent call last):
File "smal_viewer.py", line 2, in <module>
import pyqt_viewer
File "/home/mona/... | It looks like you didn't build the neural_renderer_pytorch yourself, but used a wheel. However, this wheel was built with an older pytorch version and doesn't work with the current pytorch version on your machine.
Build neural_renderer from the source (after deinstalling neural_renderer you have now) using your current... | https://stackoverflow.com/questions/64037618/ |
How to make a Trainer pad inputs in a batch with huggingface-transformers? | I'm trying to train a model using a Trainer, according to the documentation (https://huggingface.co/transformers/master/main_classes/trainer.html#transformers.Trainer) I can specify a tokenizer:
tokenizer (PreTrainedTokenizerBase, optional) β The tokenizer used to
preprocess the data. If provided, will be used to auto... | Look at the columns your tokenizer is returning. You might wanna limit it to only the required columns.
For Example
def preprocess_function(examples):
#function to tokenize the dataset.
if sentence2_key is None:
return tokenizer(examples[sentence1_key], truncation=True, padding=True)
return tokenizer(ex... | https://stackoverflow.com/questions/64047261/ |
How does one install torchmeta for a ppc64le architecture in pytorch? | I was trying to use torchmeta in a ppc64le architecture. Unfortunately it's not been easy to install since ppc64le requires special binaries to work.
I eventually managed to get the right binaries for pytorch and torchvision by following these instructions (that prepend the right ibm channel with the conda binaries, pl... | Because there are not wheels for powerpc for h5py you are installing h5py from source (from the tarball). This requires both the Python and h5py development headers to be available, see https://docs.h5py.org/en/stable/build.html#source-installation.
Either install h5py from conda or install the required build dependen... | https://stackoverflow.com/questions/64049603/ |
how "data" and "target" are choosen in a federated learning? (PySyft) | i can't understand how in function train() below, the variable (data, target) are choosen.
def train(args, model, device, federated_train_loader, optimizer, epoch):
model.train()
for batch_idx, (data, target) in enumerate(federated_train_loader): # <-- now it is a distributed dataset
model.send(data.... | Consider it like this. When you hook torch, all your torch tensors will get additional functionality - methods like .send(), .federate(), and attributes like .location and ._objects. Your data and target, which were once torch tensors, became pointers to tensors residing in different VirtualWorker objects due to .feder... | https://stackoverflow.com/questions/64050391/ |
Using both vCPU's with google cloud computing. Python code. PyTorch | I am new to cloud computing. I made a virtual machine in google cloud computing, machine type:
e2-highcpu-2 (2 vCPU's, 2 GB geheugen)
I run a script with running the command
python3 simulation1.py
When I look at the output control screen, I note that only 50% of the CPU power is used. So I just use one of my 2 CPU's. ... | Looks like your question can be resumed to "is Python capable of running on multiple cores?"
And you can find the answer to that question perfectly explained in this post.
Basically:
Python threads cannot take advantage of many cores. This is due to an internal implementation detail called the GIL (global int... | https://stackoverflow.com/questions/64051603/ |
PyTorch linear regression model | I have a multivariate linear regression problem in which each data point looks like this:
y_i = 3 # Some integer between 0 and 20
X_i = [0.5, 80, 0.004, 0.5, 0.789] # A 5 dimensional vector
I can train a simple linear model by using sklearn, something like:
from sklearn import linear_model... | tam63,
you are missing activation function in the model definition. replace
y_pred = self.linear1(x)
with
y_pred = F.relu(self.linear1(x))
there are few more things that may go wrong.
For instance (1) too low a learning rate, (2) too few layers (add one more). If you are familiar with TF as you say, try same problem... | https://stackoverflow.com/questions/64052643/ |
PyTorch: difference between type(a), a.type, a.type() | suppose a is a tensor, then what's the difference between:
type(a)
a.type
a.type()
I couldn't find a document differentiating these.
| type is the python in-built method.
It will return type of object. like <class 'torch.Tensor'>
torch.Tensor.type (x.type()) is pytorch in-built method.
It will return type of data stored inside tensor. like torch.DoubleTensor, etc.
Edit:
And about x.type() vs x.type -
When you write a function name with pare... | https://stackoverflow.com/questions/64056979/ |
Jupyter doesn't recognize torchaudio | I am trying to install torchaudio to use in a Jupyter notebook but when i import it i get the error:
ModuleNotFoundError: No module named 'torchaudio'
I tried to import it in a .py file that the notebook uses but to with no success. I thought maybe it wasnt installed properly but when i try to install it using pip ins... | pip install torchaudio
should return:
Collecting torchaudio
Downloading https://files.pythonhosted.org/packages/96/34/c651430dea231e382ddf2eb5773239bf4885d9528f640a4ef39b12894cb8/torchaudio-0.6.0-cp36-cp36m-manylinux1_x86_64.whl (6.7MB)
|ββββββββββββββββββββββββββββββββ| 6.7MB 2.4MB/s
Requirement already sati... | https://stackoverflow.com/questions/64058958/ |
matching PyTorch tensor dimensions | I am having some issues with regards to the dimensionality of my tensors in my training function at present. I am using the MNIST dataset, so 10 possible targets, and originally wrote the prototype code using a training batch size of 10, which was in retrospect not the wisest choice. It gave poor results during some ea... | There are several problems in your training script. I will address each of them below.
First, you should NOT do data batching by hand. Pytorch/torchvision have functions for that, use a dataset and a data loader: https://pytorch.org/tutorials/recipes/recipes/loading_data_recipe.html.
You should also NEVER update the ... | https://stackoverflow.com/questions/64067203/ |
Pytorch: What happens to memory when moving tensor to GPU? | Iβm trying to understand what happens to both RAM and GPU memory when a tensor is sent to the GPU.
In the following code sample, I create two tensors - large tensor arr = torch.Tensor.ones((10000, 10000)) and small tensor c = torch.Tensor.ones(1). Tensor c is sent to GPU inside the target function step which is called ... |
Iβm sending torch.Tensor.ones(1) to GPU and yet it consumes 487 MB of GPU memory. Does CUDA allocate a minimum amount of memory on the GPU even if the underlying tensor is very small?
The CUDA device runtime reserves memory for all sorts of things at context establishment, some of which are fixed in size and some of ... | https://stackoverflow.com/questions/64068771/ |
What does this strange C++ syntax do? | From what I understand, 3 arguments are being passed to m.def(). I don't understand the syntax of the second argument passed, i.e. [] (Observable...){} What does this mean?
m.def(
"DumpHistogramFile",
[](Observable<NetBase>::Observer* ob) {
HistogramNetObserver* hist_ob =
dynamic_cast_if... | The second argument is a function that takes a pointer to an Observer and doesn't return anything. When executed, it calls DumpHistogramFile. This is called a lambda expression.
| https://stackoverflow.com/questions/64073352/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.