instruction
stringlengths
13
150
input
stringlengths
36
29.1k
output
stringlengths
31
29.5k
source
stringlengths
45
45
Dealing with large slowdown when moving PyTorch code to GPU
I have a Graph Neural Network model I have written using Pytorch. On my CPU I am not getting fantastic performance, so I tried to port it over to a V100 GPU I have access to. In this process, I have received a huge performance decrease (around 10times slower). I have two ideas of where might be the issue, but I would ...
Your problem is almost guaranteed to be bound by the memory movement to the GPU, especially since you mention your singular batches. The only ways that may help you speed up the current implementation might be to look into memory maps, which we are not able to see whether or not you are already using them based on the...
https://stackoverflow.com/questions/60189355/
Get the value of '[UNK]' in BERT
I have designed a model based on BERT to solve NER task. I am using transformers library with the "dccuchile/bert-base-spanish-wwm-cased" pre-trained model. The problem comes when my model detect an entity but the token is '[UNK]'. How could I know which is the string behind that token? I know that an unknown token ca...
The tokenizer works in two steps. First, it does pre-tokenization, which is basically splitting on spaces and separating punctuation. Let's have a look at it on a random Czech sentence: tokenizer.basic_tokenizer.tokenize("Kočka leze dírou.") This gives you: ['kocka', 'leze', 'dirou', '.'] In the second step, it app...
https://stackoverflow.com/questions/60192523/
How to make early stopping in image classification pytorch
I'm new with Pytorch and machine learning I'm follow this tutorial in this tutorial https://www.learnopencv.com/image-classification-using-transfer-learning-in-pytorch/ and use my custom dataset. Then I have same problem in this tutorial but I dont know how to make early stopping in pytorch and if do you have better wi...
This is what I did in each epoch val_loss += loss val_loss = val_loss / len(trainloader) if val_loss < min_val_loss: #Saving the model if min_loss > loss.item(): min_loss = loss.item() best_model = copy.deepcopy(loaded_model.state_dict()) print('Min loss %0.2f' % min_loss) epochs_no_improve = 0...
https://stackoverflow.com/questions/60200088/
Subsetting A Pytorch Tensor Using Square-Brackets
I came across a line of code used to reduce a 3D Tensor to a 2D Tensor in PyTorch. The 3D tensor x is of size torch.Size([500, 50, 1]) and this line of code: x = x[lengths - 1, range(len(lengths))] was used to reduce x to a 2D tensor of size torch.Size([50, 1]). lengths is also a tensor of shape torch.Size([50]) cont...
After being quite stumped by the behavior, I did some more digging into this, and found that it is consistent behavior with the indexing of multi-dimensional NumPy arrays. What makes this counter-intuitive is the less obvious fact that both arrays have to have the same length, i.e. in this case len(lengths). In fact, ...
https://stackoverflow.com/questions/60201895/
The result is different when I apply torch.manual_seed before loading cuda() after loading the model
I tried to make sure my code to be reproducible (always get the same results) So I applied below settings before my codes. os.environ['PYTHONHASHSEED'] = str(args.seed) random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.cuda.manual_seed(args.seed) torch.cuda.manual_seed_all(args.seed)...
The Net.cuda() has no effect on the random number generator. Under the hood it just calls cuda() for all of the model parameters. So basically it's multiple calls to Tensor.cuda(). https://github.com/pytorch/pytorch/blob/ecd3c252b4da3056797f8a505c9ebe8d68db55c4/torch/nn/modules/module.py#L293 We can test this by doin...
https://stackoverflow.com/questions/60221715/
Huggingface Transformers ByteLevelBPETokenizer tokenizer not found
I'm trying to run through the (new) tutorial here: https://huggingface.co/blog/how-to-train, but hit an error trying to load the ByteLevelBPETokenizer. I started from an existing conda env and also tried with a totally fresh env, but both give the same error: Exception has occurred: ImportError cannot import name 'Byt...
Okay, turns out the transformers installer pulls an older version (0.0.11). So... pip uninstall tokenizers pip install tokenizers==0.4.2 ...fixes it. It does issues a warning: ERROR: transformers 2.4.1 has requirement tokenizers==0.0.11, but you'll have tokenizers 0.4.2 which is incompatible., but this can safely be...
https://stackoverflow.com/questions/60244001/
No such operator torchvision::nms
When I try to run yoloV3 detect,it happend the error op = torch._C._jit_get_operation(qualified_op_name) RuntimeError: No such operator torchvision::nms Though this code is the source code of torchvision ,I try sevaral time to correct the code by the tips with failure.
I had the same problem on Ubuntu 18.04. Upgrading python to 3.8 and Installing fresh torch and torchvision libraries worked for me. virtualenv -p python3.8 torch17 source torch17/bin/activate pip install cython matplotlib tqdm scipy ipython ninja yacs opencv-python ffmpeg opencv-contrib-python Pillow scikit-image sciki...
https://stackoverflow.com/questions/60247432/
broadcasting across tensors in `pytorch`
I am using pytorch as an array processing language (not for the traditional deep learning purposes), and I am wondering what the canonical way is to do "batching" parallelism. For example, suppose I want to compute svds of two dimensional layers of a 3-d tensor (using torch.svd(), say), and I want to return a tuple o...
PyTorch is a high level software library with lots of python wrappers for highly optimized compiled code. A function or operator either supports batch data or not. There is no other way around it than writing your own C/C++/CUDA code and invoke it with python. Luckily, most functions support batch processing (includi...
https://stackoverflow.com/questions/60250696/
Implementing SmoothL1Loss for specific case
I have been experimenting with L1 and MSE losses in Pytorch and noticing that L1Loss performs better because it is more robust to outliers. I discovered SmoothL1Loss which seems to be the best of both worlds. I understand that it behaves like MSELoss for error<1 and like L1Loss otherwise. My dataset only contains va...
Yes, in this case it acts just like torch.nn.MSELoss, and it is called Huber Loss all in all. Due to it's nature threshold doesn't make much sense, let's look at example why that is the case: How it works Let's compare errors being larger than 1.0 in case of MSELoss and SmoothL1Loss. Assume our absolute error (|f(x)...
https://stackoverflow.com/questions/60252902/
pytorch conv2d value cannot be converted to type uint8_t without overflow
I'm passing a torch.Tensor with a dtype of torch.uint8 to an nn.Conv2d module and it is giving the error RuntimeError: value cannot be converted to type uint8_t without overflow: -0.0344873 My conv2d is defined as self.conv1 = nn.Conv2d(3, 6, 5). The error comes in my forward method when I pass the tensor to t...
Converting the tensor to a float seemed to fix it self.conv1(x.float())
https://stackoverflow.com/questions/60253449/
Unable to import torch.distributed.rpc
I was trying to run the RPC rnn example from the following link - https://github.com/pytorch/examples/tree/master/distributed/rpc/rnn but I am unable to import RPC module of the torch.distributed and getting the following error. Traceback (most recent call last): File ".\main.py", line 6, in <module> impo...
PyTorch Distributed package does not support Windows yet. Requests for this feature is tracked here: https://github.com/pytorch/pytorch/issues/37068
https://stackoverflow.com/questions/60257756/
(pytorch) I want to normalize [0 255] integer tensor to [0 1] float tensor
I want to normalize [0 255] integer tensor to [0 1] float tensor. I used cifar10 dataset and wanted to deal with integer image tensor. so I made them integer tensor when I loaded dataset, I used "transforms.ToTensor()" so the values were set to [0 1] float tensor([[[0.4588, 0.4588, 0.4588, ..., 0.4980, 0.4980, 0.50...
The problem is that you seem to misunderstand what transforms.Normalize does. To quote from the PyTorch documentation: Normalize a tensor image with mean and standard deviation. Given mean: (M1,...,Mn) and std: (S1,..,Sn) for n channels, this transform will normalize each channel of the input torch.*Tensor i.e....
https://stackoverflow.com/questions/60257898/
cnn IndexError: Target 2 is out of bounds
I got this error after I executed my code and it seems that the below portion of the code is throwing this error. I tried different ways but nothing could solve it. The error is given by the loss function. for i, data in enumerate(train_loader, 0): # import pdb;pdb.set_trace() inputs, labels = data ...
I faced the same problem. The problem was solved by changing the number of classes. num_classes = 10 (changed to the actual class number, instead of 1)
https://stackoverflow.com/questions/60259836/
can someone help me solve this problem, look for many solutions but they have not worked for me
error al entrenar the images have a size of ([64, 3, 224, 224]) I tried to change the batch-size or image size but I still get errors Epoch 1/30 ---------- --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython...
This is because the product of your spatial & channel dimensions is not equivalent to 23104 but rather is equal to 2876416. To flatten your tensor, you can try out = out.view(out.size(0), -1) instead, which should work fine.
https://stackoverflow.com/questions/60270418/
How does one have parameters in a pytorch model not be leafs and be in the computation graph?
I am trying to update/change the parameters of a neural net model and then having the forward pass of the updated neural net be in the computation graph (no matter how many changes/updates we do). I tried this idea but whenever I do it pytorch sets my updated tensors (inside the model) to be leafs, which kills the flo...
DOESNT WORK PROPERLY cuz the named parameter modules get deleted. Seems this works: import torch import torch.nn as nn from torchviz import make_dot import copy from collections import OrderedDict # img = torch.randn([8,3,32,32]) # targets = torch.LongTensor([1, 2, 0, 6, 2, 9, 4, 9]) # img = torch.randn([1,3,32...
https://stackoverflow.com/questions/60271131/
Error relating to conversion from list to tensor in Pytorch
There is a variable 'tmp' (3 dimension). tmp = [torch.tensor([1]),torch.tensor([2,3])] type(tmp) -> <class 'list'> type(tmp[0]) -> <class 'torch.Tensor'> type(tmp[0][0]) -> <class 'torch.Tensor'> I want to convert 'tmp' into torch.Tensor type. But, when I run this code below, an error occ...
Use torch.stack - All tensors need to be of the same size in the list. >>> torch.stack(tmp) Ex: >>> tmp = [torch.rand(2,2),torch.rand(2,2)] >>> tmp = torch.stack(tmp) >>> tmp tensor([[[0.0212, 0.1864], [0.0070, 0.3381]], [[0.1607, 0.9568], [0.9093, 0.1...
https://stackoverflow.com/questions/60274667/
AttributeError: dataset object has no attribute 'c' FastAI
I am trying to train a ResNet based UNet for image segmentation. I have the location of images and mask images in a csv file, that's why I have created my own dataloader, which is as follows: X = list(df['input_img']) y = list(df['mask_img']) X_train, X_valid, y_train, y_valid = train_test_split( X, y, test_size...
You should add the attribute c into your NumbersDataset, like this: def __init__(self, inputs, labels, c): self.inputs = inputs self.labels = labels self.c = c
https://stackoverflow.com/questions/60296710/
How to take depth of neural network as argument while constructing Network in Pytorch
I have written following code to take depth of network as parameter in Pytorch. Later I realized even if I am using many hidden layers, the learnable parameters remain the same. class Net3(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output, depth, init): super(Net3, self).__init__() ...
In init you need to create multiple hidden layers, currently you're only making one. One possibility to do this with little overhead is using a torch.nn.ModuleDict that will give you named layers: class Net3(torch.nn.Module): def __init__(self, n_feature, n_hidden, n_output, depth, init): super(Net3, self)...
https://stackoverflow.com/questions/60298457/
RuntimeError: expected scalar type Long but found Int in loss = criterion(outputs, y_train)
I built this acoustic model with features dim = [1124823,13] and labels dim = [1124823,1] and I split both to train, test, and dev. The problem that when I try to run my model I get this error RuntimeError: expected scalar type Long but found Int in loss = criterion(outputs, y_train) import torch import torch.nn as...
I think no_epochs=0 with this initialization. Possibly (len(train_loader) / batch_size) > n_iterations. Then int(no_eps) = 0. Try to change no_epochs to 100 manually, for example. no_eps = n_iterations / (len(train_loader) / batch_size) no_epochs = int(no_eps) for epoch in range(no_epochs):
https://stackoverflow.com/questions/60300668/
What does the copy_initial_weights documentation mean in the higher library for Pytorch?
I was trying to use the higher library for meta-learning and I was having issues understanding what the copy_initial_weights mean. The docs say: copy_initial_weights – if true, the weights of the patched module are copied to form the initial weights of the patched module, and thus are not part of the gradient tape ...
I think it's more or less clear what this means now to me. First I'd like to make some notation clear, specially with respect to indices wrt inner time step and outer time step (also known as episodes): W^<inner_i, outer_i> = denotes the value a tensor has at time step inner_i, outer_i. At the beginning of tr...
https://stackoverflow.com/questions/60311183/
How does one reset the dataloader in pytorch?
I was trying to reset the dataloader manually but was unable. I tried everything here https://discuss.pytorch.org/t/how-could-i-reset-dataloader-or-count-data-batch-with-iter-instead-of-epoch/22902/4 but no luck. Anyone know how to reset the data loader AND also have the suffle/randomness of the batches not be broken?
To reset a DataLoader then just enumerate the loader again. Each call to enumerate(loader) starts from the beginning. To not break transformers that use random values, then reset the random seed each time the DataLoader is initialized. def seed_init_fn(x): seed = args.seed + x np.random.seed(seed) random.see...
https://stackoverflow.com/questions/60311307/
Pytorch - how to undersample using weightedrandomsampler
I have an unbalanced dataset and would like to undersample the class that is overrepresented.How do I go about it. I would like to use to weightedrandomsampler but I am also open to other suggestions. So far I am assuming that my code will have to be structured kind of like the following. But I dont know how to exaclt...
From my understanding, pytorch WeightedRandomSampler 'weights' argument is somewhat similar to numpy.random.choice 'p' argument which is the probability that a sample will get randomly selected. Pytorch uses weights instead to random sample training examples and they state in the doc that the weights don't have to sum ...
https://stackoverflow.com/questions/60320232/
How can I matrix-multiply two PyTorch quantized Tensors?
I am new to tensor quantization, and tried doing something as simple as import torch x = torch.rand(10, 3) y = torch.rand(10, 3) x@y.T with PyTorch quantized tensors running on CPU. I thus tried scale, zero_point = 1e-4, 2 dtype = torch.qint32 qx = torch.quantize_per_tensor(x, scale, zero_point, dtype) qy = torch.qua...
It is not straight forward to implement matrix multiplication for quantized matrices. Therefore, the "conventional" matrix multiplication (@) does not support it (as your error message suggests). You should look at quantized operations, e.g., torch.nn.quantized.functional.linear: torch.nn.quantized.functional.linear(...
https://stackoverflow.com/questions/60325913/
bias dimension definition in coding neural network
In the following Figure showing the code for defining the dimension of the bias b1 term, I wonder why the first dimension of bias b1 is not the batch size? Does it mean then it just assumes this bias is applied to all batches then? If I specify the bias b1 dimension to be (batch_size, 256) then does it mean i am appl...
The weights and biases of your neural network layer are not specified in terms of batch size. eg: w1 = torch.randn(784,256) : This is a 2D matrix you're going to use for a matrix multiply. 784 is the dimension of your input image without considering batch size. (I'm guessing this is for mnist? it looks like you're fla...
https://stackoverflow.com/questions/60328668/
Why is there an error (numpy.float64 cannot be interpreted as in integer) in pytorch sample code
I was trying to run the sample code found here: https://pytorch.org/tutorials/intermediate/torchvision_tutorial.html I get a crash in the class CocoEvaluator() constructor in coco_eval.py where the following line of code: for iou_type in iou_types: self.coco_eval[iou_type] = COCOeval(coco_gt, iouType=iou_typ...
The problem most likely lies in the numpy version. Numpy version 1.18.+ usually throws this error. However when changing to numpy 1.17.4 the problem is fixed. as shown here -> https://github.com/pytorch/vision/issues/1700 -> https://www.kaggle.com/questions-and-answers/90865 #check for version number np.version.v...
https://stackoverflow.com/questions/60331464/
Gradient Computation broken by Sigmoid function in Pytorch
Hey I have been struggling with this weird problem. Here is my code for the Neural Net: class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv_3d_=nn.Sequential( nn.Conv3d(1,1,9,1,4), nn.LeakyReLU(), nn.Conv3d(1,1,9,1,4), nn.L...
I found the problem with my code. I delved deeper into what in-place actually meant. So, if you check the line conv_layer = self.linear_layers_(conv_layer) linear_layers_ of the assignment is changing the values of conv_layer in-place and as a result the values are getting overwritten and because of this, gradient ...
https://stackoverflow.com/questions/60337608/
Validation loss for pytorch Faster-RCNN
I’m currently doing object detection on a custom dataset using transfer learning from a pytorch pretrained Faster-RCNN model (like in torchvision tutorial). I would like to compute validation loss dict (as in train mode) at the end of each epoch. I can just run model in train mode for validation like this: model.trai...
There was some discussion about this issue here. The conclusion there is that it is absolutely valid to calculate validation loss in train mode. The numerical value of the val loss in itself is not meaningful, only the trend is important to prevent overfitting. Therefore while train mode does alter the numerical value ...
https://stackoverflow.com/questions/60339336/
challenging special numpy operation
I have a NumPy array that is full of indices of numbers input. I want to check if certain indices indices are in it. Say that the i'th row of input, input[i] has entries j_1<...<j_n that their values belong to indices. I would like to switch the value of input[i,j_n] with a random value from indices. How can I do...
Something like that: import random input = [[i if i not in indices else random.choice(indices) for i in x] for x in input] Better, of course, to check in set instead of list: import random d = {*indices} input = [[i if i not in d else random.choice(indices) for i in x] for x in input]
https://stackoverflow.com/questions/60340357/
Best way to run a trained PyTorch LSTM/GRU model fully in the browser
I'm looking into running a trained PyTorch model (containing LSTM/GRU layers) fully in the browser (no backend) as part of an interactive blog post. I've looked at ONNX.js, and that works great, but not for a model containing a GRU layer. I saw someone comment on the ONNX.js github that Gated RNN's are not supported ye...
There is this thread, that describes the options but is not receiving a lot of attention. In summary, as of May 2020, there are only two options: 1) ONNX.js but its development is currently stale. 2) Converting the model to Tensorflow. Technically there is a third one, that includes no server. And that is to run ...
https://stackoverflow.com/questions/60340552/
Pytorch Runtime Error - The size of tensor a (5) must match the size of tensor b (3) at non-singleton dimension
I am trying to train a Faster RCNN Network on a custom dataset consisting of images for object detection. However, I don't want to directly give an RGB image as input, I actually need to pass it through another network (a feature extractor) along with the corresponding thermal image and give the extracted features as t...
The backbone network you are using for the FasterRCNN is a pretrained mobilenet_v2. The input channel of a network is decided by the number of channels of the input data. Since the (backbone) model is pretrained (on natural images?) with 3 channels 3xNxM, you cannot use it for tensors of dimension 5xPxQ (skipping the s...
https://stackoverflow.com/questions/60342869/
Torch.sort and argsort sorting randomly in case of same element
When same elements are encountered, torch.sort and argsort sort the tensor in random manner. This is not the case in numpy. I have a list of elements already sorted according to the second column and now i want to sort it using the first column but preserve the earlier sort in case of tie in the new sorting. import to...
As per torch 1.9.0 you can run the sort with option stable=True. See https://pytorch.org/docs/1.9.0/generated/torch.sort.html?highlight=sort#torch.sort >>> x = torch.tensor([0, 1] * 9) >>> x.sort() torch.return_types.sort( values=tensor([0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1]), ...
https://stackoverflow.com/questions/60366033/
Install Pytorch GPU with pre-installed CUDA and cudnn
As the title suggests, I have pre-installed CUDA and cudnn (my Tensorflow is using them). The version of CUDA is 10.0 from nvcc --version. The versiuon of cudnn is 7.4. I am trying to install pytorch in a conda environment using conda install pytorch torchvision cudatoolkit=10.0 -c pytorch. However, the installe...
So I solved this myself finally. The issue is that I didn't reboot my system after installing pytorch. After rebooting, torch.cuda.is_available() returns True as expected.
https://stackoverflow.com/questions/60368896/
Pythonic Nested for - loops in Python
I am working on this code where I have nested for loops. a_list and b_list are list of tuples, where each tuple is made up of two tensors [(tens1, tens2), ...]. I am trying to compute the similarity of every tens1 in a_list to every tens1 in b_list. Below is the code I have. And the nested loop appears to be a bottlene...
You could use a dictionary comprehension: a2b = {a: {b: self.calculate_similarity(vec_a, vec_b ) for (b, vec_b) in b_list if a[0] != b[0]} for (a, vec_a) in a_list}
https://stackoverflow.com/questions/60378598/
Indexing in two dimensional PyTorch Tensor using another Tensor
Suppose that tensor A is defined as: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 I'm trying to extract a flat array out of this matrix by using another tensor as indices. For example, if the second tensor is defined as: 0 1 2 3 I want the result of the indexing to be 1-D tensor with the contents: 1 6 11 16 ...
1st Approach: using torch.gather torch.gather(A, 1, B.unsqueeze_(dim=1)) if you want one-dimensional vector, you can add squeeze to the end: torch.gather(A, 1, B.unsqueeze_(dim=1)).squeeze_() 2nd Approach: using list comprehensions You can use list comprehensions to select the items at specific indexes, then they can...
https://stackoverflow.com/questions/60399734/
TypeError: can't multiply sequence by non-int type of 'tuple' in pytorch
The code as below: class L2Norm(nn.Module): def __init__(self): super(L2Norm, self).__init__() self.eps = 1e-10 def forward(self, x): norm = torch.sqrt(torch.sum(x * x, dim = 1) + self.eps) x = x / norm.unsqueeze(-1).expand_as(x) return x I want to normalize the featur...
x is a tuple of two tensors, as shown in your output. x * x would require a way to multiply two tuples. If I simply define x as a tuple of ints, e.g. x=(1, 1), and tried the same code: x * x, I get the same error: >>> x=(1,1) >>> x * x Traceback (most recent call last): File "<stdin>", line...
https://stackoverflow.com/questions/60416907/
how visualize multi channel of feature from PyTorch?
I'm almost newbie at PyTorch One of my output size from conv is [1, 25, 8, 32] (25=channel, 8=height, 32=width) I can use squeeze and make it to [25, 8, 32]. But I'm confused with 25 channel. When I want to visualize sum of 25 channel and make to one GRAYorRGB image(1or3x8x32),How can i deal with in code?? I can u...
It is difficult to visualize images with more than 3 channels and it is unclear what a feature vector in 25 dimensional space actually looks like. The most straight forward approach would be to visualize the 8x32 feature maps you have as separate 25 gray scale images of size 8x32. Each image will show how how "sensiti...
https://stackoverflow.com/questions/60425609/
How to change certain values in a torch tensor based on an index in another torch tensor?
This is an issue I'm running while convertinf DQN to Double DQN for the cartpole problem. I'm getting close to figuring it out. tensor([0.1205, 0.1207, 0.1197, 0.1195, 0.1204, 0.1205, 0.1208, 0.1199, 0.1206, 0.1199, 0.1204, 0.1205, 0.1199, 0.1204, 0.1204, 0.1203, 0.1198, 0.1198, 0.1205, 0.1204, 0.1201,...
You can use torch.where - torch.where(condition, x, y) Ex.: >>> x = tensor([0.2853, 0.5010, 0.9933, 0.5880, 0.3915, 0.0141, 0.7745, 0.0588, 0.4939, 0.0849]) >>> condition = tensor([False, True, True, True, False, False, True, False, False, False]) &gt...
https://stackoverflow.com/questions/60442272/
How forward() method is used when it have more than one two input parameters in pytorch
Can someone tell me the concept behind the multiple parameters in forward() method? Generally, the implementation of forward() method has two parameters self input if a forward method has more than these parameters how PyTorch is using the forward method. Let's consider this codebase: https://github.com/bamps53/k...
Forward function set by you. That means you can add more parameters as you want. For example, you could add inputs as shown below def forward(self, input1, input2, input3): x = self.layer1(input1) y = self.layer2(input2) z = self.layer3(input3) net = torch.cat((x,y,z),1) return net You have ...
https://stackoverflow.com/questions/60463821/
Training TFBertForSequenceClassification with custom X and Y data
I am working on a TextClassification problem, for which I am trying to traing my model on TFBertForSequenceClassification given in huggingface-transformers library. I followed the example given on their github page, I am able to run the sample code with given sample data using tensorflow_datasets.load('glue/mrpc'). Ho...
Fine Tuning Approach There are multiple approaches to fine-tune BERT for the target tasks. Further Pre-training the base BERT model Custom classification layer(s) on top of the base BERT model being trainable Custom classification layer(s) on top of the base BERT model being non-trainable (frozen) Note that the BERT...
https://stackoverflow.com/questions/60463829/
Pairwise similarity matrix between a set of vectors in PyTorch
Let's suppose that we have a 3D PyTorch tensor, where the first dimension represents the batch_size, as follows: import torch import torch.nn as nn x = torch.randn(32, 100, 25) That is, for each i, x[i] is a set of 100 25-dimensional vectors. I would like to compute the similarity (e.g., the cosine similarity -- but...
The documentation implies that the shapes of the inputs to cosine_similarity must be equal but this is not the case. Internally PyTorch broadcasts via torch.mul, inserting a dimension with a slice (or torch.unsqueeze) will give you the desired result. This is not optimal due to duplicate computations and memory for the...
https://stackoverflow.com/questions/60467264/
pytorch model summary - forward func has more than one argument
I am using torch summary from torchsummary import summary I want to pass more than one argument when printing the model summary, but the examples mentioned here: Model summary in pytorch taken only one argument. for e.g.: model = Network().to(device) summary(model,(1,28,28)) The reason is that the forward functi...
You can use the example given here: pytorch summary multiple inputs summary(model, [(1, 16, 16), (1, 28, 28)])
https://stackoverflow.com/questions/60480686/
creating a common embedding for two languages
My task deals with multi-language like (english and hindi). For that I need a common embedding to represent both languages. I know there are methods for learning multilingual embedding like 'MUSE', but this represents those two embeddings in a common vector space, obviously they are similar, but not the same. So I w...
I think a good lead would be to look at past work that has been done in the field. A good overview to start with is Sebastian Ruder's talk, which gives you a multitude of approaches, depending on the level of information you have about your source/target language. This is basically what MUSE is doing, and I'm relativel...
https://stackoverflow.com/questions/60481990/
How to normalize images in PyTorch
transform = transforms.Compose([ transforms.ToTensor() ]) trainset = torchvision.datasets.ImageFolder(root='C:/Users/beomseokpark/Desktop/CNN/train_data', transform = transform) data_loader = DataLoader(dataset = trainset, batch_size = 8, shuffle = True, num_workers=2) with torch.no_grad(): for num, data in e...
There's the "lazy man" approach: You can simply plug a nn.BatchNorm2d as the very first layer of your network. With the appropriate momentum, and track_running_stats=True this layer will estimate your data's mean and variance for you. Alternatively, you can compute the mean and variance using mu = torch.zeros((3,), d...
https://stackoverflow.com/questions/60485362/
PyTorch FasterRCNN TypeError: forward() takes 2 positional arguments but 3 were given
I am working on object detection and I have a dataset containing images and their corresponding bounding boxes (ground-truth values). I actually have built my own feature extractor which takes an image as input and outputs a feature map(basically an encoder-decoder system where the final output of the decoder is the s...
This is because only the image inputs should be passed into the models, instead of both images and the ground truth targets. So instead of doing output = model(images, targets), you can do output = model(images). As for why the error message talks about being given 3 positional arguments, this is because forward is in...
https://stackoverflow.com/questions/60513469/
Why torch.FloatTensor([[[0,1,2],[3,4,5]],[[6,7,8],[9,10,11]]]) size is [2,2,3]?
>>> ft = torch.FloatTensor([[[0,1,2],[3,4,5]],[[6,7,8],[9,10,11]]]) >>> print(ft.shape) torch.Size([2, 2, 3]) I can't understand this result. I think the torch size should be [2,3,2], but the result is [2,2,3].
Because len([[[0,1,2],[3,4,5]],[[6,7,8],[9,10,11]]]) = 2 This is the first 2. and each item inside: len([[0,1,2],[3,4,5]]) = 2 This is the second 2. and each item inside: len([0,1,2]) = 3 This is the 3.
https://stackoverflow.com/questions/60519646/
Pytorch - select region of a tensor using torch function
I am looking for a way to select a region of a PyTorch tensor using a torch function (without using numpy). Do you have suggestions on how to proceed? In other words, I'm looking for a way to crop a region of a matrix. Using numpy, it would be something like import numpy as np A = np.random.rand(16,16) B = A[0:8, 0:...
What's wrong with regular slicing? import torch A = torch.randn([1,3,64,64]) B = A[..., 16:32, 16:32]
https://stackoverflow.com/questions/60527036/
What is the difference between sample() and rsample()?
When I sample from a distribution in PyTorch, both sample and rsample appear to give similar results: import torch, seaborn as sns x = torch.distributions.Normal(torch.tensor([0.0]), torch.tensor([1.0])) sns.distplot(x.sample((100000,))) sns.distplot(x.rsample((100000,))) When should I use sample(), and...
Using rsample allows for pathwise derivatives: The other way to implement these stochastic/policy gradients would be to use the reparameterization trick from the rsample() method, where the parameterized random variable can be constructed via a parameterized deterministic function of a parameter-free random variabl...
https://stackoverflow.com/questions/60533150/
getting the classification labels for torchvision's pretrained networks
Pytorch's torchvision package provides pre-trained neural networks for image classification. I've been using the following code to classify an image using Alexnet (note: some of this code is from this webpage): from PIL import Image import torch from torchvision import transforms from torchvision import models # func...
Torchvision models are pretrained on the ImageNet dataset. Due to its comprehensiveness and size, ImageNet is the most commonly used dataset for pretraining & transfer learning. As you noted, it has 1000 classes. The complete class list can be searched, or you can refer to this listing on GitHub: https://gist.githu...
https://stackoverflow.com/questions/60536972/
Tensor output from final layer is of the wrong shape in PyTorch
I am building a sequence-to-label classifier, where the input data are text sequences and output labels are binary. The model is very simple, with GRU hidden layers and a Word Embeddings input layer. I want a [n, 60] input to output a [n, 1] label, but the Torch model returns a [n, 60] output. My model, with minimal l...
The output from your model is of shape torch.Size([64, 60, 1]) i.e. 64 is the batch size, and (60, 1) corresponds [n, 1] as expected. Assuming you're using nn.CrossEntropy(input, target), it expected the input to be (N,C) and target to be (N), where C is number of classes. Your output is consistent, and hence loss is...
https://stackoverflow.com/questions/60537594/
Pytorch dataset and shared memory?
I would want to cache data in a torch.utils.data.Dataset. The simple solution is to just persist certain tensors in a member of the dataset. However, since the torch.utils.data.DataLoader class spawns multiple processes, the cache would only be local to each instance and would cause me to possibly cache multiple copies...
The answer depends on your OS and settings. If you are using Linux with the default process start method, you don't have to worry about duplicates or process communication, because worker processes share memory! This is efficiently implemented as Inter Process Communication (IPC) through shared memory (some more detail...
https://stackoverflow.com/questions/60542153/
torch.nn.functional.conv2d for several channels/batches
I have an image with I want to pad (to maintain the same shape) and then perform a convolution with a given kernel. It works ok if I have only one channel and one image in the batch. But how to properly rewrite it for several batches & channels? I suppose, for batches I can just duplicate the kernel along dimension...
The documentation at https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.conv2d seems to answer your question: input – input tensor of shape (minibatch,in_channels,iH,iW) weight – filters of shape (out_channels,in_channels/groups,kH,kW) so your x must be size (batch_size, in_channels, 16, 16) a...
https://stackoverflow.com/questions/60551548/
How do I crop a Landsat image into smaller chunks for training and then predict on the original image
I am looking at using Landsat imagery to train a CNN for unsupervised pixel-wise semantic segmentation classification. That said, I have been unable to find a method that allows me to crop images from the larger Landsat image for training and then predict on the original image. Essentially here is what I am trying to ...
Borrowing from Ronneberger et al., what we have been doing is to split the input Landsat scene and corresponding ground truth mask into overlapping tiles. Take the original image and pad it by the overlap margin (we use reflection for the padding) then split into tiles. Here is a code snippet using scikit-image: imp...
https://stackoverflow.com/questions/60555060/
padding and attention mask does not work as intended in batch input in GPT language model
The following code is without batch: from transformers import GPT2LMHeadModel, GPT2Tokenizer import torch tokenizer = GPT2Tokenizer.from_pretrained("gpt2") model = GPT2LMHeadModel.from_pretrained('gpt2') model.eval() context=torch.tensor([tokenizer.encode("This is")]) output, past = model(context) token = torch.argma...
I'm not sure if this helps, but you don't need to implement you own attention masking and padding. The Transformers library provides the encode_plus() and batch_encode_plus() functions that will perform tokenization, generate the attention masks, and do padding for you. The results come out as Python dictionaries.
https://stackoverflow.com/questions/60579343/
How is the number of channels adjusted in efficientnet
I was reading the code at efficientnet and was shocked by its clever ideas. But I don't quite understand how it adjusts the number of channels. def round_filters(filters, width_coefficient, depth_divisor): filters *= width_coefficient new_filters = int(filters + depth_divisor / 2) // depth_divisor * depth_divisor...
It's making the scaled width divisible by depth_divisor. You can view as rounding the scaled width to the nearest multiple of depth_divisor with some additional consideration (round up when going down more than 10%). In almost all applications of this function in various MobileNets and EfficientNets the depth_divisor i...
https://stackoverflow.com/questions/60583868/
Is there a nice way to to check if numpy array and torch tensor point to same underlying data?
I want to check if numpy array and torch tensor point to same underlying memory. So far I've came up with a simple check but it doesn't look super elegant. import numpy as np import torch # example a = np.random.randn(3,3) b = torch.from_numpy(a) assert a.__array_interface__['data'][0] == b.data_ptr() Is there a ...
This is a completely valid way to access and compare the pointers. The array interface is designed to allow sharing data buffers, so it will have the correct pointer. With that said, if you prefer a less verbose solution, you could also grab it directly like so: import numpy as np import torch ​ # example a = np.rand...
https://stackoverflow.com/questions/60587536/
I don't understand pytorch input sizes of conv1d, conv2d
I have a data of 2 temporal series of 18 points each one. So I organized in a matrix of 18 rows and 2 columns (with 180 samples to classify in 2 classes - activated and non-activated). So, I want to do a CNN with this data, my kernel walks in one direction, along the lines (temporal). Examples of the figure attached. ...
You will want to use a two channel conv1d as the first convolution later. I.e. it will take in a tensor of shape [B, 2, 18]. Having 2 channel input with kernel size 3 will define kernels of shape [2, 3] where the kernel slides along the last dimension of the input. The number of channels C1 in your output feature map i...
https://stackoverflow.com/questions/60591140/
Error: AttributeError: module 'transformers' has no attribute 'TFBertModel'
I am applying transfer learning with the python framework (PyTorch). I am getting the below error, when loading a PyTorch pre-trained model in Google Colab. After changing the code 1 to be as code 2, I got the same error. CODE 1: BertModel.from_pretrained CODE 2: TFBertModel.from_pretrained Error: AttributeError: mod...
You should probably list the available package with its version in your python and your Colab link, for TFBertModel is only available when you have tensorflow. In order to reproduce your error. I play around in the Colab as following: No tensorflow cause error when you import TFBertModel !pip install transformers...
https://stackoverflow.com/questions/60593173/
How to implement a PyTorch NN from a directed graph
I'm new to Pytorch and teaching myself, and I want to create ANNs that takes in a directed graph. I also want to pass predefined weights & biases for each connection into it, but willing to ignore that for now. My motivation for these conditions is that I'm trying to implement the NEAT algorithm, which is basical...
Since you don't plan on doing any actual training of the network, PyTorch might not be your best option in this case. NEAT is about recombining and mutating neural networks - both their structure and their weights and biases - and thereby achieving better results. PyTorch generally is a deep learning framework, meanin...
https://stackoverflow.com/questions/60605251/
How to get top-k elements of each row in a 2D tensor?
How to get the top-k elements of each row in a 2D tensor in an elegant way instead of using for-loop as below? import torch elements = torch.rand(5,10) topk_list = [2,3,1,2,0] # means top2 for 1st row, top3 for 2nd row, top1 for 3rd row,.... index_list = [] # record the topk index in elements for i in range(5): ...
If your k's don't vary too much and you want to vectorize your code you can first take the maximum top k per row and then gather the desired results. # Code from OP import torch elements = torch.rand(5,10) topk_list = [2,3,1,2,0] # means top2 for 1st row, top3 for 2nd row, top1 for 3rd row,.... index_list = [] # reco...
https://stackoverflow.com/questions/60614116/
AttributeError: module 'tensorflow' has no attribute 'value'
I am training pytorch-yolov3 in custom dataset. I prepared all the required txt, data and names files . while runninng following command: python3 train.py --model_def config/yolov3.cfg --data_config config/custom.data I got following error: Warning: indexing with dtype torch.uint8 is now deprecated, please use ...
Change summary = tf.summary(value=[tf.summary.Value(tag=tag, simple_value=value)]) To summary = tf.summary.scalar(tag=tag, simple_value=value)
https://stackoverflow.com/questions/60614678/
Install Detectron2 on Windows 10
I try to install Facebook's Detectron2 followed this official repo. Following that repo, detectron2 can only install on linux. However, I'm working on a server run on Windows operator. Anybody know how to install it on Windows?
Answer found through this issue: https://github.com/facebookresearch/detectron2/issues/9 These steps worked for me on my RTX 3070. Install Anaconda https://docs.anaconda.com/anaconda/install/windows/ Create a environment.yml file containing the following code. name: detectron2 channels: - pytorch - conda-forge ...
https://stackoverflow.com/questions/60631933/
Inverted colors in Tensorboard SummaryWriter add_image() function
There is an image stored in image_tensor (image_tensor of size (3,256,512), storing values in the interval 0,255) which I would like to display in Tensorboard (TensorboardX for PyTorch, more specifically) via the add_image() function for SummaryWriter. When I add the image to the Tensorboard via writer.add_image("colo...
I had a similar problem, where I was also unable to track the problem. The solution that worked for me but is unfortunately a little bit cumbersome is: Take your image and plug it into a matplotlib figure then use add_figure. For example: fig, ax = plt.subplots(2,3) # add your subplots with some images eg. ax[0,0].ims...
https://stackoverflow.com/questions/60651684/
Python coverage report covering only test file
I’m pretty new to contributing to open source projects and am trying to get some coverage reports so I can find out what needs more / better testing. However, I am having trouble getting the full coverage of a test. This is for pytorch For example, lets say I want to get the coverage report of test_indexing_py. I run...
I think its because you are asking to check the coverage from the test running directory, ie where test_indexing.py is. A better approach would be like running the test from the root directory itself, rather than test directory, it has several advantages like the configuration file reading and all. And regarding you...
https://stackoverflow.com/questions/60658028/
Sharing parameters in different nn.Moules in pytorch
I've got the model that you can see below, but I need to create two instances of them that shares x2h and h2h. Does anyone know how to do it? class RNN(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(RNN, self).__init__() self.hidden_size = hidden_size self.x2h...
It is a Python question i assume. Variables declared inside the class, not inside a method are class or static variables. Ref: https://radek.io/2011/07/21/static-variables-and-methods-in-python/
https://stackoverflow.com/questions/60659971/
How to append a list with arrays of two different sizes based on conditons
I was wondering how to do this in a more efficient way for arbitrary arrays, the code is written in PyTorch, but it is only for 1-d tensors. Thank you! test=[] data=np.random.uniform(0,1,[20,]) x=torch.from_numpy(data).float() x,_=torch.sort(x) v=torch.rand(5).float() v,_=torch.sort(v) for i in range(len(x)): if ...
you can use the built-in function next: for i in x: test.append(next((e for e in v[:4] if i < e), v[4])) you can also use a list comprehension instead of for loop: s = v[:4] d = v[4] test = [next((e for e in s if i < e), d)) for i in x] if the test variable has already some elements you can use the i...
https://stackoverflow.com/questions/60663054/
How to visualize 3d joints of a SMPL model based on pose params
I am trying to use demo.py in nkolot / GraphCMR | GitHub. I am interested in obtaining joints from the inferred SMPL image and visualize it similar to described in README of this project: gulvarol / smplpytorch | GitHub. I also posted the issue here: https://github.com/nkolot/GraphCMR/issues/36. What I tried that didn'...
The problem is that smpl_pose (of shape torch.Size([1, 24, 3, 3])) is the SMPL pose parameters expressed as a rotation matrix. You need to make a transformation from rotation matrix to axis-angle representation which is (72,1). You can use Rodrigues formula to do it, as claimed in the paper: Get more information from...
https://stackoverflow.com/questions/60667134/
An appropriate way of adding a feature to a time series forecasting model input
I have been working on a demand forecasting model for a while. I am using an LSTM model to predict the future demand of a product family of a company. To solidify and exemplify my raw data, an example is as below; Unprocessed data np.random.seed(1) raw_data = pd.DataFrame({"product_type": ["A"]*3...
I would first recommend you to re-think the shape of your dataset. A classic time serie dataset "X" feeded to a LSTM network will have a 3D shape as : X.shape[0] : number of time series (to use for training / testing) X.shape[1] : number of timesteps in the time series X.shape[2] : number of features of each time ser...
https://stackoverflow.com/questions/60667909/
How to compare one picture to all data test in siamese neural network?
I've been build siamese neural network using pytorch. But I've just test it by inserting 2 pictures and calculate the similarity score, where 0 says that picture is different and 1 says picture is same. import numpy as np import os, sys from PIL import Image dir_name = "/Users/tania/Desktop/Aksara/Compare" #this shou...
Yes there is a way, you could use the softmax function: output = torch.softmax(output) This returns a tensor of 26 values, each corresponding to the probability that the image corresponds to each of the 26 classes. Hence, the tensor sums to 1 (100%). However, this method is suitable for classification tasks, as op...
https://stackoverflow.com/questions/60680091/
Can't convert Pytorch to ONNX
Trying to convert this pytorch model with ONNX gives me this error. I've searched github and this error came up before in version 1.1.0 but was apparently rectified. Now I'm on torch 1.4.0. (python 3.6.9) and I see this error. File "/usr/local/lib/python3.6/dist-packages/torch/onnx/init.py", line 148, in export strip_...
I used to have a similar error when exporting using torch.onnx.export(model, x, ONNX_FILE_PATH) and I fixed it by specifying the opset_version like so: torch.onnx.export(model, x, ONNX_FILE_PATH, opset_version = 11)
https://stackoverflow.com/questions/60682622/
TypeError: h5py objects cannot be pickled
I am trying to run a PyTorch implementation of a code, which is supposed to work on SBD dataset. The training labels are originally available in .bin file, which are then converted to HDF5 (.h5) files. Upon running the algorithm, I get an error as: " TypeError: h5py objects cannot be pickled " I think the error is s...
setting num_workers=0 solve this issue for me
https://stackoverflow.com/questions/60684061/
How to load large multi file parquet files for tensorflow/pytorch
I am trying to load a few parquet files from a directory into Python for tensorflow/pytorch. The files are too large to be loaded through the pyarrow.parquet functions import pyarrow.parquet as pq dataset = pq.ParquetDataset('dir') table = dataset.read() This gives out of memory error. I have also tried using pe...
For pyarrow, you can list the directory with Python, iterate over *.parquet files, open each one as pq.ParquetFile, and read it one row group at a time. This will alleviate the memory pressure, but won't be super fast without parallelization. For petastorm, you are right to use make_batch_reader(). Indeed, the error m...
https://stackoverflow.com/questions/60685684/
Google Colab TensorBoard in another Chrome Tab
I am going through the PyTorch tutorials and am currently on the TensorBoard one. Through research, I have been able to get it to work inline and through another tab. My preference is to have it persisent in another tab that will update automatically. The method described below uses ngrok: https://medium.com/@iamsdt/u...
Update: Here's an example cell with two buttons to open Tensorboard in another window and hide it on Colab notebook: %load_ext tensorboard %tensorboard --logdir="logdir" import IPython display(IPython.display.HTML(''' <button id='open_tb'>Open TensorBoard</button> <button id='hide_tb'>Hid...
https://stackoverflow.com/questions/60686617/
Can I combine Monte Carlo policy gradient algorithm with other policy gradient algorithms
I know that Monte Carlo REINFORCE policy gradient algorithm is different in how it calculates the reward values by calculating discounted cumulative future reward at each step. here is the peace of code to calculate the discounted cumulative future reward at each time step. G = np.zeros_like(self.reward_memory, dtyp...
You are mixing some things up here. The Monte Carlo approach is a way to compute the returns for the state-action pairs: as the discounted sum of all the future rewards after that state-action pair (s, a) following the current policy π. (It is also worth noting that REINFORCE is not an especially good RL algorithm, an...
https://stackoverflow.com/questions/60689453/
Can someone explain this pytorch neural network code ? Are there two different neural networks here or one?
class doubleNetwork(nn.Module): def __init__(self, input_dim, output_dim): super(doubleNetwork, self).__init__() self.policy1 = nn.Linear(input_dim, 256) self.policy2 = nn.Linear(256, output_dim) self.value1 = nn.Linear(input_dim, 256) self.value2 = nn.Linear(256, 1) def forward(self, state): ...
You have two networks in parallel. You can see it in the forward method: state -> policy1 -> policy2 -> logits state -> value1 -> value2 -> value policy1, policy2, value1 and value2 are 4 different and independent fully connected (Linear) layers. The nn.Linear method creates a new layer of neurons every time it's ca...
https://stackoverflow.com/questions/60701648/
Pytorch device and .to(device) method
I'm trying to learn RNN and Pytorch. So I saw some codes for RNN where in the forward probagation method, they did a check like this: def forward(self, inputs, hidden): if inputs.is_cuda: device = inputs.get_device() else: device = torch.device("cpu") embed_out = self.embeddings(inputs) ...
This code is deprecated. Just do: def forward(self, inputs, hidden): embed_out = self.embeddings(inputs) logits = torch.zeros((self.seq_len, self.batch_size, self.vocab_size), device=inputs.device) Note that to(device) is cost-free if the tensor is already on the requested device. And do not use get_device() b...
https://stackoverflow.com/questions/60713781/
What does 'Epoch' mean in training Generative Adversarial Networks
I am training a GAN with text data. When I train the discriminator, I randomly sample m positive data from the dataset and generate m negative data with the generator. I found many papers mention about details of implementation such as training epochs. About the training epochs, I have a question about sampling positiv...
In my opinion, an epoch is when you passed through the whole training data once. and I think in the paper also they mean a pass through the whole training set when they mention an epoch. However, the epoch can be also defined as after processing k elements, where k can be smaller than n (the size of the training set)....
https://stackoverflow.com/questions/60715524/
Deploying a pytorch model in java
I have a pytorch model trained and saved and now I want to use it in a java (not android) environment in windows os (since I'm using some library only available in java), Is it possible? I couldn't find a straight answer in the pytorch docs, and when clicking java api docs the link is broken.
@Gilad, You can do this with Deep Java Library (djl.ai). Check out: https://github.com/awslabs/djl/tree/master/pytorch/pytorch-engine
https://stackoverflow.com/questions/60721831/
Is there any way to convert pytorch tensor to tensorflow tensor
https://github.com/taoshen58/BiBloSA/blob/ec67cbdc411278dd29e8888e9fd6451695efc26c/context_fusion/self_attn.py#L29 I need to use mulit_dimensional_attention from the above link which is implemented in TensorFlow but I am using PyTorch so can I Convert Pytorch Tensor to TensorFlow Tensor or I have to implement it in Py...
You can convert a pytorch tensor to a numpy array and convert that to a tensorflow tensor and vice versa: import torch import tensorflow as tf pytorch_tensor = torch.zeros(10) np_tensor = pytorch_tensor.numpy() tf_tensor = tf.convert_to_tensor(np_tensor) That being said, if you want to train a model that uses a com...
https://stackoverflow.com/questions/60722008/
Predicting the surface of the car using its 2d bbox and plate bbox
I'm trying to solve an interesting problem w/o using GPU intensive model in inference time. (No Deep Learning) Input: 2D Image which contains car(s) in it, with accurate bboxes, and also a bbox of the plate's car. (We also know that the cameras are located just a bit above the cars) Output: Surface of the car predict...
Using Deep learning-based object detection methods is tend to achieve a really high detection accuracy. Deep neural network is a trend to improve the accuracy of bounding box, designing a reasonable regression loss function is also an important way. So, if you are considering accuracy as an important factor on the proj...
https://stackoverflow.com/questions/60723535/
Understanding tf.nn.depthwise_conv2d
From https://www.tensorflow.org/api_docs/python/tf/nn/depthwise_conv2d Given a 4D input tensor ('NHWC' or 'NCHW' data formats) and a filter tensor of shape [filter_height, filter_width, in_channels, channel_multiplier] containing in_channels convolutional filters of depth 1, depthwise_conv2d applies a differ...
In pytorch terms: always one input channel per group, 'channel_multiplier' output channels per group; not in one step; see 1 I see a way to emulate several input channels per group. For two, do depthwise_conv2d, then split result Tensor as deck of cards by half, and then sum acquired halves elementwise (before relu...
https://stackoverflow.com/questions/60724571/
tensorboard colab tensorflow._api.v1.io.gfile' has no attribute 'get_filesystem
I am trying to use tensorboard on colab. I manage to make it work, but not for all commands. add_graph and add_scalar works, but when I tried to run add_embedding I am getting the following error: AttributeError: module 'tensorflow._api.v1.io.gfile' has no attribute 'get_filesystem' This is the relevant code (I thin...
For me, this fixed the problem: import tensorflow as tf import tensorboard as tb tf.io.gfile = tb.compat.tensorflow_stub.io.gfile
https://stackoverflow.com/questions/60730544/
Approximate the q-function with NN in the FrozenLake exercise
import numpy as np import gym import random import time from IPython.display import clear_output env = gym.make("FrozenLake-v0") action_space_size = env.action_space.n state_space_size = env.observation_space.n q_table = np.zeros((state_space_size, action_space_size)) num_episodes = 10000 max_steps_per_episode = 1...
This is a slightly broad question, but here's a breakdown. Firstly NNs are just function approximators. Give them some input and output and they will find f(input) = output Only, if such a function exists and is differentiable based on the loss/cost So the Q function is Q(state,action) = futureReward for that action...
https://stackoverflow.com/questions/60749628/
Deploying a hosted deep learning model on Heroku?
I currently want to deploy a deep learning REST API using Flask on Heroku. The weights (Its a pre-trained BERT model) are stored here*as a .zip file. Is there a way I can directly deploy these? From what I currently understand I have to have these uploaded on Github/S3. That's a bit of a hassle and seems pointless si...
Generally you can write a bash script that unzips the content and then you execute your program. However... Time Concern: Unpacking costs time. And the free tier heroku workers only work for roughly a day before being forcefully restarted. If you are operating a web dyno the restarts will be even more frequent and if...
https://stackoverflow.com/questions/60757087/
Understanding log_prob for Normal distribution in pytorch
I'm currently trying to solve Pendulum-v0 from the openAi gym environment which has a continuous action space. As a result, I need to use a Normal Distribution to sample my actions. What I don't understand is the dimension of the log_prob when using it : import torch from torch.distributions import Normal means = to...
If one takes a look in the source code of torch.distributions.Normal and finds the definition of the log_prob(value) function, one can see that the main part of the calculation is: return -((value - self.loc) ** 2) / (2 * var) - some other part where value is a variable containing values for which you want to calculat...
https://stackoverflow.com/questions/60765000/
Pytorch w/ GPU on Docker Container Error - no CUDA-capable device is detected
I am trying to use Pytorch with a GPU on my Docker Container. 1. On the Host - I have nvidia-docker installed, CUDA Driver etc Here is the nvidia-smi output from host: Fri Mar 20 04:29:49 2020 +-----------------------------------------------------------------------------+ | NVIDIA-SMI 440.64.00 Driver...
It needs runtime options, but well, the runtime option is not available at compose file format 3. So there's some options Downgrade your compose file version to 2, so something like this : version: 2 backend: build: ./app ports: - "5000:5000" volumes: - backend-data:/code links: - ...
https://stackoverflow.com/questions/60768583/
Torch.nn.Transformer Example Code Throwing Tensor Shape Errors
I was trying to implement a Transformer model with Pytorch and was experimenting with the example from this GitHub repo, which was linked from here in the documentation, and ran into a problem within the PositionalEncoding class, found within model.py. The code for the class's __init__() function is as follows: def _...
Try 0:51:2 instead of 0::2 0::2 will generate this -> [0,2,4,...,until the end of Elements]
https://stackoverflow.com/questions/60769118/
In pytorch, how can I sum some elements, and get a tensor of smaller shape?
Specifically I have a tensor of dimension 298x160x160 (faces in 298 frames), I need to sum every 4x4 element in last two dimesnion so that I can get a 298x40x40 tensor. How can I achieve that?
You could create a Convolutional layer with a single 4x4 channel and set its weights to 1, with a stride of 4 (also see Conv2D doc): a = torch.ones((298,160,160)) # add a dimension for the channels. Conv2D expects the input to be : (N,C,H,W) # where N=number of samples, C=number of channels, H=height, W=width a = a.un...
https://stackoverflow.com/questions/60769227/
Have you encountered the similar problem like loss jitter during training?
Background: It's about loss jittering which generates at the beginning stage of every training epoch. When the dataloader loads the first batch data to feed into the network, the loss value always rises suddenly, then returns to normal from the second batch and continues to decline. The curve is so strange. I need your...
You have a batch in your dataset that have high loss, that's it. It is not that common that people store metrics for every batch, usually it is the average over epoch (or average over multiple batch steps) that is stored. You won't see such spikes if you will store averages. You also could reduce these spikes by shu...
https://stackoverflow.com/questions/60774620/
Installing torchvision from source libavcodec/avcodec.h not found
I am trying to install torchvision from source, was able to get pytorch installed (needed it from source to use GPU) and now can't get torchvision to work. I am getting the following error when I run the setup.py: C:\Users\hoski\vision\torchvision\csrc\cpu\decoder\defs.h(11): fatal error C1083: Cannot open include...
Try change has_ffmpeg = ffmpeg_exe is not None in Setup.py to has_ffmpeg = False
https://stackoverflow.com/questions/60781599/
how to assign value to a tensor using index
I defined four tensors that represent index_x,index_y,index_z,and value,respectively and assigned value to a new tensor using these three index. Why were the results of the two assignments different? import torch import numpy as np import random import os def seed_torch(seed=0): random.seed(seed) np.random.se...
Can't add a comment, but when I run your exact code it returns tensor(0.) on my machine, so it seems to work just fine. Also, just a tip, instead of the for loop a_list, b_list, c_list = [], [], [] for i in range(0, 512*512): a_ = random.randint(0, 399) b_ = random.randint(0, 399) c_ = random.randint(0, 1...
https://stackoverflow.com/questions/60808314/
How update weights of two separate neural network with a computed loss?
I have an encoder and a proxy network that help the encoder to maximize information between its input(an image) and output (feature vector of image). to get this done, I used a loss function that estimate MI and by an optimizer the weights of both networks get updated with computed loss, but I'm not sure that does this...
If you have multiple networks, this is an example of how they would train encoder = Encoder(args).to(device) decoder = Decoder(args).to(device) params = list(encoder.parameters()) + list(decoder.parameters()) optimizer = torch.optim.Adam(params, learning_rate) And this is called on each batch: optimizer.zero_grad...
https://stackoverflow.com/questions/60815938/
Dimension mismatch CNN LibTorch/PyTorch
I have a CNN structure in LibTorch but the dimensions are not ok. My objective is to input a 3 channel 64x64 image and output a logistic regression float for a DGAN. Last layer I set as input channels 36 because if I remove that layer the output neuron had 6x6 dimension so I guesses that was the required dimension for ...
I had several issues but at the end this architecture worked. using namespace torch; class DCGANDiscriminatorImpl: public nn::Module { private: nn::Conv2d conv1, conv2, conv3, conv4; nn::BatchNorm2d batch_norm1, batch_norm2; nn::Linear fc1; public: DCGANDiscriminatorImpl() :conv1(nn::Conv2d...
https://stackoverflow.com/questions/60826846/
Pytorch crashes on input in eval mode
My model trains perfectly fine, but when I switch it to evaluation mode it does not like the data types of the input samples: Traceback (most recent call last): File "model.py", line 558, in <module> main_function(train_sequicity=args.train) File "model.py", line 542, in main_function out = model(use...
The errors seems to be clear: tgt is Float, but it was expecting it to be Long. Why? In your code, you define that go_tokens is torch.int64 (i.e., Long): def forward(self, tgt, memory): go_tokens = torch.zeros((1, tgt.size(1)), dtype=torch.int64) + 3 # GO_2 token has index 3 tgt = torch.cat([go_tokens, tgt],...
https://stackoverflow.com/questions/60838718/
Pytorch - Concatenating Datasets before using Dataloader
I am trying to load two datasets and use them both for training. Package versions: python 3.7; pytorch 1.3.1 It is possible to create data_loaders seperately and train on them sequentially: from torch.utils.data import DataLoader, ConcatDataset train_loader_modelnet = DataLoader(ModelNet(args.modelnet_root, cat...
If I got your question right, you have train and dev sets (and their corresponding loaders) as follows: train_set = CustomDataset(...) train_loader = DataLoader(dataset=train_set, ...) dev_set = CustomDataset(...) dev_loader = DataLoader(dataset=dev_set, ...) And you want to concatenate them in order to use train+dev ...
https://stackoverflow.com/questions/60840500/
Compute grads of cloned tensor Pytorch
I am having a hard time with gradient computation using PyTorch. I have the outputs and the hidden states of the last time step T of an RNN. I would like to clone my hidden states and compute its grad after backpropagation but it doesn't work. After reading pytorch how to compute grad after clone a tensor, I use...
Based on the comments the problem is that hidden_copy is never visited during the backward pass. When you perform backward pytorch follows the computation graph backwards starting at loss_T and works backwards to all the leaf nodes. It only visits the tensors which were used to compute loss_T. If a tensor isn't part o...
https://stackoverflow.com/questions/60853680/
Slice 4d tensor into 4D tensor of smaller subtensors (slice in last 2 dimensions only)
The question is analogous to Slice 2d array into smaller 2d arrays except for the fact that I use tensors (torch) & I have a 4D, not 2D, tensor of the shape eg. (3, 1, 32, 32) - in my case, it is 3 images of size 32x32. I want to split each tensor of form [i, 0, :, :] into smaller subarrays, so the output would h...
reshape will not work for this purpose. You could look into skimage's view_as_blocks, where the resulting blocks are non-overlapping views of the input array: from skimage.util.shape import view_as_blocks view_as_blocks(a, block_shape=(3,1,8,8)).reshape(3, 16, 8, 8)
https://stackoverflow.com/questions/60865167/
k-fold cross validation using DataLoaders in PyTorch
I have splitted my training dataset into 80% train and 20% validation data and created DataLoaders as shown below. However I do not want to limit my model's training. So I thought of splitting my data into K(maybe 5) folds and performing cross-validation. However I do not know how to combine the datasets to my dataload...
I just wrote a cross validation function work with dataloader and dataset. Here is my code, hope this is helpful. # define a cross validation function def crossvalid(model=None,criterion=None,optimizer=None,dataset=None,k_fold=5): train_score = pd.Series() val_score = pd.Series() total_size = len(...
https://stackoverflow.com/questions/60883696/
pytorch .cuda() can't get the tensor to cuda
I try to get my data onto gpu,but it doesn't work; in my train.py if __name__ == '__main__': ten = torch.FloatTensor(2) ten = ten.cuda() print(ten) args = config() train_net(args, args.train_net, loss_config=net_loss_config[args.train_net]) when it runs ,it prints this tensor([0., 0.]) the tensor is not on cuda ...
The error means that the ten variable in your model is of type torch.FloatTensor (CPU), while the input you provide to the model is of type torch.cuda.FloatTensor (GPU). The most likely scenario is that you have nn.Parameter or other modules such as nn.Conv2d defined in the __init__() method of your model, and additio...
https://stackoverflow.com/questions/60899711/
LSTM in PyTorch Classifying Names
I am trying the example presented in https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html but I am using a LSTM model instead of a RNN. The dataset is composed by different names (of different sizes) and their corresponding language (total number of languages is 18), and the objective is to ...
Lets dig into the solution step by step Frame the problem Given your problem statement, you will have to use LSTM for making a classification rather then its typical use of tagging. The LSTM is unrolled for certain timestep and this is the reason why input and ouput dimensions of a recurrent models are Input: batch...
https://stackoverflow.com/questions/60900346/
How to prevent inf while working with exponential
I'm trying to create a function in a network with trainable parameters. In my function I have an exponential that for large tensor values goes to infinity. What would the best way to avoid this be? The function is as follows: step1 = Pss-(k*Pvv) step2 = step1*s step3 = torch.exp(step2) step4 = torch.log10(1+step3) ...
One solution is to just use a more stable computation. Notice that log(1 + exp(x)) is approximately equal to x when x is large enough. Intuitively this can be observed by noting that, for example, exp(50) is approximately 5.18e+21 for which adding 1 will have no effect when using 32-bit floating point arithmetic like P...
https://stackoverflow.com/questions/60903821/