instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Pytorch for Raspberry Pi 3 B+
I have successfully cross compiled Pytorch 1.7 for Raspberry Pi3 B+ and the following wheel was generated as the result: torch-1.7.0a0-cp37-cp37m-linux_armv7l.whl However, when I try to install the wheel on the pi, I get this error: ERROR: torch-1.7.0a0-cp37-cp37m-linux_armv7l.whl is not a supported wheel on this plat...
I eventually found the answer, I had python 3.8 on my target hw (raspberry pi 3B+) and I used had python 3.7 on my build system. Downgrading python 3.8 to python 3.7 on target hw fixed the issue.
https://stackoverflow.com/questions/64073994/
AttributeError: 'Function' object has no attribute 'block_variable'
I have written a subclass of torch_fenics. In this, the input is a vector from DG space. I use this input in the weak formulation and then calculate the solution. Further, I need the gradient of the solution with respect to the given input. I get the following error log on running the same ~/miniconda3/envs/py37/lib/...
Don't import dolfin in your code. It will resolve the issue.
https://stackoverflow.com/questions/64077834/
Creating a Pseudo-Cyclic signal using a cyclic signal
I am looking for a way using numpy or pytorch to skew a tensor. For example given an array of samples of sin(x), i hope to get a skewed version of it (preferably the same size) such that the cycle of the function is either stretched or shrinks or even both (if it can interpolate it randomly), so in some parts the frequ...
You can play around with (for instance) locally varying frequency. Considering a sine function as a base periodic function, using a locally varying frequency can give "stretched" and/or "dilated" effect. Example 1: chirp function with linear frequency change (check the wiki page for more information...
https://stackoverflow.com/questions/64087503/
deep neural network model stops learning after one epoch
I am training a unsupervised NN model and for some reason, after exactly one epoch (80 steps), model stops learning. ] Do you have any idea why it might happen and what should I do to prevent it? This is more info about my NN: I have a deep NN that tries to solve an optimization problem. My loss function is customized ...
The symptom is that the training loss stops being improved relatively early. Suppose that your problem is learnable at all, there are many reasons for the for this behavior. Following are most relavant: Improper preprocessing of input: Neural network prefers input with zero mean. E.g., if the input is all positive, it...
https://stackoverflow.com/questions/64095558/
Char RNN classification with batch size
I'm replicating this example for a classification with a Pytorch char-rnn. for iter in range(1, n_iters + 1): category, line, category_tensor, line_tensor = randomTrainingExample() output, loss = train(category_tensor, line_tensor) current_loss += loss I see that every epoch only 1 example is taken and ran...
If you construct a Dataset class by inheriting from the PyTorch Dataset class and then feed it into the PyTorch DataLoader class, then you can set a parameter batch_sizeto determine how many examples you will get out in each iteration of your training loop. I have followed the same tutorial as you. I can show you how I...
https://stackoverflow.com/questions/64098364/
Input fixed length sequence of frames to CNN
I want my pytorch CNN to take as input a sequence of length SEQ_LEN of 32x32 RGB images concatenated along channels dimension. Therefore, a single input of the network has shape (32, 32, 3, SEQ_LEN). How should I define my CNN input layer? The common way SEQ_LEN = 10 input_conv = nn.Conv2d(in_channels=SEQ_LEN, out_chan...
Given your comments, it sounds like your data is not fit for a 2D convolutional neural network at all, and that a 3D one (Conv3d) would be more appropriate. As you can see from its documentation, its input shape is what you would expect.
https://stackoverflow.com/questions/64100096/
PyTorch LSTM not learning in training
I have the following simple LSTM network: class LSTMModel(nn.Module): def __init__(self, input_dim, hidden_dim, layer_dim, output_dim): super().__init__() self.hidden_dim = hidden_dim self.layer_dim = layer_dim self.rnn = nn.LSTM(input_dim, hidden_dim, layer_dim, batch_first=True) ...
So normally 6 layers in your LSTM are way to much. The input dimension is 28 (are you training MNIST, or are the inputs letters?) so 10 as hidden dimension is acutally way to small. Try the following parameters: hidden_dim = 128 to 512 layer_dim = 2 to max. 4 I see your output-shape is 1 and you dont use an activation...
https://stackoverflow.com/questions/64103683/
In 2020 what is the optimal way to train a model in Pytorch on more than one GPU on one computer?
What are the best practices for training one neural net on more than one GPU on one machine? I'm a little confused by the different options from nn.DataParallel vs putting different layers on different GPUs with .to('cuda:0') and .to('cuda:1'). I see in the Pytorch docs the latter method the date was 2017. Is there a s...
If you cannot fit all the layers of your model on a single GPU, then you can use model parallel (that article describes model parallel on a single machine, with layer0.to('cuda:0') and layer1.to('cuda:1') like you mentioned). If you can, then you can try distributed data parallel - each worker will hold its own copy of...
https://stackoverflow.com/questions/64105986/
Why is looping through pytorch tensors so slow (compared to Numpy)?
I've been working with image transformations recently and came to a situation where I have a large array (shape of 100,000 x 3) where each row represents a point in 3D space like: pnt = [x y z] All I'm trying to do is iterating through each point and matrix multiplying each point with a matrix called T (shape = 3 X 3)...
Why are you using a for loop?? Why do you compute a 3x3 dot product and only uses the first element of the result?? You can do all the math in a single matmul: with torch.no_grad(): depth_array = torch.matmul(pnt_cloud, T[:1, :].T) # nx3 dot 3x1 -> nx1 # since you only want non negative results depth_array = ...
https://stackoverflow.com/questions/64136656/
How to load checkpoints across different versions of pytorch (1.3.1 and 1.6.x) using ppc64le and x86?
As I outlined here I am stuck using old versions of pytorch and torchvision due to hardware e.g. using ppc64le IBM architectures. For this reason, I am having issues when sending and receiving checkpoints between different computers, clusters and my personal mac. I wonder if there is any way to load models in a way to ...
I believe what the developers intend is passing a flag for saving as a pickle. Just a default behavior change. For previously checkpointed files reload the zip file saved weights in the newer env(with pytorch>=1.6), and then checkpoint again as a pickle (no need to re-train); update your code and add flag from next ...
https://stackoverflow.com/questions/64141188/
Fine tuning of Bert word embeddings
I would like to load a pre-trained Bert model and to fine-tune it and particularly the word embeddings of the model using a custom dataset. The task is to use the word embeddings of chosen words for further analysis. It is important to mention that the dataset consists of tweets and there are no labels. Therefore, I us...
Since the objective of the masked language model is to predict the masked token, the label and the inputs are the same. So, whatever you have written is correct. However, I would like to add on the concept of comparing word embeddings. Since, BERT is not a word embeddings model, it is contextual, in the sense, that the...
https://stackoverflow.com/questions/64145666/
BERT NER Python
I am using BERT model for Named Entity Recognition task. I have torch version - 1.2.0+cu9.2 torch vision version - 0.4.0+cu9.2 Nvidia drivers compatible with cuda 9.2 when i am trying to train my model using the command loss, scores = model(b_input_ids.type(torch.cuda.LongTensor), token_type_ids=None,attention_mask=b_i...
A bit of googling provided the following hint with the following suggestions: This is due to an out of bounds index in the embedding matrix. If you are seeing this error using an nn.Embedding layer, you might add a print statement which shows the min and max values for each input. Some batches might have an out of b...
https://stackoverflow.com/questions/64156127/
Pytorch issue: torch.load() does not correctly load a saved model from file after closing and reopening Spyder IDE
I followed the most basic code procedure for saving and loading neural network model parameters and it works perfectly fine. After training the network, it is saved to a specified file in a specified folder in the package using the standard torch.save(model.state_dict(), file) method; when I need to rerun the program t...
It might be due to the fact that the state of your program is known while running the IDE but when closing it the state is lost resulting in the inability to know how to load the model (because the IDE doesnt know what model you are using). To solve this, try defining a new model and loading the parameters to it via lo...
https://stackoverflow.com/questions/64163602/
How to do 'same' padding in PyTorch if (n - 1) / 2 is no integer value
I am trying to reconstruct a neural network written in tensorflow. For the convolutional layer, they just use padding='SAME'. This doesn't exist in pytorch. I know, that I can calculate the padding with p = (n - 1) / 2 for stride=1. But what if this doesn't result in an integer value? In my case, n is 4 and I always wa...
Use math.floor function to round down to the nearest integer or the math.ceil function to round up to the nearest integer: import math # for flooring p = math.floor((n - 1) / 2)) # for ceiling p = math.ceil((n - 1) / 2)) For example, by default, pytorch uses flooring for MaxPool layers. So, I think flooring is a goo...
https://stackoverflow.com/questions/64163825/
Pytorch - Trick AutoGrad into thinking another output is the final outcome
The scenario: I have a simple torch CNN network that predicts if a given image input is a dog or a cat. After getting the output of the neural network, I need to apply a modifier of X to each prediction. For example, if the neural network return [0.6, 0.4], and I want to apply a modifier of [0.05, -0.03], I need the ...
Use torch.no_grad context manager to deactivate autograd, for example this operation is not going to be recorded, but you should use in-place operation, otherwise you will add another tensor without grad_fn and break the graph. In your case: out = model(inputs) # [0.6, 0.4] with torch.no_grad(): out.add_(torch.te...
https://stackoverflow.com/questions/64178913/
Huggingface transformers unusual memory use
I have the following code attempting to use XL transformers to vectorize text: text = "Some string about 5000 characters long" tokenizer = TransfoXLTokenizerFast.from_pretrained('transfo-xl-wt103', cache_dir=my_local_dir, local_files_only=True) model = TransfoXLModel.from_pretrained("transfo-xl-wt...
Are you sure you are using the gpu instead of cpu? Try to run the python script with CUDA_LAUNCH_BLOCKING=1 python script.py. This will produce the correct python stack trace (as CUDA calls are asynchronous) Also you can set the CUDA_VISIBLE_DEVICES using export CUDA_VISIBLE_DEVICES=device_number. There is also an issu...
https://stackoverflow.com/questions/64180517/
Runtime Error : both arguments to matmul need to be at least 1d but they are 0d and 2d
This is the code I have written, I have tried modifying here and there and have always gotten the same error. As I am a beginner to PyTorch, I am just trying things out to see if machine learning will work on a linear dataset. So, with random, I initialized a dataset. Then, made a single linear neural network. Then, tr...
There are two errors in your code, first regarding shapes, second regarding dtypes. BTW. Please use snake_case for variables (e.g. my_dataset, net) and CamelCase for classes as it's a common Python convention. Shape error This one lies here: for i, data in enumerate(DataSet, 0): input, target = data optimizer.z...
https://stackoverflow.com/questions/64192810/
Pytorch listed by conda but cannot import
I am well aware similar questions have been asked at least twice, but none of the answers seams to solve the issue at hand My configuration Windows 10.0.18363, Anaconda 4.8.5, Cuda 10.1.243 conda env create -n torch -y python 3.7 conda activate torch conda install conda -y conda install pytorch torchvision cudatoolkit=...
More a suggestion than a solution: you can at least reduce the problem surface by working with a YAML instead of using a series of create/activate/install commands. Create the file: torch.yaml name: torch channels: - pytorch - defaults dependencies: - python=3.7 - pytorch - torchvision - cudatoolkit=10.2 T...
https://stackoverflow.com/questions/64197273/
How does Pytorch's `autograd` handle non-mathematical functions?
During the course of my training process, I tend to use a lot of calls to torch.cat() and copying tensors into new tensors. How are these operations handled by autograd? Is the gradient value affected by these operations?
As pointed out in the comments, cat is a mathematical function. For example we could write the following (special case) definition of cat in more traditional mathematical notation as The Jacobian of this function w.r.t. either of its inputs can be expressed as Since the Jacobian is well defined you can, of course, ap...
https://stackoverflow.com/questions/64211037/
Kernel keeps dying when plotting a graph after importing the torch library
I'm trying to run the following code: import matplotlib.pyplot as plt %matplotlib inline import torch x = y = torch.tensor([1,2,3]).numpy() plt.plot(x,y); I keep getting the message: The kernel appears to have died. It will restart automatically. and a restart and a red "Dead kernel" tag on the toolbar. But...
import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" Run this first, then it'll resolve your problem. Although I guess, it is a temporary solution you can refer to this link: https://www.programmersought.com/article/53286415201/
https://stackoverflow.com/questions/64216189/
How to monitor GPU memory usage when training a DNN?
I give a result example. I want to ask how to get the data like this graph.
You can use pytorch commands such as torch.cuda.memory_stats to get information about current GPU memory usage and then create a temporal graph based on these reports.
https://stackoverflow.com/questions/64221308/
How is cross entropy loss work in pytorch?
I am experimenting with some of the pytorch codes. With cross entropy loss I found some interesting results and I have used both binary cross entropy loss and cross entropy loss of pytorch. import torch import torch.nn as nn X = torch.tensor([[1,0],[1,0],[0,1],[0,1]],dtype=torch.float) softmax = nn.Softmax(dim=1) bc...
The reason that you are seeing this is because nn.CrossEntropyLoss accepts logits and targets, a.k.a X should be logits, but is already between 0 and 1. X should be much bigger, because after softmax it will go between 0 and 1. ce_loss(X * 1000, torch.argmax(X,dim=1)) # tensor(0.) nn.CrossEntropyLoss works with logits...
https://stackoverflow.com/questions/64221896/
What is a subspace of a dimension in pytorch?
The documentation of torch.Tensor.view says: each new view dimension must either be a subspace of an original dimension, or only span across original dimensions ... https://pytorch.org/docs/stable/tensors.html?highlight=view#torch.Tensor.view What is a subspace of a dimension?
The 'subspace of an original dimension' dilemma In order to use tensor.view() the tensor must satisfy two conditions- each new view dimension must either be a subspace of an original dimension or only span across original dimensions ... Lets discuss this one by one, First, regarding subspace of an original dimension ...
https://stackoverflow.com/questions/64225965/
pyTorch gradient becomes none when dividing by scalar
Consider the following code block: import torch as torch n=10 x = torch.ones(n, requires_grad=True)/n y = torch.rand(n) z = torch.sum(x*y) z.backward() print(x.grad) # results in None print(y) As written, x.grad is None. However, if I change the definition of x by removing the scalar multiplication (x = torch.ones(n,...
When you set x to a tensor divided by some scalar, x is no longer what is called a "leaf" Tensor in PyTorch. A leaf Tensor is a tensor at the beginning of the computation graph (which is a DAG graph with nodes representing objects such as tensors, and edges which represent a mathematical operation). More spec...
https://stackoverflow.com/questions/64233099/
I want to use Conv1D and MaxPool1D in pytorch for a 3-d tensor to its third dimension
For example, there is a 3-d tensor, I want to run the conv1d calculation on its third dimension, import torch import torch.nn as nn x = torch.rand(4,5,6) conv1d =nn.Conv1d(in_channels=1,out_channels=2,kernel_size=5,stride=3,padding=0) y = conv1d(x) I hope the shape of y is (4,5,2,-1), but I get an error Given groups=...
To use Conv1d you need your input to have 3 dimensions: [batch_size, in_channels, data_dimension] So, this would work: x = torch.rand(4, 1, 50) # [batch_size=4, in_channels=1, data_dimension=50] conv1d = nn.Conv1d(in_channels=1,out_channels=2,kernel_size=2,stride=3,padding=0) x = conv1d(x) print(x.shape) # Will outpu...
https://stackoverflow.com/questions/64240012/
Why does the evaluation loss increases when training a huggingface transformers NER model?
Training a huggingface transformers NER model according to the documentation, the evaluation loss increases after a few epochs, but the other scores (accuracy, precision, recall, f1) continuously getting better. The behaviour seems unexpected, is there a simple explanation for this effect? Can this depend on the given ...
Accuracy and loss are not necessarily exactly (inversely) correlated. The loss function is often an approximation of the accuracy function - unlike accuracy, the loss function must be differentiable. A good explanation can be found here.
https://stackoverflow.com/questions/64313576/
element-wise operation in pytorch
I have two Tensors A and B, A.shape is (b,c,100,100), B.shape is (b,c,80,80), how can I get tensor C with shape (b,c,21,21) subject to C[:, :, i, j] = torch.mean(A[:, :, i:i+80, j:j+80] - B)? I wonder whether there's an efficient way to solve this? Thanks very much.
You should use an average pool to compute the sliding window mean operation. It is easy to see that: mean(A[..., i:i+80, j:j+80] - B) = mean(A[..., i:i+80, j:j+80]) - mean(B) Using avg_pool2d: import torch.nn.functional as nnf C = nnf.avg_pool2d(A, kernel_size=80, stride=1, padding=0) - torch.mean(B, dim=(2,3), keepd...
https://stackoverflow.com/questions/64313895/
The size of tensor a (707) must match the size of tensor b (512) at non-singleton dimension 1
I am trying to do text classification using pretrained BERT model. I trained the model on my dataset, and in the phase of testing; I know that BERT can only take to 512 tokens, so I wrote if condition to check the length of the test senetence in my dataframe. If it is longer than 512 I split the sentence into sequences...
This is because, BERT uses word-piece tokenization. So, when some of the words are not in the vocabulary, it splits the words to it's word pieces. For example: if the word playing is not in the vocabulary, it can split down to play, ##ing. This increases the amount of tokens in a given sentence after tokenization. You ...
https://stackoverflow.com/questions/64320883/
Correct way to feed data to RNN in PyTorch
I have a data sequence a which is of shape [seq_len, 2], seq_len is the length of the sequence. There is time correlation among elements of a[:, 0] and a[:, 1], but a[:, 0] and a[:, 1] are independent of each other. For training I prepare data of shape [batch_size, seq_len, 2]. The initialization of BRNN that I use is ...
The question is how, if at all, your data contributes to the overall optimization problem. You said that elements of a[:, 0] are time-correlated and elements of a[:, 1] are time-correlated. Are a[i, 0] and a[i, 1] time-correlated? Does it makes sense for both sequences to be set together? If, for example, you are tryi...
https://stackoverflow.com/questions/64329449/
How to stop importing line arguments with imported file
I have two programs train.py and predict.py and I am importing a trained model from train to predict. Both programs accept line arguments and train runs fine, but when I run predict with its line arguments, an error occurs that I haven't typed in the arguments required by train.py. How I can solve this?
Your question could use some more context. But here is what suspect might be happenning : context When you import a file (module), its content is executed. If your file only contain declarations (such as variable, class and function definitions) all is good, and you can use them from the place you wrote your import sta...
https://stackoverflow.com/questions/64355327/
Python3 Pytorch RuntimeError on GCP - no msg
My System I am running a neural network training on using Python 3.6.9 with pytorch 1.6.0 I am using a google cloud platform N1 Server with a Tesla T4, 2 cores CPU, 12GB RAM. This is on an Ubuntu 18.04 image. Problem When my code reaches the training line I get the following RuntimeError with no real explanation that I...
Anthony Leo thank you so much for your detailed answer! Unfortunately this ended up being a problem with one of the modules I installed while setting up my server. This did not end up being a problem of the server itself or of my code, I just installed a module incorrectly while setting up. I am sorry for all the time ...
https://stackoverflow.com/questions/64356499/
Command Errored Exit Status 1: - Pytorch Object Detection
I tried to follow this tutorial to learn how to run my own object detection, but I am running into an error that I can't seem to fix. I found a solution on some git hubs issues pages. They suggested running: !pip install git+https://github.com/philferriere/cocoapi.git, but I still get the same error. I am using Google ...
This is what is written in https://github.com/cocodataset/cocoapi To install: For Python, run "make" under coco/PythonAPI So you cannot do pip install even in local. Follow these steps in your google colaboratory to install, !git clone https://github.com/cocodataset/cocoapi.git # by default you are in /cont...
https://stackoverflow.com/questions/64356845/
Batch-wise beam search in pytorch
I'm trying to implement a beam search decoding strategy in a text generation model. This is the function that I am using to decode the output probabilities. def beam_search_decoder(data, k): sequences = [[list(), 0.0]] # walk over each step in sequence for row in data: all_candidates = list() ...
Below is my implementation, which may be a little bit faster than the for loop implementation. import torch def beam_search_decoder(post, k): """Beam Search Decoder Parameters: post(Tensor) – the posterior of network. k(int) – beam size of decoder. Outputs: indic...
https://stackoverflow.com/questions/64356953/
RuntimeError: Can only calculate the mean of floating types. Got Byte instead. for mean += images_data.mean(2).sum(0)
I have the following pieces of code: # Device configuration device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') seed = 42 np.random.seed(seed) torch.manual_seed(seed) # split the dataset into validation and test sets len_valid_set = int(0.1*len(dataset)) len_train_set = len(dataset) - len_valid_set...
As the error says, your images_data is a ByteTensor, i.e. has dtype uint8. Torch refuses to compute the mean of integers. You can convert the data to float with: (images_data * 1.0).mean(2) Or torch.Tensor.float(images_data).mean(2)
https://stackoverflow.com/questions/64358283/
Run pytorch in pyodide?
Is there any way I can run the python library pytorch in pyodide? I tried installing pytorch with micropip but it gives this error message: Couldn't find a pure Python 3 wheel for 'pytorch'
In Pyodide micropip only allows to install pure python wheels (i.e. that don't have compiled extensions). The filename for those wheels ends with none-any.whl (see PEP 427). If you look at Pytorch wheels currently available on PyPi, their filenames ends with e.g. x86_64.whl so it means that they would only work on the ...
https://stackoverflow.com/questions/64358372/
I get a tensor of 600 values instead of 3 values for mean and std of train_loader in PyTorch
I am trying to Normalize my images data and for that I need to find the mean and std for train_loader. mean = 0.0 std = 0.0 nb_samples = 0.0 for data in train_loader: images, landmarks = data["image"], data["landmarks"] batch_samples = images.size(0) images_data = images.view(batch_sampl...
First, the weird shape you get for your mean and std ([600]) is unsuprising, it is due to your data having the shape [8, 600, 800, 3]. Basically, the channel dimension is the last one here, so when you try to flatten your images with # (N, 600, 800, 3) -> [view] -> (N, 600, 2400 = 800*3) images_data = images.view...
https://stackoverflow.com/questions/64362402/
how to fix the torch.cuda.is_available() False problem without restarting the machine?
I have: $ python Python 3.7.6 (default, Jan 8 2020, 19:59:22) [GCC 7.3.0] :: Anaconda, Inc. on linux Type "help", "copyright", "credits" or "license" for more information. >>> import torch >>> torch.cuda.is_available() False >>> quit() $ nvidia-smi W...
This happens quite often to ubuntu users (I am not so sure about other distros). I have noticed this behavior especially when I leave my machine on sleep. Without restarting you could run the following commands as mentioned in this thread sudo rmmod nvidia_uvm sudo modprobe nvidia_uvm
https://stackoverflow.com/questions/64363633/
Training Sparse Autoencoders
My dataset consists of vectors that are massive. The data points are all mostly zeros with ~3% of the features being 1. Essentially my data is super sparse and I am attempting to train an autoencoder however my model is learning just to recreate vectors of all zeros. Are there any techniques to prevent this? I have ...
It seems like you are facing a severe "class imbalance" problem. Have a look at focal loss. This loss is designed for binary classification with severe class imbalance. Consider "hard negative mining": that is, propagate gradients only for part of the training examples - the "hard" ones....
https://stackoverflow.com/questions/64364684/
PyTorch Circular Padding in one Dimension
for a convolution i want to apply a circular padding in one dimension and a zero padding in all other dimension. How can i do this? For the convolution there are 28 channels and fore the the data is described in spherical bins. There are 20 bins for radius times 20 bins for polar times 20 bins for inclination. The circ...
Using numpy, you could do a wrap padding so the array gets wrapped along the second axis: np.pad(x, ((0,0),(1,1)), mode='wrap') array([[3, 1, 2, 3, 1], [6, 4, 5, 6, 4], [9, 7, 8, 9, 7]])
https://stackoverflow.com/questions/64368682/
Trying to use Tensorboard on Google Colab
The page below gives informations about Tensorboard: https://pytorch.org/docs/stable/tensorboard.html I am using Google Colab and when i write the following instructions(which are in the link above): !pip install tensorboard tensorboard --logdir=runs it sends me the following error message: File "<ipython-inp...
As explained in How to use Tensorboard with PyTorch in Google Colab. In Google Colab you should start Tensorboard magic at the start of your code with: %load_ext tensorboard and after you define a summary file you need to insatiate Tensorboard with %tensorboard --logdir $tensorboard_dir where Tensorboard dir is a scr...
https://stackoverflow.com/questions/64372169/
How can I repartition RDD by key and then pack it to shards?
I have many files containing millions of rows in format: id, created_date, some_value_a, some_value_b, some_value_c This way of repartitioning was super slow and created for me over million of small ~500b files: rdd_df = rdd.toDF(["id", "created_time", "a", "b", "c&quot...
You can repartition by adding a Random Salt key. val totRows = rdd_df.count val maxRowsForAnId = rdd_df.groupBy("id").count().agg(max("count")) val numParts1 = totRows/maxRowsForAnId val totalUniqueIds = rdd_df.select("id").distinct.count val numParts2 = totRows/(10000*totalUniqueIds) ...
https://stackoverflow.com/questions/64372813/
predict the position of an image in another image
If one image is a part of another image, then how to compute the accurate location in deep learning way? Now I could compute this by extracting and matching key points using OpenCV, but I hope to solve it with neural networks. Any ideas to design the networks and loss functions? Thanks very much.
This is a detection problem. The simplest approach to do it is to create a a network with two heads, one for classification and the other for the bounding box (regression). you feed your network with the image and respective label, and sum the lossess and do a backward. train for some epochs and you'll get your self a ...
https://stackoverflow.com/questions/64382601/
AttributeError: module 'torch' has no attribute 'hstack'
I am following this doc for hstack. a = torch.tensor([1, 2, 3]) b = torch.tensor([4, 5, 6]) torch.hstack((a,b)) But I keep getting the error: AttributeError: module 'torch' has no attribute 'hstack' Here is the torch version that results in this error: torch.__version__ '1.6.0+cpu' What am I doing wrong?
Apparently you are calling a function that does not exist YET in your PyTorch version --this is what the error message is about. Your link points to the help page related to developers preview: note .8.0a0+342069f version number in the top left corner. When clicking, Click here to view docs for latest stable release. l...
https://stackoverflow.com/questions/64405165/
Size mismatch in fully connected layers
I build the following simply model in pytorch as a first run and I am gettign a size mismatch error that does not make sense as out_feat always equals in_feat for the subsequent layer... class Network(nn.Module): def __init__(self): super(Network,self).__init__() #first linear block s...
Batch normalization works when batch size is greater than 1, so an input of shape (1, 32) won't work. Try a larger batch size, like 2. Moreover, you're trying to use ReLU in the form x = nn.ReLU(x). This is wrong, as nn.ReLU is a layer. This line of code returns you the ReLU layer itself rather than a tensor. Either de...
https://stackoverflow.com/questions/64417660/
Is it possible to add own function in transform.compose in pytorch
I am using a pre-trained Alex model. I am running this model on some random image dataset. I want to convert RGB images to YCbCr images before training. I am wondering is it possible to add a function on my own to transform.compose, For example: transform = transforms.Compose([ ycbcr(), #something like this transfo...
You can pass a custom transformation to torchvision.transform by defining a class. To understand better I suggest that you read the documentations. In your case it will be something like the following: class ycbcr(object): def __call__(self, img): """ :param img: (PIL): Image ...
https://stackoverflow.com/questions/64420379/
What is the difference between a .ckpt and a .pth file in Pytorch?
I am following a code from GitHub that uses Pytorch. The model is saved using : model.save(ARGS.working_dir + '/model_%d.ckpt' % (epoch+1)). What is the difference between using .pth and .ckpt in Pytorch?
There is no difference. the extension in Pytorch models that you see is something random. You can choose anything. People usually use pth to indicate a PyTorcH model (and hence .pth). but then again its completely up to you on how you want to save your model.
https://stackoverflow.com/questions/64456843/
OSError: libcurand.so.10: cannot open shared object file: No such file or directory
I am working on Nvidia Jetson Tx2 (with JETPACK 4.2) and installed the pytorch following this link. When I am importing torch in python its giving me an error OSError: libcurand.so.10: cannot open shared object file: No such file or directory I have tried all the options but nothing worked. export LD_LIBRARY_PATH=$LD_L...
emm I found this answer as followed... https://forums.developer.nvidia.com/t/mounting-cuda-onto-l4t-docker-image-issues-libcurand-so-10-cannot-open-no-such-file-or-directory/121545 The key is : "You can use JetPack4.4 for CUDA 10.2 and JetPack4.3 for CUDA 10.0." Maybe downloading Pytorch v1.4.0 and Jetpack 4....
https://stackoverflow.com/questions/64482976/
Use CrossEntropyLoss with LogSoftmax
From the Pytorch documentation, CrossEntropyLoss combines LogSoftMax and NLLLoss together in one single class But I am curious; what happens if we use both CrossEntropyLoss for criterion and LogSoftMax in my classifier: model_x.fc = nn.Sequential (nn.Linear(num_ftrs, 2048, bias=True), nn.ReLU(), ...
TL;DR: You will decrease the expressivity of the model because it only can produce relatively flat distribution. What you suggest in the snippet actually means applying the softmax normalization twice. This will give you a distribution with the same rank of probabilities, but it will be much flatter and it will prevent...
https://stackoverflow.com/questions/64494819/
Is there a way to convert the quint8 pytorch format to np.uint8 format?
I'm using the code below to get the quantized unsiged int 8 format in pytorch. However, I'm not able to convert the quant variable to the to np.uint8. Is there possible to do that? import torch quant = torch.quantize_per_tensor(torch.tensor([-1.0, 0.352, 1.321, 2.0]), 0.1, 10, torch.quint8)
This can be done using torch.int_repr() import torch import numpy as np # generate a test float32 tensor float32_tensor = torch.tensor([-1.0, 0.352, 1.321, 2.0]) print(f'{float32_tensor.dtype}\n{float32_tensor}\n') # convert to a quantized uint8 tensor. This format keeps the values in the range of # the float32 forma...
https://stackoverflow.com/questions/64503533/
how to convert outlogits to tokens?
i have a forward function in allenNlp given by : def forward(self, input_tokens, output_tokens): ''' This is the main process of the Model where the actual computation happens. Each Instance is fed to the forward method. It takes dicts of tensors as input, with same keys as the fields in your Instan...
In allennlp you have access to the self.vocab attribute with Vocabulary. get_token_from_index. Usually to select a token from the logits one would apply a softmax (in order to have all the probability summing to 1) and then pick the most probable one. If you want to decode sequences from a model maybe you should look i...
https://stackoverflow.com/questions/64513991/
What is the correct way to use a PyTorch Module inside a PyTorch Function?
We have a custom torch.autograd.Function z(x, t) which computes an output y in a way not amenable to direct automatic differentiation, and have computed the Jacobian of the operation with respect to its inputs x and t, so we can implement the backward method. However, the operation involves making several internal call...
I guess you could create a custom functor that inherits torch.autograd.Function and make the forward and backward methods non-static (i.e remove the @staticmethod in this example so that net could be an attribute of your functor. that would look like class MyFunctor(torch.nn.autograd.Function): def __init(net): ...
https://stackoverflow.com/questions/64516138/
do I have to add softmax in def forward when I use torch.nn.CrossEntropyLoss
https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html When I read the contents above, I understood that torch.nn.CrossEntropy already computes exp score of the last layer. So I thought the forward function doesn't have to include softmax. For example, return self.fc(x) rather than return nn.softmax(s...
JHPark, You are correct - with torch.nn.CrossEntropyLoss there is no need to include softmax layer. If one does include softmax it will still lead to proper classification result, since softmax does not change which element has max score. However, if applied twice, it may distort relative levels of the outputs, making...
https://stackoverflow.com/questions/64519911/
Can I use BERT as a feature extractor without any finetuning on my specific data set?
I'm trying to solve a multilabel classification task of 10 classes with a relatively balanced training set consists of ~25K samples and an evaluation set consists of ~5K samples. I'm using the huggingface: model = transformers.BertForSequenceClassification.from_pretrained(... and obtain quite nice results (ROC AUC = 0...
From my experience, you are going wrong in your assumption an out-of-the-box pre-trained BERT model (without any fine-tuning) should serve as a relatively good feature extractor for the classification layers. I have noticed similar experiences when trying to use BERT's output layer as a word embedding value with litt...
https://stackoverflow.com/questions/64526841/
Pytorch datatype/dimension confusion TypeError: 'Tensor' object is not callable
This piece of code is originally written in numpy and I'm trying to utilise GPU computation by rewriting it in pytorch, but as I'm new to pytorch a lot of problems occured to me. Firstly I'm confused by the dimension of the tensors. Sometimes after operating on the tensors, only transposing the tensor would fix the pro...
ar = torch.stack( (index, vector([index, 1]), prob([index, 1]), CumProb([index, 1])) ) # Problems occur here vector is of type torch.Tensor. It has no __call__ defined. You are going for vector(...) (vector([index,1])) while you should slice the data directly like this: vector[index, 1]. Same goes for prob and Cu...
https://stackoverflow.com/questions/64533134/
What makes BertGeneration and/or RobertaForCausalLM causal models? Where does the causal attention masking happen?
I am trying to use RobertaForCausalLM and/or BertGeneration for causal language modelling / next-word-prediction / left-to-right prediction. I can't seem to figure out where the causal masking is happening? I want to train teacher forcing with the ground-truth labels, but no information from future tokens to be include...
I have found it. It happens in get_extended_attention_mask in modeling utils. Consider this question solved :slight_smile:
https://stackoverflow.com/questions/64537339/
How can I calculate FLOPs and Params without 0 weights neurons affected?
My Prune code is shown below, after running this, I will get a file named 'pruned_model.pth'. import torch from torch import nn import torch.nn.utils.prune as prune import torch.nn.functional as F from cnn import net ori_model = '/content/drive/My Drive/ECG_weight_prune/checkpoint_dir/model.pth' save_path = '/content/...
One thing you could do is to exclude the weights below a certain threshold from the FLOPs computation. To do so you would have to modify the flop counter functions. I'll provide examples for the modification for fc and conv layers below. def linear_flops_counter_hook(module, input, output): input = input[0] out...
https://stackoverflow.com/questions/64551002/
Calculate covariance of torch tensor (2d feature map)
I have a torch tensor with shape (batch_size, number_maps, x_val, y_val). The tensor is normalized with a sigmoid function, so within range [0, 1]. I want to find the covariance for each map, so I want to have a tensor with shape (batch_size, number_maps, 2, 2). As far as I know, there is no torch.cov() function as in ...
You could try the function suggested on Github: def cov(x, rowvar=False, bias=False, ddof=None, aweights=None): """Estimates covariance matrix like numpy.cov""" # ensure at least 2D if x.dim() == 1: x = x.view(-1, 1) # treat each column as a data point, each row as...
https://stackoverflow.com/questions/64554658/
Why multiplication on GPU is slower than on CPU?
Here is my code (simulate the feed-forward neural network): import torch import time print(torch.cuda.is_available()) # True device = torch.device('cuda:0' ) a = torch.tensor([1,2,3,4,5,6]).float().reshape(-1,1) w1 = torch.rand(120,6) w2 = torch.rand(1,120) b1 = torch.rand(120,1) b2 = torch.rand(1,1).reshape(1,1) ...
The reason can be a lot of things: Your model is simple. For GPU calculation there is the cost of memory transfer to and from the GPU's memory You calculation is on a small data batch, probably with bigger data sample you should see better performance on GPU than CPU We should not forget the caching, you calculate the...
https://stackoverflow.com/questions/64556682/
What do you use to access CSV data on S3 and other object storage providers as a PyTorch Dataset?
My dataset is stored as a collection of CSV files in an Amazon Web Services (AWS) Simple Storage Service (S3) bucket. I'd like to train a PyTorch model based on this data but the built-in Dataset classes do not provide native support for object storage services like S3 or Google Cloud Storage (GCS), Azure Blob storage,...
Check out ObjectStorage Dataset which has support for object storage services like S3 and GCS osds.readthedocs.io/en/latest/gcs.html You can run pip install osds to install it and then point it at your S3 bucket to instantiate the PyTorch Dataset and DataLoader using something like from osds.utils import ObjectStorage...
https://stackoverflow.com/questions/64580099/
I have an error on Pytorch and in particular with nllloss
I want to appply the criterion, where criterion = nn.NLLLoss() I apply it on output and labels loss = criterion(output.view(-1,1), labels.long()) where: *the shape of the labels labels tensor([ 1, 4, 1, 1, 4, 1, 2, 3, 2, 4, 2, 3, 3, 4, 0, 4]) output tensor([ 0.1829, 0.1959, 0.1909, 0.1895, 0...
Your label and output shapes must be [batch_size] and [batch_size, n_classes] respectively.
https://stackoverflow.com/questions/64581993/
How to index intermediate dimension with an index tensor in pytorch?
How can I index a tensor t with n dimensions with an index tensor of m < n dimensions, such that the last dimensions of t are preserved? The index tensor is shaped equal to tensor t for all dimensions before dimension m. Or in other terms, I want to index intermediate dimensions of a tensor, while keeping all the fo...
In this case, you can do something like this: t[torch.arange(t.shape[0]).unsqueeze(1), index, ...] Full code: import torch t = torch.tensor([[[ 15.2165, -7.9702], [ 0.6646, 5.2844], [-22.0657, -5.9876], [ -9.7319, 11.7384], [ 4.3985, ...
https://stackoverflow.com/questions/64590830/
How to make Intel GPU available for processing through pytorch?
I'm using a laptop which has Intel Corporation HD Graphics 520. Does anyone know how to it set up for Deep Learning, specifically Pytorch? I have seen if you have Nvidia graphics I can install cuda but what to do when you have intel GPU?
PyTorch doesn't support anything other than NVIDIA CUDA and lately AMD Rocm. Intels support for Pytorch that were given in the other answers is exclusive to xeon line of processors and its not that scalable either with regards to GPUs. Intel's oneAPI formerly known ad oneDNN however, has support for a wide range of har...
https://stackoverflow.com/questions/64593792/
Accessing functions in the class modules of nn.Sequential
When running nn.Sequential, I include a list of class modules (which would be layers of a neural network). When running nn.Sequential, it calls forward functions of the modules. However each of the class modules also has a function which I would like to access when the nn.Sequential runs. How can I access and run this ...
You can use a hook for that. Let's consider the following example demonstrated on VGG16: This is the network architecture: Say we want to monitor the input and output for layer (2) in the features Sequential (that Conv2d layer you see above). For this matter we register a forward hook, named my_hook which will be cal...
https://stackoverflow.com/questions/64606524/
RuntimeError: Expected hidden[0] size (1, 1, 512), got (1, 128, 512) for LSTM pytorch
I trained the LSTM with a batch size of 128 and during testing my batch size is 1, why do I get this error? I'm suppose to initialize the hidden size when doing testing? Here is the code that i'm using, I initialize the hidden state init_hidden function as (number_of_layers, batch_size, hidden_size) since batch_first=T...
please edit your post and add code. How did you initialize the hidden-state? What does you model look like. hidden[0] is not your hidden-size, its the hidden-state of the lstm. The shape of the hidden-state has to be initialized like this: hidden = ( torch.zeros((batch_size, layers, hidden_size)), torch.zeros((layers, ...
https://stackoverflow.com/questions/64629583/
Can´t install Pytorch on PyCharm: No matching distribution found for torch==1.7.0+cpu
I tried multiple times installing Pytorch on Pycharm. I used the code that the pytorch web site give you for a specific configuration. I use this one: enter image description here Then I copied this information on Pycharm Terminal and I get this message: (venv) D:\Usuarios\AuCap\Documents\mnist>pip install torch==1....
Downgrade your Python version as python3.9 is not supported by PyTorch right now (python3.8 is fine though). See this issue, it will be supported in subsequent releases. You can build your own PyTorch from source if you wish though.
https://stackoverflow.com/questions/64636103/
object detection: is object in the photo, python
I am trying to detect plants in the photos, i've already labeled photos with plants (with labelImg), but i don't understand how to train model with only background photos, so that when there is no plant here model can tell me so. Do I need to set labeled box as the size of image? p.s. new to ml so don't be rude, please...
I recently had a problem where all my training images were zoomed in on the object. This meant that the training images all had very little background information. Since object detection models use space outside bounding boxes as negative examples of these objects, this meant that the model had no background knowledge....
https://stackoverflow.com/questions/64641364/
PyTorch dll issues for Caffe2
I am using a Windows 10 Machine and after re-installing Anaconda and all of the packages I had previously, including torchvision, torch and necessary dependencies, I am still getting this error: OSError: [WinError 127] The specified procedure could not be found. Error loading "C:\Users\XXX\Anaconda3\envs\XXX\lib\s...
After a long time trying many things with Anaconda I decided to use bare python instead and I installed Python 3.8.6 and installed PyTorch from the link you provided and it finally worked even with CUDA support. Make sure to completely remove all Anaconda/Other Python version scripts from your path to ensure only the 3...
https://stackoverflow.com/questions/64653750/
Saving and reload huggingface fine-tuned transformer
I am trying to reload a fine-tuned DistilBertForTokenClassification model. I am using transformers 3.4.0 and pytorch version 1.6.0+cu101. After using the Trainer to train the downloaded model, I save the model with trainer.save_model() and in my trouble shooting I save in a different directory via model.save_pretrained...
Do you tried loading the by the trainer saved model in the folder: mitmovie_pt_distilbert_uncased/results The Huggingface trainer saves the model directly to the defined output_dir.
https://stackoverflow.com/questions/64663385/
complex functions that already support autograd - Pytorch
I am using this customized function to reshape my tensors in the customized loss function. def reshape_fortran(x, shape): if len(x.shape) > 0: x = x.permute(*reversed(range(len(x.shape)))) return x.reshape(*reversed(shape)).permute(*reversed(range(len(shape)))) Though, I receive this error: RuntimeError: _unsaf...
Complex Autograd was in Beta as of version 1.8, but is now stable and should fully support such operations as of 1.9.
https://stackoverflow.com/questions/64689253/
Unable to install PyTorch on Windows 10 (x86_64) with Cuda 11.0 using pip
I tried following the instructions on pytorch.org and ran the command provided by them for my configuration, but I get the following error ERROR: Could not find a version that satisfies the requirement torch===1.7.0+cu110 (from versions: 0.1.2, 0.1.2.post1, 0.1.2.post2) ERROR: No matching distribution found for torch==...
Just go to https://pytorch.org/get-started/locally/ and get PyTorch for any platform using conda or pip.
https://stackoverflow.com/questions/64691517/
IndexError: index_select(): Index is supposed to be a vector
for batch_id, (data, target) in enumerate(tqdm(train_loader)): print(target) print('Entered for loop') target = torch.sparse.torch.eye(10).index_select(dim=0, index=target) data, target = Variable(data), Variable(target) The line which contains the index_select function gives this e...
If you would look at the shape of your target variable, you would find that it is a 2D tensor of shape: target.shape # torch.Size([10, 1]) Error message is a bit confusing, but in essence index should be a 1D tensor (vector). So using .squeeze method would make: target.squeeze().shape # torch.Size([10]) and index_sel...
https://stackoverflow.com/questions/64693739/
PyTorch is tiling images when loaded with Dataloader
I am trying to load an Images Dataset using the PyTorch dataloader, but the resulting transformations are tiled, and don't have the original images cropped to the center as I am expecting them. transform = transforms.Compose([transforms.Resize(224), transforms.CenterCrop(224), ...
Pytorch stores tensors in channel-first format, so a 3 channel image is a tensor of shape (3, H, W). Matplotlib expects data to be in channel-last format i.e. (H, W, 3). Reshaping does not rearrange the dimensions, for that you need Tensor.permute. plt.imshow(images[6].permute(1, 2, 0))
https://stackoverflow.com/questions/64705364/
clever image augmentation - random zoom out
i'm building a CNN to identify facial keypoints. i want to make the net more robust, so i thought about applying some zoom-out transforms because most pictures have about the same location of keypoints, so the net doesn't learn much. my approach: i want augmented images to keep the original image size so apply MaxPool2...
I suggest to use torchvision.transforms.RandomResizedCrop as a part of your Compose statement. which will give you random zooms AND resize the resulting the images to some standard size. This avoids issues in both your questions.
https://stackoverflow.com/questions/64727718/
Defining Loss function in pytorch
I have to define a huber loss function which is this: This is my code def huber(a, b): res = (((a-b)[abs(a-b) < 1]) ** 2 / 2).sum() res += ((abs(a-b)[abs(a-b) >= 1]) - 0.5).sum() res = res / torch.numel(a) return res ''' yet, it is not working properly. Do you have any idea what is wrong?
Huber loss function already exists in PyTorch under the name of torch.nn.SmoothL1Loss. Follow this link https://pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html for more!
https://stackoverflow.com/questions/64735517/
How to Use Class Weights with Focal Loss in PyTorch for Imbalanced dataset for MultiClass Classification
I am working on Multiclass Classification (4 classes) for Language Task and I am using the BERT model for classification task. I am following this blog as reference. My BERT Fine Tuned model returns nn.LogSoftmax(dim=1). My data is pretty imbalanced so I used sklearn.utils.class_weight.compute_class_weight to compute w...
You may find answers to your questions as follows: Focal loss automatically handles the class imbalance, hence weights are not required for the focal loss. The alpha and gamma factors handle the class imbalance in the focal loss equation. No need of extra weights because focal loss handles them using alpha and gamma m...
https://stackoverflow.com/questions/64751157/
Pytorch installation could not find a version that satisfies the requirement
When i tried to install Pytorch in the way they suggest on their website: pip install torch===1.7.0 torchvision===0.8.1 torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html this is the error that appear: ERROR: Could not find a version that satisfies the requirement torch===1.7.0 (from versions: 0....
Just wanted to start out by letting all the mac, linux, and python 3.8.x- users here know that adding "https://" to the command does not solve the problem: Proof that it doesn't help or solve anything Here's why: OP, you probably have python 3.9 installed on your machine. Unfortunately, Python 3.9 is not yet ...
https://stackoverflow.com/questions/64756531/
Pytorch : W ParallelNative.cpp:206
I'm trying to use a pre-trained template on my image set by following the tutorial right here : https://pytorch.org/tutorials/beginner/finetuning_torchvision_models_tutorial.html Only I always get this "error" when I run my code and the console locks up : [W ParallelNative.cpp:206] Warning: Cannot set number ...
I have the same problem. Mac. Python 3.6 (also reproduces on 3.8). Pytorch 1.7. It seems that with this error dataloaders don't (or can't) use parallel computing. You can remove the error (this will not fix the problem) in two ways. If you can access your dataloaders, set num_workers=0 when creating a dataloader Set e...
https://stackoverflow.com/questions/64772335/
Indexing list of tensors
I have two identical lists of tensors (with different sizes) except that for the first one all of the tensors are assigned to the cuda device. For example: list1=[torch.tensor([0,1,2]).cuda(),torch.tensor([3,4,5,6]).cuda(),torch.tensor([7,8]).cuda()] >>> list1 [tensor([0, 1, 2], device='cuda:0'), tensor([3, 4,...
np.array trys to convert each of the elements of a list into a numpy array. This is only supported for CPU tensors. The short answer is you can explicitly instruct numpy to create an array with dtype=object to make the CPU case works. To understand what exactly is happening lets take a closer look at both cases. Case 1...
https://stackoverflow.com/questions/64775560/
Whats the equivalent of tf.keras.Input() in pytorch?
can someone tell me what the equivalent of tf.keras.Input() in pytorch is? At the documentation it says, "Initiates a Keras Tensor", so does it just creates a new empty tensor? Thanks
There's no equivalent in PyTorch to the Keras' Input. All you have to do is pass on the inputs as a tensor to the PyTorch model. For eg: If you're working with a Conv net: # Keras Code input_image = Input(shape=(32,32,3)) # An input image of 32x32x3 (HxWxC) feature = Conv2D(16, activation='relu', kernel_size=(3, 3))(i...
https://stackoverflow.com/questions/64780641/
Optuna Pytorch: returned value from the objective function cannot be cast to float
def autotune(trial): cfg= { 'device' : "cuda" if torch.cuda.is_available() else "cpu", # 'train_batch_size' : 64, # 'test_batch_size' : 1000, # 'n_epochs' : 1, # 'seed' : 0, # 'log_interval' : 100, # 'save_model' : False, ...
This exception is raised because the objetive function from your study must return a float. In your case, the problem is in this line: study.optimize(autotune, n_trials=1) The autotune function you defined before does not return a value and cannot be used for optimization. How to fix? For hyperparameter search, the au...
https://stackoverflow.com/questions/64781266/
How to implement Softmax regression with pytorch?
I am working on a uni assignment where I need to implement Softmax Regression with Pytorch. The assignment says: Implement Softmax Regression as an nn.Module and pipe its output with its output with torch.nn.Softmax. As I am new to pytorch, I am not sure how to do it exactly. So far I have tried: class SoftmaxRegressi...
As far as I understand, the assignment wants you to implement your own version of the Softmax function. But, I didn't get what do you mean by and pipe its output with torch.nn.Softmax. Are they asking you to return the output of your custom Softmax along with torch.nn.Softmax from your custom nn.Module? You could do th...
https://stackoverflow.com/questions/64783744/
Is NN just Bad at Solving this Simple Linear Problem, or is it because of Bad Training?
I was trying to train a very straightforward (I thought) NN model with PyTorch and skorch, but the bad performance really baffles me, so it would be great if you have any insight into this. The problem is something like this: there are five objects, A, B, C, D, E, (labeled by their fingerprint, e.g.(0, 0) is A, (0.2, ...
First thing I've noticed: super(SingleNN, self).__init__() should be super(NN, self).__init__() instead. Change that and let me know if you still get any errors.
https://stackoverflow.com/questions/64795826/
Extracting feature vector for grey images via ResNet18: output with shape [1, 224, 224] doesn't match the broadcast shape [3, 224, 224]
I have 600x800 images that have only 1 channel. I am trying to use pre-trained ResNet18 to extract their features however the code expects 3 channel: import torch import torchvision import torchvision.models as models from PIL import Image img = Image.open("labeled-data/train_moth/moth/frame163.png") # Loa...
many models (almost all models) from torchvision module expects our input to be in 3 channel. So when ever you are using pretrained model , just convert your image to RGB scale. So if i see your code just change this img = Image.open("labeled-data/train_moth/moth/frame163.png") to this img = Image.open(&quot...
https://stackoverflow.com/questions/64796538/
Build KNN graph over some subset of Node features
I have a point cloud that I want to use a graph neural network on. Each point in the point cloud is characterised by its positional coordinates as well as it's color. So a single node is (X, Y, Z, C). Now I want to apply an Edge Convolution on this (as described in the DGL Edge-Conv example, and to do it I should build...
Supposing you have a tensor pc of shape (NUM_POINTS, 4) where each row is (X, Y, Z, C), then you could use sklearn as follows: from sklearn.neighbors import NearestNeighbors import dgl k = 3 # number of neighbours you want neigh = NearestNeighbors(n_neighbors=k) neigh.fit(pc[:, :3].numpy()) # selects only (X, Y, Z) ...
https://stackoverflow.com/questions/64800266/
trying to build pytorch 1.0.0 cuda 10.2 with support for old gpu (3.0)
I'm playing with a couple of projects that explicitly require pytorch == 1.0.0, but I have an old graphics card that only supports cuda 3.0 so I'm using the cpu, which is very slow, being the graphics card a dual gpu I decided to give a try and build pytorch from the sources with support for 3.0 (I have planned to upda...
Apparently the problem was that both libcusparse and aten/src/ATen/native/sparse/cuda/SparseCUDABlas.cu implement cusparseGetErrorString() and for version >= 10.2 the one in the library should be used. --- aten/src/ATen/native/sparse/cuda/SparseCUDABlas.cu.orig 2020-11-16 12:13:17.680023134 +0000 +++ aten/src/ATen/n...
https://stackoverflow.com/questions/64853878/
How to convert pip install to Poetry file?
With hours of research, I still can't figure out a way to convert this pip install cmd to pyproject.toml file. I'm trying to install PyTorch. pip install torch==1.7.0+cpu torchvision==0.8.1+cpu torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html This is what I got at the moment (Completely Wrong!) ...
Previous solution didnt work for me as mentioned in this poetry issue#2543. So what worked for me in the meantime was to upgrade to version 1.2(preview) which addresses that issue. Install poetry 1.2 curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/install-poetry.py | python - --preview Add below...
https://stackoverflow.com/questions/64871630/
LU is not same as A when I used torch.solver
let A=[[3,2],[1,-3]] and B=[[3],[-10]] and solve equation AX=B by using torch.solve: X, LU = torch.solve(B,A) Then I got X=[[-1],[3]] and LU=[[3,2],[0.333,-3.666]]. According to definition of LU decompose, LU must be same as A, however they aren't same. Can anyone explain this??? Thank you
The representation you got is a compact way of representing the lower trainagular matrix L and the upper trainagular matrix U. You can use torch.tril and torch.triu to get these matrices explicitly: L = torch.tril(LU, -1) + torch.eye(LU.shape[-1]) U = torch.triu(LU) verify: In [*]: L Out[*]: tensor([[1.0000, 0.0000],...
https://stackoverflow.com/questions/64874981/
What is the correct input to LSTM?
I have tensors of varying length . These tensors are data for different time period. My aim is to get final output of the lstm. torch.randn(4)-Time1 torch.randn(3,4)-Time2 torch.randn(4,4)-Time3 These are my data, what is the input to LSTM from here? , my aim is to get the final output from the lstm For example, thi...
You can access the last hidden layer as hn[-1] output = self.ffn(hn[-1])
https://stackoverflow.com/questions/64875981/
How to run a pytorch project with CPU?
A Pytorch project is supposed to run on GPU. I want to run it on my laptop only with CPU. There are a lot of places calling .cuda() on models, tensors, etc., which fail to execute when cuda is not available. Is it possible to do it without changing the code everywhere?
Here's the simplest fix I can think of: Put the following line near the top of your code: device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') Do a global replace. Change .cuda() to .to(device), where device is the variable set in step 1.
https://stackoverflow.com/questions/64897730/
How to write a contextmanager to throw and catch errors
I want to catch the runtime error CUDA out of memory on multiple occasions in my code. I do this to then rerun the whole training workflow with lower batch size. What is the best way to do that? I am currently doing this: try: result = model(input) # if the GPU runs out of memory, start the experiment again with a ...
Using a context manager is about properly acquiring and releasing a resource. Here you don't really have any resource that you are acquiring and releasing, so I don't think a context manager is appropriate. How about just using a function? def try_compute_model(input): try: return model(input) # if the ...
https://stackoverflow.com/questions/64900712/
How to use fairseq interactive.py non-interactively?
I am trying to translate from English to Arabic using Fairseq. But the interactive.py script translate pieces of text fragment on-the-fly. But I need to use it as reading an input text file and writing output text file write. I referred this GitHub issue - https://github.com/pytorch/fairseq/issues/858 But it doesn't cl...
fairseq-interactive can read lines from a file with the --input parameter, and it outputs translations to standard output. So let's say I have this input text file source.txt (where every sentence to translate is on a separate line): Hello world! My name is John You can run: fairseq-interactive --input=source.txt [all...
https://stackoverflow.com/questions/64902144/
PyTorch: Vectorizing patch selection from a batch of images
Suppose I have a batch of images as a tensor, for example: images = torch.zeros(64, 3, 1024, 1024) Now, I want to select a patch from each of those images. All the patches are of the same size, but have different starting positions for each image in the batch. size_x = 100 size_y = 100 start_x = torch.zeros(64) start_...
You can use torch.take to get rid of a for loop. But first, an array of indices should be created with this function def convert_inds(img_a,img_b,patch_a,patch_b,start_x,start_y): all_patches = np.zeros((len(start_x),3,patch_a,patch_b)) patch_src = np.zeros((patch_a,patch_b)) inds_src = np.arange(...
https://stackoverflow.com/questions/64903931/
Why we need a decoder_start_token_id during generation in HuggingFace BART?
During the generation phase in HuggingFace's code: https://github.com/huggingface/transformers/blob/master/src/transformers/generation_utils.py#L88-L100 They pass in a decoder_start_token_id, I'm not sure why they need this. And in the BART config, the decoder_start_token_id is actually 2 (https://huggingface.co/facebo...
You can see in the code for encoder-decoder models that the input tokens for the decoder are right-shifted from the original (see function shift_tokens_right). This means that the first token to guess is always BOS (beginning of sentence). You can check that this is the case in your example. For the decoder to understa...
https://stackoverflow.com/questions/64904840/
how to add transformation in pytorch object detection
I'm new to PyTorch & going through the PyTorch object detection documentation tutorial pytorch docx. At their collab version, I made the below changes to add some transformation techniques. First change to the __getitem__ method of class PennFudanDataset(torch.utils.data.Dataset) if self.transforms is not None: ...
I believe the Pytorch transforms only work on images (PIL images or np arrays in this case) and not labels (which are dicts according to the trace). As such, I don't think you need to "tensorify" the labels as in this line target = T.ToTensor()(target) in the __getitem__ function.
https://stackoverflow.com/questions/64905441/
PyTorch: RuntimeError: Input, output and indices must be on the current device
I am running a BERT model on torch. It's a multi-class sentiment classification task with about 30,000 rows. I have already put everything on cuda, but not sure why I'm getting the following run time error. Here is my code: for epoch in tqdm(range(1, epochs+1)): model.train() loss_train_total = 0 ...
You should put your model on the device, which is probably cuda: device = "cuda:0" model = model.to(device) Then make sure the inputs of the model(input) are on the same device as well: input = input.to(device) It should work!
https://stackoverflow.com/questions/64914598/
cuda is not available on my pytorch, but I can't find anything wrong with the version
for some reason I have to use cuda version10.0 instead of upgrading it The version of DriverAPI is higher than RunTimeAPI but somebody told me thats OK Others who asked the same question at last found their version was not match. emmmm not like me details here OS:Windows10 Python 3.7&3.8 both tried result of 'nvcc ...
How did you install it ? I assume with pip. For pytorch I would recommend manually downloading the wheel from https://download.pytorch.org/whl/torch_stable.html and install it with: pip install torch-1.4.0+cu100-cp38-cp38-linux_x86_64.whl Assuming python 3.8 and linux. If you use something different make sure to s...
https://stackoverflow.com/questions/64917109/
Pytorch: use pretrained vectors to initialize nn.Embedding, but this embedding layer is not updated during the training
I initialized nn.Embedding with some pretrain parameters (they are 128 dim vectors), the following code demonstrates how I do this: self.myvectors = gensim.models.KeyedVectors.load_word2vec_format(cfg.vec_dir) self.vec_weights = torch.FloatTensor(self.myvectors.vectors) self.embeds = torch.nn.Embedding.from_pretrained(...
The torch.nn.Embedding.from_pretrained classmethod by default freezes the parameters. If you want to train the parameters, you need to set the freeze keyword argument to False. See the documentation. So you might try this instead: self.embeds = torch.nn.Embedding.from_pretrained(self.vec_weights, freeze=False)
https://stackoverflow.com/questions/64919743/
Training Data Split across GPUs in DDP Pytorch Lightning
Goal: Train a model in Distriubted Data Parallel(DDP) setting using Pytorch Lightning Framework Questions: Training Data Partition: How is data partition across separate GPUs is handled with Pytorch Lightning? Am I supposed to manually partition the data or Pytorch lightning will take care of that? Loss Averaging: Do...
Lightning handles both of these scenarios for you out of the for you but it can be overridden. The code for this can be found in the official github here.
https://stackoverflow.com/questions/64920829/
The result is empty when prediction of Faster RCNN model (Pytorch)
I'm trying to train Faster RCNN model. After training, I try to predict the result of image but the result is empty. My data is w: 1600, h: 800, c: 3, classes: 7, bounding boxes:(x1, y1, x2, y2) My model is below. My model import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from ...
You should change the number of classes to model = FasterRCNN(backbone, num_classes=YOUR_CLASSES+1, # +1 is for the background rpn_anchor_generator=anchor_generator, box_roi_pool=roi_pooler) Remember that the class 0 is reserved for the background, so yo...
https://stackoverflow.com/questions/64931112/
What is the most efficient way to broadcast an operation on slices of PyTorch Tensors?
I have a tensor T of shape (b, r) I want to do an operation for each (r), in a way that it gets parallelized by the GPU The naive implementation, in numpy for simplicity, would look something like: T_dash = np.array([(T[i] - np.max(T[i]) for i in range(T.size[0])]) What would be the best way to do this?
There's a new vmap function available (in the master branch at the time of writing, experimental) that will help do batch operations, where you define the operation to be performed for each element. vmap can be helpful in hiding batch dimensions. In your case, it goes something like def each_elem_fn(tensor): return t...
https://stackoverflow.com/questions/64934952/