instruction stringlengths 13 150 | input stringlengths 36 29.1k | output stringlengths 31 29.5k | source stringlengths 45 45 |
|---|---|---|---|
PyTorch Model can only recognize birds when birds are close to camera | update 1
The easiest way to stop cropping images is: to pass in a tuple to size parameter.
So it looks like this:
size=(299,299)
Unfortunately, it does not solve my problem. So the question is still opening.
I just trained my birds model. It works fine when I was testing it with close pictures.
But when I move... | Your dataset is biased toward birds at a certain scale, i.e., their size, in pixels, span a very small range (you can verify this).
Center-cropping the images will not change that - the size of the birds (in pixels) will not change.
Therefore, your model cannot handle scale changes.
In order to overcome this limitatio... | https://stackoverflow.com/questions/59509006/ |
Convert pytorch tensor to opencv mat and vice versa in C++ | I want to convert pytorch tensors to opencv mat and vice versa in C++. I have these two functions:
cv::Mat TensorToCVMat(torch::Tensor tensor)
{
std::cout << "converting tensor to cvmat\n";
tensor = tensor.squeeze().detach().permute({1, 2, 0});
tensor = tensor.mul(255).clamp(0, 255).to(torch::kU8);
... | Not sure if the error is happening at the memcpy step. But you can use the void* data variant of the Mat constructor
Mat (int rows, int cols, int type, void *data, size_t step=AUTO_STEP)
and you can skip the memcpy step
tensor = uint8_tensor //shape: (h, w, 3)
cv::Mat mat = cv::Mat(height, width, CV_8UC3, tensor.data_... | https://stackoverflow.com/questions/59512310/ |
'Sequential' object has no attribute 'features' while extracting vgg19 pytorch features |
I'm trying to extract the features of images using VGG19 network (the output should be of dim : [1 , 7 , 7 , 512] per frame
here is the code I have used :
deep_net = models.vgg19(pretrained=True).cuda()
deep_net = nn.Sequential(*list(deep_net.children())[:-2])
deep_net.eval()
save_file_sample_path = ... | It's because you are rebuilding deep_net with nn.Sequential so it loses the attribute features.
deep_net = models.vgg19(pretrained=True)
deep_net.features
Sequential(
(0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
(1): ReLU(inplace=True)
...
(36): MaxPool2d(kernel_size=2, stride=2, pad... | https://stackoverflow.com/questions/59512941/ |
Fast.Ai EarlyStoppingCallback does not work |
callbacks = [EarlyStoppingCallback(learn, monitor='error_rate', min_delta=1e-5, patience=5)]
learn.fit_one_cycle(30, callbacks=callbacks, max_lr=slice(1e-5,1e-3))
As you can see, I use patience = 5 and min_delta=1e-5 and monitor='error_rate'
My understanding is: patience tells how many epochs it waits if improv... | It keeps track of the best error rate and compares the min_delta to the difference between this epoch and that value:
class EarlyStoppingCallback(TrackerCallback):
...
if self.operator(current - self.min_delta, self.best):
self.best,self.wait = current,0
else:
self.wait += 1
if self.wait > self.patience... | https://stackoverflow.com/questions/59517321/ |
torch.max slower with GPU than with CPU when specifying dimension | t1_h = torch.tensor(np.arange(100000), dtype=torch.float32)
cuda0 = torch.device('cuda:0')
t1_d = torch.tensor(np.arange(100000), dtype=torch.float32, device = cuda0)
%timeit -n 10000 max_h = torch.max(t1_h, 0)
%timeit -n 10000 max_d = torch.max(t1_d, 0)
10000 loops, best of 3: 144 µs per loop
10000 loops, best of 3... | I discovered this myself, and opened an issue in PyTorch. It looks like it'll be fixed soon - maybe version 1.5 or 1.6? - but in the meantime the suggested workaround is to use
ii=a.argmax(0)
maxval = a.gather(0, ii.unsqueeze(0)).squeeze(0)
| https://stackoverflow.com/questions/59517626/ |
PyTorch CNN: Loss is unchanging | I have tried researching a situation for my unchanging loss, and all the answers I found were specific to the code. I just started learning about CNNs and majority of the CNN is from an example and modified to fit the needs of my dataset. I am trying to classify types of ECGs (normal, atrial fibrillation, other, noisy)... | At the end of your network there's a softmax layer but in your training you use MSELoss. This tells me that your model is outputting probabilities but then you are calculating loss as if it is continuous. Not sure exactly how that is working for you but I would suspect this is a reason for faulty loss.
As mentioned be... | https://stackoverflow.com/questions/59525926/ |
FastAI PyTorch Train_loss and valid_loss look very good, but the model recognize nothing | Update 1
I’m thinking that it might be the mistake in my detector code.
So, here is my code for using the trained learner/model to predict images.
import requests
import cv2
bytes = b''
stream = requests.get(url, stream=True)
bytes = bytes + stream.raw.read(1024) # I have my mobile video streaming to this url. the r... | Your learning rate schedule is sub-optimal for this dataset. Try to first figure out the best learning rate for this network and dataset with
LRFinder. This can be done by exploring the loss behavior for different learning rates with
learn.lr_find()
learn.recorder.plot()
Edit:
It looks like you are re-training th... | https://stackoverflow.com/questions/59548794/ |
Language translation using TorchText (PyTorch) | I have recently started with ML/DL using PyTorch. The following pytorch example explains how we can train a simple model for translating from German to English.
https://pytorch.org/tutorials/beginner/torchtext_translation_tutorial.html
However I am confused on how to use the model for running inference on custom inpu... | Yes globally what you are saying is correct, and of course you can any vocab, e.g. provided by spacy. To convert a tensor into natrual text, one of the most used thechniques is to keep both a dict that maps indexes to words and an other dict that maps words to indexes, the code below can do this:
tok2idx = defaultdict(... | https://stackoverflow.com/questions/59549980/ |
Numpy / PyTorch - how to assign value with indices in different dimensions? | Suppose I have a matrix and some indices
a = np.array([[1, 2, 3], [4, 5, 6]])
a_indices = np.array([[0,2], [1,2]])
Is there any efficient way to achieve following operation?
for i in range(2):
a[i, a_indices[i]] = 100
# a: np.array([[100, 2, 100], [4, 100, 100]])
| Use np.put_along_axis -
In [111]: np.put_along_axis(a,a_indices,100,axis=1)
In [112]: a
Out[112]:
array([[100, 2, 100],
[ 4, 100, 100]])
Alternaytively, if you want to do with the explicit way, i.e. integer-based indexing -
In [115]: a[np.arange(len(a_indices))[:,None], a_indices] = 100
| https://stackoverflow.com/questions/59551458/ |
Running a PyTorch dataloader/Dataset on multiple distributed CPUs | I wonder if there is a way to distributed the dataloader/Dataset to many CPUs, even when using a single GPU.
Specifically, I would like to have a Dataset class, and the __getitem__ function will be distributed across many different CPUs (using mpi maybe? but any other way is also good).
Thanks
EDIT
My title was erroneo... | You can do this of course, but mind you - it is not always very effective for general Machine Learning needs, due to the hefty communication costs.
Use DistributedDataParallel
Implements distributed data parallelism that is based on
torch.distributed package at the module level.
This container parallelizes t... | https://stackoverflow.com/questions/59552122/ |
Padding a tensor until reaching required size | I'm working with certian tensors with shape of (X,42) while X can be in a range between 50 to 70.
I want to pad each tensor that I get until it reaches a size of 70. so all tensors will be (70,42).
is there anyway to do this when I the begining size is a variable X? thanks for the help!
| Use torch.nn.functional.pad - Pads tensor.
import torch
import torch.nn.functional as F
source = torch.rand((3,42))
source.shape
>>> torch.Size([3, 42])
# here, pad = (padding_left, padding_right, padding_top, padding_bottom)
source_pad = F.pad(source, pad=(0, 0, 0, 70 - source.shape[0]))
source_pad.shap... | https://stackoverflow.com/questions/59553580/ |
Why does loss decrease but accuracy decreases too (Pytorch, LSTM)? | I have built a model with LSTM - Linear modules in Pytorch for a classification problem (10 classes). I am training the model and for each epoch I output the loss and accuracy in the training set. The ouput is as follows:
epoch: 0 start!
Loss: 2.301875352859497
Acc: 0.11388888888888889
epoch: 1 start!
Loss: 2.... | Decreasing loss does not mean improving accuracy always.
I will try to address this for the cross-entropy loss.
CE-loss= sum (-log p(y=i))
Note that loss will decrease if the probability of correct class increases and loss increases if the probability of correct class decreases. Now, when you compute average loss, ... | https://stackoverflow.com/questions/59554880/ |
Pytorch on Google VM (Linux) does not recognize GPU | I created a Google VM instance using this available image:
c1-deeplearning-common-cu100-20191226
Description
Google, Deep Learning Image: Base, m39 (with CUDA 10.0), A Debian based image with CUDA 10.0
I then installed Anaconda onto this VM, then installed Pytorch using the following command line as recommended by... | I was able to resolve the issue. Not being a computer science guy, I figured that it could be an nvidia driver compatibility issue. Since Pytorch was built using CUDA 10.1 driver, and the deep learning image had CUDA 10.0 installed, I created another VM instance but this time instead of using the public image noted e... | https://stackoverflow.com/questions/59557542/ |
Merge two tensor in pytorch | Tensor a:
tensor([[1, 2, 3],
[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
Tensor b:
tensor([4,4,4,4])
Question 1:
How to merge two tensors and get result c:
tensor([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
Question 2: How to divide tensor c and get original... | Question 1: Merge two tensors -
torch.cat((a, b.unsqueeze(1)), 1)
>>> tensor([[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4]])
First, we use torch.unsqueeze to add single dim in b tensor to match a dim to be concanate. Then use torch.cat Concatenates tensors a ... | https://stackoverflow.com/questions/59558460/ |
What is the difference between model.to(device) and model=model.to(device)? | Suppose the model is originally stored on CPU, and then I want to move it to GPU0, then I can do:
device = torch.device('cuda:0')
model = model.to(device)
# or
model.to(device)
What is the difference between those two lines?
| No semantic difference. nn.Module.to function moves the model to the device.
But be cautious.
For tensors (documentation):
# tensor a is in CPU
device = torch.device('cuda:0')
b = a.to(device)
# a is still in CPU!
# b is in GPU!
# a and b are different
For models (documentation):
# model a is in CPU
device = torch.de... | https://stackoverflow.com/questions/59560043/ |
How to implying bagging method for LSTM neural network using pyTorch? | Like the title, my question is how to apply the Bagging method for LSTM using the PyTorch library? I have built one using TensorFlow on python. But now to implied into the system using C and C++, the requirement is I need to using PyTorch?
Is there any recommendation for not need to use the PyTorch and applying direct... | If you want to create an ensemble in PyTorch, you can train multiple models separately and then define a class to use them together:
class MyEnsemble(nn.Module):
def __init__(self, firstModel, secondModel):
super(MyEnsemble, self).__init__()
self.firstModel = modelA
self.secondModel = model... | https://stackoverflow.com/questions/59560372/ |
How can I optimize the 5-layer loop using functions provided by torch? | x is the tensor with the shape of (16, 10, 4, 25, 53), y has the same size as x.
mean's shape is (25, 53), the size of jc and ac are both (16, 10, 4).
How can I optimize the following expression with torch functions?
for k in range(x.size()[0]):
for s in range(x.size()[1]):
for u in range(x.size()[2]):
... | I think you are looking at broadcasting your tensors along singleton dimensions.
First, you need the number of dimensions to be the same, so if mean is of shape (25,53) then mean[None, None, None, ...] is of shape (1, 1, 1, 25, 53) - you did not change anything in the underlying data, but the number of dimensions is no... | https://stackoverflow.com/questions/59561002/ |
What does the interleave_keys() function in torchtext library do exactly? | You can find this function at torchtext/data/utils.py file
I have given the official code with documentation below
def interleave_keys(a, b):
"""Interleave bits from two sort keys to form a joint sort key.
Examples that are similar in both of the provided keys will have similar
values for the key defined... | So upon breaking down the function I was able to figure out what this function is doing.
format(x, '016b') This piece of code converts the integer (a and b which is actually no of words in the sentences in my case) to 16 digit binary number.
And the interleave function takes out the pairs (of the same position) of bi... | https://stackoverflow.com/questions/59564451/ |
Is there any method to generate a piecewise function for tensors in pytorch? |
I want to get a piecewise function like this for tensors in pytorch. But I don't know how to define it. I use a very stupid method to do it, but it seems not to work in my code.
def trapezoid(self, X):
Y = torch.zeros(X.shape)
Y[X % (2 * pi) < (0.5 * pi)] = (X[X % (2 * pi) < (0.5 * pi)] % (... | Since your function has period 2π we can focus on [0,2π]. Since it's piecewise linear, it's possible to express it as a mini ReLU network on [0,2π] given by:
trapezoid(x) = 1 - relu(x-1.5π)/0.5π - relu(0.5π-x)/0.5π
Thus, we can code the whole function in Pytorch like so:
import torch
import torch.nn.functional as F
fro... | https://stackoverflow.com/questions/59578581/ |
PyTorch: is there a definitive training loop similar to Keras' fit()? | I'm coming over from Keras to PyTorch, and one of the surprising things I've found is that I'm supposed to implement my own training loop.
In Keras, there is a de facto fit() function that: (1) runs gradient descent and (2) collects a history of metrics for loss and accuracy over both the training set and validation s... | Short answer: there is no equivalent training loop for PT and TF.keras and there shall never be one.
First of all, the training loop is syntactical sugar that is supposed to makes one's life easier. From my point of view, "making life easier" is a moto of TF.keras framework and this is the main reason it has it. Train... | https://stackoverflow.com/questions/59584457/ |
Pass user specified parameters to DataLoader | I am using U - Net and implementing the weighting technique described in the papers from 2015 (U-Net: Convolutional Networks for Biomedical
Image Segmentation) and 2019 (U-Net – Deep Learning for Cell Counting, Detection, and Morphometry). In that technique there is a variance σ and a weight w_0. I would like, especial... | What you need to do is to set sigma as an attribute of the Dataset and change it between epochs.
For the dataset definition
class UNetDataset(object):
def __init__(self, ..., sigma=5):
self.sigma = sigma
Now, within __getitem__, you can use the sigma value using self.sigma
Now within your training ... | https://stackoverflow.com/questions/59586493/ |
How could I know whether a function in Pytorch allocates new memory or not? | Recently, I got stuck in a situation that, in my model, the input data really consumed a lot of memory. And this lead to a lot of memory usage when I operate the data in my network layers. I really want to know whether the operations will allocate new memory block or not. I saw the pytorch doc only found how to use the... | If you are running on a GPU, the best way to check memory consumption is to use the linux command nvidia-smi. You can call this in jupyter-notebook using !nvidia-smi. This way, after any Pytorch command, you can check if new memory has been allocated or not
| https://stackoverflow.com/questions/59591601/ |
How can I get hidden_states from BertForSequenceClassification? | I read the official tutorial(https://huggingface.co/transformers/model_doc/bert.html) and tried to set config, but it doesn't work.
from transformers import PretrainedConfig
model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2)
model.config.output_hidden_states = True
model.load_stat... | Output should be a list that holds the hidden states. I expect that because you are loading the parameter.pkl which may not have output hidden states by default, it is overwriting your config.output_hidden_states to False? See what happens if you set it to True after loading the state_dict?
| https://stackoverflow.com/questions/59592736/ |
What is the correct way to measure the total execution time for a pytorch function running on GPU? | Following is an example code showing what I am trying to measure. Here I am using time.perf_counter() to measure time. Is this the correct way to measure execution time in this scenario? If not, what is the correct way? My concern is, GPU evaluations are asynchronous and GPU execution might not be completed when ExecTi... | I think you are looking for pyotrch's bottleneck profiler.
| https://stackoverflow.com/questions/59596483/ |
About pytorch learning rate scheduler | here is my code
optimizer = optim.SGD(net.parameters(), lr=0.1)
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.5)
for i in range(15):
lr = scheduler.get_lr()[0]
lr1 = optimizer.param_groups[0]["lr"]
print(i, lr, lr1)
scheduler.step()
And here is the result
0 0.1 0.1
1 0.1 0.1... | Yes, the "problem" is in the use of get_lr(). To get the current LR, what you need is actually the get_last_lr().
If you take a look at the implementation:
def get_lr(self):
if not self._get_lr_called_within_step:
warnings.warn("To get the last learning rate computed by the scheduler, "
... | https://stackoverflow.com/questions/59599603/ |
Method for feeding multi-class image data-set where folders name can be used as labels in Pytorch? | I want to feed the multiclass image data-set in Pytorch, in the main folder of data-set I have 15 more folders with different names, I want to use folders names as the labels.
For example, one folder name is Aeroplanes and contain the images (1245 images) other folder name is Cars and contains images of the Cars (997)... | To split your dataset into train and test datasets you could use random_split function:
import torch
from torchvision import datasets, transforms
from torch.utils import data
import numpy as np
dataset = datasets.ImageFolder('path_to_dataset', transform=transforms.ToTensor())
lengths = [int(np.ceil(0.5*len(dataset))... | https://stackoverflow.com/questions/59603064/ |
Pytorch mask tensor with boolean numpy array | I have a 84x84 pytorch tensor named target. I need to mask it with an 84x84 boolean numpy array which consists of True and False.
When I do target = target[mask], I get the error TypeError: can't convert np.ndarray of type numpy.bool_. The only supported types are: double, float, float16, int64, int32, and uint8.
Su... | I think there is some confusion with the types. But this works.
import torch
tensor = torch.randn(84,84)
c = torch.randn(tensor.size()).bool()
c[1, 2:5] = False
x = tensor[c].size()
For testing I created a tensor with random values. Afterwards 3 elements are set to False. In the last step I look get the size 7053 re... | https://stackoverflow.com/questions/59604918/ |
AttributeError: 'MpoImageFile' object has no attribute 'shape' | images, labels = next(iter(self.loader))
grid = torchvision.utils.make_grid(images)
images, labels = next(iter(self.loader))
triggers the error.
I have a custom dataset class where I load each image (RGB) from an url :
image = Image.open(urllib.request.urlopen(URL))
and I apply some albumentations transfo... | In order to work with albumentations, you must pass a numpy array to the transforms not a PIL image. So:
image = Image.open(urllib.request.urlopen(URL))
image = np.array(image)
| https://stackoverflow.com/questions/59613693/ |
Understanding Pytorch Grid Sample | I have a input tensor of size [1,32,296,400]
and I have a pixel set of [1, 56000, 400, 2]
After applying grid_sample with mode=‘bilinear’ I have [1, 32, 56000, 400]
Can I know what exactly happened here? I know that grid_sample is suppose to effective transform pixels to a new location in a differentiable manner, bu... | Please look at the documentation of grid_sample.
Your input tensor has a shape of 1x32x296x400, that is, you have a single example in the batch with 32 channels and spatial dimensions of 296x400 pixels.
Additionally, you have a "grid" of size 1x56000x400x2 which PyTorch interprets as new locations for a grid ... | https://stackoverflow.com/questions/59620104/ |
Trying to mask tensor with another tensor of same dimension getting "index 1 is out of bounds for dimension 0 with size 1" | attn_weights = F.softmax(self.attn(torch.cat((input, hidden_cat), 2)), dim=2)
attn_weights[mask] = float('-inf')
attn_applied = torch.bmm(attn_weights.transpose(0,1),encoder_outputs.transpose(0,1)).transpose(0,1)
attn_output = torch.cat((input, attn_applied), 2)
So I'm trying to set all the indexes in... | turns out the dtype for mask tensor had to be torch.uint8 or torch.bool I had it torch.long
| https://stackoverflow.com/questions/59620154/ |
Pytorch: can we use nn.Module layers directly in forward() function? | Generally,
In the constructor, we declare all the layers we want to use.
In the forward function, we define how the model is going to be run, from input to output.
My question is what if calling those predefined/built-in nn.Modules directly in forward() function? Is this Keras function API style legal for Pytorch? If ... | You need to think of the scope of the trainable parameters.
If you define, say, a conv layer in the forward function of your model, then the scope of this "layer" and its trainable parameters is local to the function and will be discarded after every call to the forward method. You cannot update and train weights tha... | https://stackoverflow.com/questions/59642925/ |
Basic Pytorch tensor multiplication and addition | I just realize I lack some very basic pytorch tensor math. How do I do the following with a pytorch tensor?
lab_rs = (lab_rs * [100, 255, 255] - [0, 128, 128])
This works well in numpy. It's an image with shape (3, 512, 1024) and I want to multiply and subtract values from each color channel individually
The error I... | You need to make sure all your operands can be broadcast to the same dimensions:
lab_rs = lab_rs * torch.tensor([[[100]], [[255]], [[255.]]]) - torch.tensor([[[0]], [[128]], [[128.]]])
| https://stackoverflow.com/questions/59657761/ |
PyTorch - How to use k-fold cross validation when the data is loaded through ImageFolder? | My data, which is images, is stored on the filesystem, and it is fed into my convolutional neural network through the ImageFolder data loader of PyTorch. Therefore, the training, validation, and test data is manually splitted into different folders on the filesystem. So, how can I apply k-fold cross validation when usi... | You can merge the fixed train/val/test folds you currently have using data.ConcatDataset into a single Dataset. Then you can use data.Subset to randomly split the single dataset into different folds over and over.
| https://stackoverflow.com/questions/59663573/ |
How to get quick documentation working with PyCharm and Pytorch | I'm running PyCharm on Windows 10, and installed PyTorch following the getting started guide. Where I used Chocolatey and Anaconda to set up everything.
I can run the PyTorch tutorials from inside the PyCharm IDE without any problems. So I feel like I have a proper set up, but there aren't any intellisense documentati... | I was able to get it working by doing the following:
PyStorm 2019.3
Open the settings for external documentation:
File / Settings / Tools / External Documentation
Add the following URL patterns:
Module Name: torch.nn.functional
URL: https://pytorch.org/docs/stable/nn.functional.html#{element.qname}... | https://stackoverflow.com/questions/59664464/ |
What does torchvision.transforms.Resize(size, interpolation=2) actually do? | Does it add to the image if too small or crop if too big or just stretch the image to the desired size?
| When you set interpolation=2, then you are using Bilinear interpolation, ti can be either used for upsampling or down sampling. In the case of upsampling you are doing something like
There are several types of upsampling and down-sampling, but bilinear one uses a combination of the neighbouring pixels to cimpute the ... | https://stackoverflow.com/questions/59666923/ |
RoBERTa classification RuntimeError: shape '[-1, 9]' is invalid for input of size 8 | m = MultiLabelBinarizer()
X = pd.read_csv('data/data.csv', sep=None, engine='python')
X = X.dropna()
Y_train = m.fit_transform(X['labels'])
Y_train2 = [list(i) for i in Y_train]
data = pd.DataFrame({'text': pd.Series(X[text_col]), 'labels': Y_train2})
data = data.dropna()
train_df, e... | [0,1,0,0,0,1,0,0] - it is 8 size, but your model expect size 9.
it means that, your numLabels = 9. If you have 9 classes, then the label-list in the label-colum should be like this: [0,1,0,0,0,1,0,0,0].
But I think you just need to pass the num_labels as 8
| https://stackoverflow.com/questions/59684472/ |
'int' object has no attribute 'size'" | F.nll_loss: I am getting
AttributeError: 'int' object has no attribute 'size'
when I try to run this code. I also get a snippet of the module code.
raise ValueError('Expected 2 or more dimensions (got {})'.format(dim))
if input.size(0) != target.size(0):
raise ValueError('Expected input batch_s... | Just change the for loop from:
for data in train_dataset:
to
for data in train_loader:
| https://stackoverflow.com/questions/59691234/ |
torch find indices of matching rows in 2 2D tensors | I have two 2D tensors, in different length, both are different subsets of the same original 2d tensor and I would like to find all the matching "rows"
e.g
A = [[1,2,3],[4,5,6],[7,8,9],[3,3,3]
B = [[1,2,3],[7,8,9],[4,4,4]]
torch.2dintersect(A,B) -> [0,2] (the indecies of A that B also have)
I've only see numpy sol... | This answer was posted before the OP updated the question with other restrictions that changed the problem quite a bit.
TL;DR You can do something like this:
torch.where((A == B).all(dim=1))[0]
First, assuming you have:
import torch
A = torch.Tensor([[1,2,3],[4,5,6],[7,8,9]])
B = torch.Tensor([[1,2,3],[4,4,4],[7... | https://stackoverflow.com/questions/59705001/ |
How to calculate geometric mean in a differentiable way? | How to calculate goemetric mean along a dimension using Pytorch? Some numbers can be negative. The function must be differentiable.
| A known (reasonably) numerically-stable version of the geometric mean is:
import torch
def gmean(input_x, dim):
log_x = torch.log(input_x)
return torch.exp(torch.mean(log_x, dim=dim))
x = torch.Tensor([2.0] * 1000).requires_grad_(True)
print(gmean(x, dim=0))
# tensor(2.0000, grad_fn=<ExpBackward>)
This... | https://stackoverflow.com/questions/59722983/ |
PyTorch - Custom ReLU squared Implementation | I work on a project and I want to implement the ReLU squared activation function (max{0,x^2}). Is it ok to call it like:
# example code
def forward(self, x):
s = torch.relu(x**2)
return s
Or should I implement the activation function on my own? In the second case could you please provide me an ex... | It doesn't make much sense to compute max(0, x**2) because x**2 >= 0 no matter what.
You probably want to compute max(0, x) ** 2 instead:
s = torch.pow(torch.relu(x), 2)
| https://stackoverflow.com/questions/59749991/ |
How to use pytorch to construct multi-task DNN, e.g., for more than 100 tasks? | Below is the example code to use pytorch to construct DNN for two regression tasks. The forward function returns two outputs (x1, x2). How about the network for lots of regression/classification tasks? e.g., 100 or 1000 outputs. It definitely not a good idea to hardcode all the outputs (e.g., x1, x2, ..., x100). Is the... | You can (and should) use nn containers such as nn.ModuleList or nn.ModuleDict to manage arbitrary number of sub-modules.
For example (using nn.ModuleList):
class MultiHeadNetwork(nn.Module):
def __init__(self, list_with_number_of_outputs_of_each_head):
super(MultiHeadNetwork, self).__init__()
self... | https://stackoverflow.com/questions/59763775/ |
TensorFlow / PyTorch: Gradient for loss which is measured externally | I am relatively new to Machine Learning and Python.
I have a system, which consists of a NN whose output is fed into an unknown nonlinear function F, e.g. some hardware. The idea is to train the NN to be an inverse F^(-1) of that unknown nonlinear function F. This means that a loss L is calculated at the output of F.... | AFAIK, all modern deep learning packages (pytorch, tensorflow, keras etc.) are relaying on gradient descent (and its many variants) to train networks.
As the name suggests, you cannot do gradient descent without gradients.
However, you might circumvent the "non differentiability" of your "given" function F by looking ... | https://stackoverflow.com/questions/59766210/ |
How to circumvent AWS package and ephemeral limits for large packages + large models | We have a production scenario with users invoking expensive NLP functions running for short periods of time (say 30s). Because of the high load and intermittent usage, we're looking into Lambda function deployment. However - our packages are big.
I'm trying to fit AllenNLP in a lambda function, which in turn depends ... | You could deploy your models to SageMaker inside of AWS, and run Lambda -> Sagemaker to avoid having to load up very large functions inside of a Lambda.
Architecture explained here - https://aws.amazon.com/blogs/machine-learning/call-an-amazon-sagemaker-model-endpoint-using-amazon-api-gateway-and-aws-lambda/
| https://stackoverflow.com/questions/59771715/ |
Pytorch, backprop and composite models | Just a quick check for a question I have.
I want to build a model that generates its output based on two models F and G like so.
y = G(F(x))
where x is of course the input, and y the output.
However, first I want to update the weights of the F(x) and then later update the weights of both F and G based on the value ... | If as you suggest, the optimizers and losses for F and G can be separated, then I don't think that it will be necessary to implement any different update functionalities since you can specify the set of parameters for each optimizer, e.g.
optimizer_F = optim.SGD(F.parameters(),...)
optimizer_G = optim.SGD(G.parameters... | https://stackoverflow.com/questions/59772000/ |
How can I load a model in PyTorch without redefining the model? | I am looking for a way to save a pytorch model, and load it without the model definition. By this I mean that I want to save my model including model definition.
For example, I would like to have two scripts. The first would define, train, and save the model. The second would load and predict the model without includi... | You can attempt to export your model to TorchScript using tracing. This has limitations. Due to the way PyTorch constructs the model's computation graph on the fly, if you have any control-flow in your model then the exported model may not completely represent your python module. TorchScript is only supported in PyTorc... | https://stackoverflow.com/questions/59774328/ |
Inference pytorch C++ with alexnet and cv::imread image | I am trying to infer with a C++ application an image classification task using an alexnet pre-trained net.I have successfully inferred a dog image loading the net with python:
alexnet = torchvision.models.alexnet(pretrained=True)
img = Image.open("dog.jpg")
transform = transforms.Compose([
transforms.Resize(256), ... | Your C++ code is missing this part of your Python code:
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225] ... | https://stackoverflow.com/questions/59783791/ |
Pytorch equivalent of tf.Variable | I am trying to implement this code in pytorch:
self.scale_var = tf.Variable(
0.1, name='scale_var',
trainable=True,
dtype=tf.float32,
constraint=lambda x: tf.clip_by_value(x, 0, np.infty))
I want to have a scalar value that is trainable and would like to scale a constant with ... | In PyTorch, Variable and Tensor were merged, so you are correct that a scalar variable should just be a scalar tensor.
In isolation:
>>> x=torch.tensor(5.5, requires_grad=True)
>>> x.grad
>>> x.backward(torch.tensor(12.4))
>>> x.grad
tensor(12.4000)
0.001 is a common learning rat... | https://stackoverflow.com/questions/59800247/ |
How to install torch in python | I tried pip3 install torch --no-cache-dir and, after few seconds, I got this:
Collecting torch
Downloading https://files.pythonhosted.org/packages/24/19/4804aea17cd136f1705a5e98a00618cb8f6ccc375ad8bfa437408e09d058/torch-1.4.0-cp36-cp36m-manylinux1_x86_64.whl (753.4MB)
100% |██████████████████████████████... | For pip environment use this
pip3 install torchvision
For conda environment use this (run this command on anaconda prompt)
conda install PyTorch -c PyTorch
Update
Use this code to turn off your cache
pip3 --no-cache-dir install torchvision
or
pip3 install torchvision--no-cache-dir
or
pip install --no-ca... | https://stackoverflow.com/questions/59800318/ |
Resize RGB Tensor pytorch | I want to resize a 3-D RBG tensor in pytorch. I know how to resize a 4-D tensor, but unfortunalty this method does not work for 3-D.
The input is:
#input shape: [3, 100, 200] ---> desired output shape: [3, 80, 120]
if I have a 4-D vector it works fine.
#input shape: [2, 3, 100, 200]
out = torch.nn.functional.... | Thanks to jodag I found the answer:
# input shape [3, 200, 120]
T = T.unsqueeze(0)
T = torch.nn.functional.interpolate(T,size=(100,80), mode='bilinear')
T = T.squeeze(0)
# output shape [3, 100, 80]
| https://stackoverflow.com/questions/59803041/ |
Unable to allocate GPU memory, when there is enough of cached memory | I am training vgg16 model from scratch on AWS EC2 Deep Learning AMI machine (Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0-1054-aws x86_64v)) with Python3 (CUDA 10.1 and Intel MKL) (Pytorch 1.3.1) and facing below error while updating model parameters.
RuntimeError: CUDA out of memory. Tried to allocate 24.00 MiB (GPU 0; 11... | Finally I solved the memory problem! I realized that in each iteration I put the input data in a new tensor, and pytorch generates a new computation graph.
That causes the used RAM to grow forever. Then I used .detach() function, and the RAM always stays at a low level.
self.model(input.cuda().float()).detach().requ... | https://stackoverflow.com/questions/59805901/ |
pytorch 1D Dropout leads to unstable learning | I'm implementing an Inception-like CNN in pytorch. After the blocks of convolution layers, I have three fully-connected linear layers followed by a sigmoid activation to give me my final regression output. I'm testing the effects of dropout layers in this network, but it's giving me some unexpected results.
Here is ... | I cracked the case. I realized that I flip model.train() to model.eval() in the test call without setting it back to train() after. Since Dropout behaves differently in train and eval modes, adding in Dropout revealed the bug.
| https://stackoverflow.com/questions/59815381/ |
How to remove certain layers from Fastern-RCNN in Pytorch? | Target: I want to use the pretrained Faster-RCNN model to extract features from image.
What I have tried: I use below code to build the model:
import torchvision.models as models
from PIL import Image
import torchvision.transforms as T
import torch
# download the pretrained fasterrcnn model
model = models.detection.... | print(model.modules) to get the layer names. Then delete a layer with:
del model.my_layer_name
| https://stackoverflow.com/questions/59816287/ |
Make PyTorch variables to float64 | How to make all the variables created in a PyTorch file to float64?
Is there a single line of code which can do that?
| You can set the default tensor type using this one-liner:
torch.set_default_tensor_type(torch.DoubleTensor)
| https://stackoverflow.com/questions/59826670/ |
Multiplying and powering python float and pytorch integer | Why does a python float multiplied by a torch.long gives a torch.float but powering a float by a torch.long gives a torch.long?
>>> a = 0.9
>>> b = torch.tensor(2, dtype=torch.long)
>>> foo = a * b
>>> print(foo, foo.dtype)
tensor(1.8000) torch.float32
>>> bar = a ** b
&... | This looks like a bug, probably in the way pytorch binds ** to __rpow__ or __pow__.
E.g. if you tried 0.9 - torch.tensor(2), since 0.9 isn't a tensor, this gets interpreted as torch.tensor(2).__rsub__(0.9), which works correctly. ** behaves the same way, but torch.tensor(2).__rpow__(0.9) incorrectly returns tensor(0) ... | https://stackoverflow.com/questions/59827509/ |
layer Normalization in pytorch? | shouldn't the layer normalization of x = torch.tensor([[1.5,0,0,0,0]]) be [[1.5,-0.5,-0.5,-0.5]] ? according to this paper paper and the equation from the pytorch doc. But the torch.nn.LayerNorm gives [[ 1.7320, -0.5773, -0.5773, -0.5773]]
Here is the example code:
x = torch.tensor([[1.5,.0,.0,.0]])
layerNorm = torch... | Yet another simplified implementation of a Layer Norm layer with bare PyTorch.
from typing import Tuple
import torch
def layer_norm(
x: torch.Tensor, dim: Tuple[int], eps: float = 0.00001
) -> torch.Tensor:
mean = torch.mean(x, dim=dim, keepdim=True)
var = torch.square(x - mean).mean(dim=dim, keepdim=T... | https://stackoverflow.com/questions/59830168/ |
Bitwise operations in Pytorch | Could someone help me how to perform bitwise AND operations on two tensors in Pytorch 1.4?
Apparently I could only find NOT and XOR operations in official document
| I don't see them in the docs, but it looks like &, |, __and__, __or__, __xor__, etc are bit-wise:
>>> torch.tensor([1, 2, 3, 4]).__xor__(torch.tensor([1, 1, 1, 1]))
tensor([0, 3, 2, 5])
>>> torch.tensor([1, 2, 3, 4]) | torch.tensor([1, 1, 1, 1])
tensor([1, 3, 3, 5])
>>> torch.tensor([1, ... | https://stackoverflow.com/questions/59843006/ |
How to specify pytorch as a package requirement on windows? | I have a python package which depends on pytorch and which I’d like windows users to be able to install via pip (the specific package is: https://github.com/mindsdb/lightwood, but I don’t think this is very relevant to my question).
What are the best practices for going about this ?
Are there some project I could use... |
What are the best practices for going about this ?
If your project depends on other projects that are not distributed through PyPI then you have to inform the users of your project one way or another. I recommend the following combination:
clearly specify (in your project's documentation pages, or in the project... | https://stackoverflow.com/questions/59856930/ |
PyTorch: How to define a new neural network that utilizes transfer learning | I am migrating from Keras/TF frameworks and I have litte troubles understanding the transfer learning process in PyTorch.
I want to use pytorch-lightning framework and I want to switch between different neural networks in one script.
Per this example we can switch between different neural networks in their implementa... | you can freeze weights and bais for the neural network layer except for the last layer.
you can use requires_grad = False
for param in model_conv.parameters():
param.requires_grad = False
you can find more about this at the following link
https://pytorch.org/tutorials/beginner/transfer_learning_tutorial.html
| https://stackoverflow.com/questions/59858824/ |
PyTorch allocates more memory on the first available GPU (cuda:0) | As a part of the reinforcement learning training system, I am training four policies in parallel using four GPUs. For each model, there are two processes - the actor and the learner, which only use their specific GPU (e.g. actor and learner corresponding to model #2 only use GPU #2 for all their tensors). Actor and lea... | Ok, so far I came up with a workaround. My hypothesis was right, if PyTorch CUDA subsystem is already initialized before the child process is forked, setting CUDA_VISIBLE_DEVICES to a different value for a subprocess does not do anything.
Even worse, calling torch.cuda.device_count() is enough to initialize CUDA, so w... | https://stackoverflow.com/questions/59873577/ |
Python process never finishing when called from Java | I've tried to setup an AI with PyTorch. Everything is fine when I call my script from the console. But when I call the script in a Java `ProcessBuildera, it will finish but never terminate...
Here is the ProcessBuilder code
String[] cmd = {"python3", "-i" , "AI/Home-System.py",
data.getName().replace(... | Read the process' output stream, as the end of this stream allows your ProcessBuilder to exit. Or else call the ProcessBuilder's inheritIO().
Then waitFor() the process.
Here is some sample code showing these steps.
| https://stackoverflow.com/questions/59879006/ |
Trying to learn how to implement a single Neuron | I have this code in Pytorch but cant get it to work. I have it working with Numpy as return (X.T * W).sum(axis=1) + B
But with Pytorch I keep getting this error...
def neural_network_neurons(W, B, X):
W = W.view(W.size(0), -1)
z1 = torch.matmul(X, W) + B
return ReLU(z1)
# ----------------------------... | You have the wrong orientation for W: you defined a 2x3 matrix, but your algorithm requires a 3x2. Try W.T instead?
| https://stackoverflow.com/questions/59905306/ |
In PyTorch's "MaxPool2D", is padding added depending on "ceil_mode"? | In MaxPool2D the padding is by default set to 0 and the ceil_mode is also set to False. Now, if I have an input of size 7x7 with kernel=2,stride=2 the output shape becomes 3x3, but when I use ceil_mode=True, it becomes 4x4, which makes sense because (if the following formula is correct), for 7x7 with output_shape would... | Ceil_mode=True changes the padding.
In the case of ceil mode, additional columns and rows are added at the right as well as at the down. (Not top and not left). It does not need to be one extra column. It depends on the stride value as well. I just wrote small code snippet where you can check how the populated valu... | https://stackoverflow.com/questions/59906456/ |
Image deconvolution with a CNN | I have an input tensor of shape (C,H,W), where H=W and C=W^2. This tensor contains non-linearly transformed information for an image of shape (1,H,W) squeezed to (H,W). The exact form of the transformation is not important (plus, there is no closed-form expression for it anyway). I would like to design a CNN to esti... | There's no problem with applying a ReLU layer near the beginning, as long as you apply a weighted linear layer first. If the net learns that it needs the values there, it can apply a negative weight to preserve the information (roughly speaking).
In fact, a useful thing to do in some networks is to normalize the input... | https://stackoverflow.com/questions/59913069/ |
where could I find training.pt / test.pt | In the Pytorch docs for MNIST I read:
root (string): Root directory of dataset where MNIST/processed/training.pt
and MNIST/processed/test.pt exist.
Where could I find these two files traing.pt, test.pt? And what are their format?
| Assuming pytorch 1.x+, The constructor of torchvision.datasets.MNIST follows this signature:
torchvision.datasets.MNIST(root, train=True, transform=None, target_transform=None, download=False)
The easiest way to get the dataset is to set download=True, that way it will automatically download and store training.pt ... | https://stackoverflow.com/questions/59915334/ |
Famous neural networks for regression | I have come across many neural network architecture for classification problems. AlexNet, ResNet, VGGNet, GoogLeNet etc... Is there similar networks for regression problems which can be used for transfer learning?
| Alright, all those architecture are not only for classification, the only shift you have to make for modifying a DL model from classification to regression is to change the top layer. For example in the VGGNET the last layer could be :
Dense(25, activation='softmax')
That means that we want to predict 25 outputs wit... | https://stackoverflow.com/questions/59928750/ |
Autograd function in Pytorch documentation |
In the Pytorch documentation https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html#sphx-glr-beginner-blitz-autograd-tutorial-py
In the image, I am unable to understand what y.backward(v) means and why do we need to define another tensor v to do the backward operation and also how we got the results of x... | y.backward() computes dy/dz where z are all the leaf nodes in the computation graph. And it stores dy/dz in z.grad.
For example: In the above case, leaf nodes are x.
y.backward() works when y is a scalar which is the case for most of the deep-learning. When y is a vector you have to pass another vector (v in the abov... | https://stackoverflow.com/questions/59935596/ |
while installing apex extension for pytorch(python environment) the following error is showing, am unable to solve this problem | I want to install apex extension for my pytorch environment, my system is windows 10 and am using python version 3.8.1 and pip version is 20.0.2
I read the instructions from this https://github.com/NVIDIA/apex and I executed the command
pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cud... |
pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext
The line specified in your link is
$ pip install -v --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./
Note that you're missing the final ./, which is why pip tells you that
You must give at least o... | https://stackoverflow.com/questions/59943865/ |
How can I convert Tensor into Bitmap on PyTorch Mobile? | I found that solution (https://itnext.io/converting-pytorch-float-tensor-to-android-rgba-bitmap-with-kotlin-ffd4602a16b6) but when I tried to convert that way I found that the size of inputTensor.dataAsFloatArray is more than bitmap.width*bitmap.height. How works converting tensor to float array or is there any other p... | None of the answers were able to produce the output I wanted, so this is what I came up with - it is basically only reverse engineered version of what happenes in TensorImageUtils.bitmapToFloat32Tensor().
Please note that this function only works if you are using MemoryFormat.CONTIGUOUS (which is default) in TensorImag... | https://stackoverflow.com/questions/59950520/ |
PyTorch-YOLOv3 Generating Training and Validation Curves | Hello again stackoverflow! I greatly appreciate this community and the helpful feedback.
I have some other questions that I hope someone can help me with. I am working with an implementation of PyTorch-YOLOv3 from https://github.com/eriklindernoren/PyTorch-YOLOv3
I have been able to train the model, but now I would... | The solution is mentioned in the issues. The exact link is: https://github.com/eriklindernoren/PyTorch-YOLOv3/issues/283
Replace in utils:269
ByteTensor = torch.cuda.ByteTensor if pred_boxes.is_cuda else torch.ByteTensor
With:
BoolTensor = torch.cuda.BoolTensor if pred_boxes.is_cuda else torch.BoolTensor
And it usa... | https://stackoverflow.com/questions/59961103/ |
Make GPU available again after numba.cuda.close()? | So when I run cuda.select_device(0) and then cuda.close(). Pytorch cannot access the GPU again, I know that there is way so that PyTorch can utilize the GPU again without having to restart the kernel. But I forgot how. Does anyone else know?
from numba import cuda as cu
import torch
# random tensor
a=torch.rand(100... | I had the same issue but with TensorFlow and Keras when iterating through a for loop to tune hyperparamenters. It did not free up the GPU memory used by older models. The cuda solution did not work for me. The following did:
import gc
gc.collect()
| https://stackoverflow.com/questions/59982296/ |
How to use Pytorch OneCycleLR in a training loop (and optimizer/scheduler interactions)? | I'm training an NN and using RMSprop as an optimizer and OneCycleLR as a scheduler. I've been running it like this (in slightly simplified code):
optimizer = torch.optim.RMSprop(model.parameters(), lr=0.00001,
alpha=0.99, eps=1e-08, weight_decay=0.0001, momentum=0.0001, centered=False)
... | Use optimizer.step() before scheduler.step(). Also, for OneCycleLR, you need to run scheduler.step() after every step - source (PyTorch docs). So, your training code is correct (as far as calling step() on optimizer and schedulers is concerned).
Also, in the example you mentioned, they have passed steps_per_epoch para... | https://stackoverflow.com/questions/59996859/ |
How exactly should the input file be formatted for the language model finetuning (BERT through Huggingface Transformers)? | I wanted to employ the examples/run_lm_finetuning.py from the Huggingface Transformers repository on a pretrained Bert model. However, from following the documentation it is not evident how a corpus file should be structured (apart from referencing the Wiki-2 dataset). I've tried
One document per line (multiple sente... | First of all, I strongly suggest to also open this as an issue in the huggingface library, as they have probably the strongest interest to answer this, and may take it as a sign that they should update/clarify their documentation.
But to answer your question, it seems that this specific sample script is basically retur... | https://stackoverflow.com/questions/60001698/ |
Error in Tensorboard's(PyTorch) add_graph | I'm following this Pytorch's Tensorboard documentation.
I have the following code:
model = torchvision.models.resnet50(False)
writer.add_graph(model)
It throws the following error:
_ = model(*args) # don't catch, just print the error message
TypeError: ResNet object argument after * must be an iterable, not NoneType... | I had this problem too..
Passing an input_to_model parameter different from None solved the problem. However, I though it should be optional
dataiter = iter(trainloader)
images, labels = dataiter.next()
writer.add_graph(model, images)
| https://stackoverflow.com/questions/60021266/ |
Computing Linear Layer in Tensor/Outer-Product space in PyTorch is Very Slow | I would like to make a PyTorch model that takes the outer product of the input with itself and then does a linear regression on that. As an example, consider the input vector [1,2,3], then I would like to compute w and b to optimize [1*1, 1*2, 1*3, 2*1, 2*2, 2*3, 3*1, 3*2, 3*3] @ w + b.
For a batch input with r rows a... | When you have to reshape a tensor during the training loop of a model it's always best to use view instead of reshape. There doesn't appear to be any performance overhead with a view, but it does require that the tensor data is contiguous.
If your tensors at the beginning aren't contiguous you can recopy the tensor an... | https://stackoverflow.com/questions/60025695/ |
pytorch train function Varibles and Tensors (read my introduction i dont know my problem as well it just dont work ) | I started learning pytorch and started with videos about MNIST handwriting and learnt it with an video but the video is 2 years old and some things have changen since then i guess because it dosent work as in the video and i seriously dont know anything so i dont know whats my error or what i do wrong i just type every... | I believe just setting num_workers to zero would solve your problem. One other thing that would solve your problem is to place your code in a main function.
The reasons for this can be found here:
https://docs.python.org/2/library/multiprocessing.html#multiprocessing-programming . The reason for this is that num_work... | https://stackoverflow.com/questions/60029369/ |
Why is PyTorch 2x slower than Keras for an identical model and hyperparameters? | I've experienced this with custom made modules as well, but for this example I'm specifically using one of the official PyTorch examples and the MNIST dataset.
I've ported the exact architecture in Keras and TF2 with eager mode like so:
model = keras.models.Sequential([ keras.layers.Conv2D(32, (3, 3) , input_shape=... | I think there is a subtle difference that must be taken into consideration; my best bet/hunch is the following: it is not the processing time in itself per GPU, but the max_queue_size=10 parameter, 10 by default in Keras.
Since by default in the normal for-loop in PyTorch the data is not queued, the queue which Keras ... | https://stackoverflow.com/questions/60029607/ |
Is there any way that can convert a data format of .pb file from NCHW into NHWC? | I have a CNN model which was trained in Pytorch based on the data format N(batch) x C(channel) x H(height) x W(width). I saved the pre-trained model as model.pth. Afterward, I converted the pre-trained model from model.pth -> model.onnx by using existing function:
torch.onnx.export(model, dummy_input, "model.onnx")
... | Short answer, you are in a tough spot.
Long answer, it's difficult yet possible. What makes your problem difficult is your graph is already trained. It is inefficient, yet easier to convert NCHW->NHWC while you create the training graph. See similar answer here and here.
Now to your answer, you'll have to overload c... | https://stackoverflow.com/questions/60048660/ |
Sequence labeling for sentences and not tokens | I have sentences that belong to a paragraph. Each sentence has a label.
[s1,s2,s3,…], [l1,l2,l3,…]
I understand that I have to encode each sentence using an encoder, and then use sequence labeling. Could you guide me on how I could do that, combining them?
| If i understand your question correctly, you are looking for encoding of your sentences into numeric representation.
let's say you have data like :
data = ["Sarah, is that you? Hahahahahaha Todd give you another black eye??"
"Well, being slick comes with the job of being a propagandist, Andi..."
"Sad... | https://stackoverflow.com/questions/60048900/ |
how to duplicate the input channel in a tensor? | I have a tensor with the shape torch.Size([39, 1, 20, 256, 256]) how do I duplicate the channel to make the shape torch.Size([39, 3, 20, 256, 256]).
| I am fairly certain that this is already a duplicate question, but I could not find a fitting answer myself, which is why I am going ahead and answer this by referring to both the PyTorch documentation and PyTorch forum
Essentially, torch.Tensor.expand() is the function that you are looking for, and can be used as fol... | https://stackoverflow.com/questions/60058698/ |
I cant install torch-sparse in Google Colab | I am trying to install torch-sparse in Google Colab using ! pip install torch-sparse, but i am getting the following erorr:
Collecting torch-sparse
Using cached https://files.pythonhosted.org/packages/0e/bf/6242893c898621e7e4756e1ad298e903df6dfae208aec1c32adf8cfd1f7f/torch_sparse-0.4.4.tar.gz
Requirement a... | You need to go into Runtime -> Change runtime type and choose a GPU as the Hardware accelerator. After this it should install fine.
Collecting torch-sparse
Downloading https://files.pythonhosted.org/packages/0e/bf/6242893c898621e7e4756e1ad298e903df6dfae208aec1c32adf8cfd1f7f/torch_sparse-0.4.4.tar.gz
Requirement alre... | https://stackoverflow.com/questions/60059680/ |
Get feature vectors from BertForSequenceClassification | I have successfully build a sentiment analysis tool with BertForSequenceClassification from huggingface/transformers to classify $tsla tweets as positive or negative.
However, I can't find out how I can obtain the feature vectors per tweet (more specifically the embedding of [CLS]) from my finetuned model.
more info... | I also have this problem after fine-tuning BertForSequenceClassification. I know your purpose is to get the hidden state of [CLS] as the representation of each tweet. Right? As the instruction of API document, I think the code is:
model = BertForSequenceClassification.from_pretrained(OUTPUT_DIR, output_hidden_states=T... | https://stackoverflow.com/questions/60064988/ |
What is the default batch size of pytorch SGD? | What does pytorch SGD do if I feed the whole data and do not specify the batch size? I don't see any "stochastic" or "randomness" in the case.
For example, in the following simple code, I feed the whole data (x,y) into a model.
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
for epoch in r... | The SGD optimizer in PyTorch is just gradient descent. The stocastic part comes from how you usually pass a random subset of your data through the network at a time (i.e. a mini-batch or batch). The code you posted passes the entire dataset through on each epoch before doing backprop and stepping the optimizer so you'r... | https://stackoverflow.com/questions/60068114/ |
Transformers PreTrainedTokenizer add_tokens Functionality | Referring to the documentation of the awesome Transformers library from Huggingface, I came across the add_tokens functions.
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertModel.from_pretrained('bert-base-uncased')
num_added_toks = tokenizer.add_tokens(['new_tok1', 'my_new-tok2'])
model.res... | If you add tokens to the tokenizer, you indeed make the tokenizer tokenize the text differently, but this is not the tokenization BERT was trained with, so you are basically adding noise to the input. The word embeddings are not trained and the rest of the network never saw them in context. You would need a lot of data... | https://stackoverflow.com/questions/60068129/ |
free up the memory allocation cuda pytorch? |
RuntimeError: CUDA out of memory. Tried to allocate 12.00 MiB (GPU 1;
11.91 GiB total capacity; 10.12 GiB already allocated; 21.75 MiB free; 56.79 MiB cached)
I encountered the preceding error during pytorch training.
I'm using pytorch on jupyter notebook. Is there a way to free up the gpu memory in jupyter not... | I had the same issue sometime back.
There are generally two way I go about.
Decrease the batch size
Sometimes, even when I had decrease the batch size to '1', this issue persists. Then I changed my approach as follows.
Decrease the image size ( or patch size, depending upon your implementation). Decreasing the image... | https://stackoverflow.com/questions/60068277/ |
How to run inference of a pytorch model on pyspark dataframe (create new column with prediction) using pandas_udf? | Is there a way to run the inference of pytorch model over a pyspark dataframe in vectorized way (using pandas_udf?).
One row udf is pretty slow since the model state_dict() needs to be loaded for each row. I'm trying to use pandas_udf to speed this up, since all the operations can be vectorized efficiently in pandas/p... | So apparently this issue is due to an incompatibility between spark 2.4.x and pyarrow >= 0.15. See here:
https://issues.apache.org/jira/browse/SPARK-29367
https://arrow.apache.org/blog/2019/10/06/0.15.0-release/
https://spark.apache.org/docs/3.0.0-preview/sql-pyspark-pandas-with-arrow.html#usage-notes
How I fixed i... | https://stackoverflow.com/questions/60074543/ |
addition of 2 pytorch tensors with diffrent size | I have 2 tensors with dimension, A = [64,155,300] and B =[64,155,100]
when I add this 2 tensors ie. C= A+B,
I get this error ==> " RuntimeError: The size of tensor a (300) must match the size of tensor b (100) at non-singleton dimension 2 "
could anyone please help how should I add above tensors? any help will be app... | As error says you can not add two tensor with mis-match shapes
but if you want you can repeat your third dim of B tensor so it can match with A
using torch.Tensor.repeat try A + B.repeat(1,1,3)
>>> A.shape
torch.Size([64, 155, 300])
>>> B.shape
torch.Size([64, 155, 100])
>>> B = B.repeat(1... | https://stackoverflow.com/questions/60088784/ |
Converting python list to pytorch tensor | I have a problem converting a python list of numbers to pytorch Tensor :
this is my code :
caption_feat = [int(x) if x < 11660 else 3 for x in caption_feat]
printing caption_feat gives : [1, 9903, 7876, 9971, 2770, 2435, 10441, 9370, 2]
I do the converting like this : tmp2 = torch.Tensor(caption_feat)
now p... | You can directly convert python list to a pytorch Tensor by defining the dtype. For example,
import torch
a_list = [3,23,53,32,53]
a_tensor = torch.Tensor(a_list)
print(a_tensor.int())
>>> tensor([3,23,53,32,53])
| https://stackoverflow.com/questions/60090093/ |
What is projection layer in the context of neural machine translation using RNN? | I read a paper about machine translation, and it uses projection layer.
The projection layer is explained as follows: "Additional projection aims to reduce the dimensionality of the encoder output representations to match the decoder stack dimension."
Does anyone know this architecture or how to implement this layer i... | It is a standard linear projection. You can just add nn.Linear(2 * model_dim, model_dim) where model_dim is RNN dimension.
The encoder is bidirectional, with one RNNs in both directions having an output of dimension model_dim. The decoder only works in the forward direction, so it has states of only model_dim dimensi... | https://stackoverflow.com/questions/60110462/ |
Pytorch: load dataset of grayscale images | I want to load a dataset of grayscale images. I used ImageFolder but this doesn't load gray images by default as it converts images to RGB.
I found solutions that load images with ImageFolder and after convert images in grayscale, using:
transforms.Grayscale(num_output_channels=1)
or
ImageOps.grayscale(image)
Is... | Assuming the dataset is stored in the "Dataset" folder as given below, set the root directory as "Dataset":
Dataset
class_1
img1.png
img2.png
class_2
img1.png
img2.png
from torchvision.datasets import ImageFolder
from torch.utils.data import DataLoader, random_split
from torchvision import transforms
root =... | https://stackoverflow.com/questions/60116208/ |
Concatenate with respect to 1st dimension | In the following code what does torch.cat really do. I know it concatenates the batch which is contained in the sample but why do we have to do that and what does concatenate really mean.
# memory is just a list of events
def sample(self, batch_size):
samples = zip(*random.sample(self.memory, batch_size))
re... | torch.cat concatenates as the name suggests along specified dimension.
Example from documentation will tell you everything you need to know:
x = torch.randn(2, 3) # shape (2, 3)
catted = torch.cat((x, x, x), dim=0) # shape (6, 3), e.g. 3 x stacked on each other
Remember concatenated tensors need to have the same di... | https://stackoverflow.com/questions/60117911/ |
How to speed up slicing in python, not using the for loop | I'm trying to speed up the following python code:
import torch
import numpy as np
A = torch.zeros(11, 16, 64)
B = torch.randn(11, 9, 64)
indices = np.random.randint(0,9,(11,16))
for i in range(len(A)):
A[i,:,:] = B[i,indices[i],:]
Is there a nice way not to use the for loop? This way, it is really slow, espec... | You can use multiple mult-dimensional indices but they need to be the same size or broadcastable. So for example
# create a (11, 1) range array that broadcasts with indices which is (11, 16)
indices0 = np.expand_dims(np.arange(indices.shape[0]), 1)
A = B[indices0, indices, :]
Since broadcasting can be confusing I'll... | https://stackoverflow.com/questions/60124854/ |
Load multiple .npy files (size > 10GB) in pytorch | Im looking for a optimized solution to load multiple huge .npy files using pytorch data loader.
I'm currently using the following method which creates a new dataloader for each file in each epoch.
My data loader is something like:
class GetData(torch.utils.data.Dataset):
def __init__(self, data_path, target_pa... | According to numpy.load, you can set the argument mmap_mode='r' to receive a memory-mapped array numpy.memmap.
A memory-mapped array is kept on disk. However, it can be accessed and sliced like any ndarray. Memory mapping is especially useful for accessing small fragments of large files without reading the entire f... | https://stackoverflow.com/questions/60127632/ |
How to concurrently run multiple branches in pytorch? | I was trying to build a network with multiple branches in pytorch. But how can I run multiple branches in parallel instead of run them one by one?
Not like tensorflow or keras, pytorch use dynamic graph, so I can't define concurrent processing beforehand.
I looked up for some similar official implement of pytorch ne... | In general you don't have to care about performance of network execution as long as you use functions provided by pytorch.
As pointed out in the comments, all calls to the gpu are asynchron. And as long as a call is not dependent on data it is executed. So in your case you have multiple branches. Pytorch will schedule... | https://stackoverflow.com/questions/60133474/ |
TypeError: forward() missing 1 required positional argument: 'negative' | I want to utilize deep neural network to classify Hyperspectral Image. But every time I run this code, it gives me this error "TypeError: forward() missing 1 required positional argument: 'negative'".
Code show as below(Not completed):
import numpy as np
import scipy.io as sio
from tqdm import tqdm
import torch
import... | You are using nn.TripletMarginLoss() as your loss function.
This specific loss function expects three inputs for computing the loss: anchor, positive and negative.
Your code passes only two arguments.
| https://stackoverflow.com/questions/60134907/ |
Visualize the output of Vgg16 model by TSNE plot? | I need to visualize the output of Vgg16 model which classify 14 different classes.
I load the trained model and I did replace the classifier layer with the identity() layer but it doesn't categorize the output.
Here is the snippet:
the number of samples here is 1000 images.
epoch = 800
PATH = 'vgg16_epoch{}.pth'.fo... | The VGG16 outputs over 25k features to the classifier. I believe it's too much to t-SNE. It's a good idea to include a new nn.Linear layer to reduce this number. So, t-SNE may work better. In addition, I'd recommend you two different ways to get the features from the model:
The best way to get it regardless of the mod... | https://stackoverflow.com/questions/60138486/ |
how to check whether a certain number is in the Pytorch tensor? | for a Pytorch tensor A:
A = tensor([1,0,0],
[0,0,0])
is there way I can check whether the number 1 is an element of the tensor A?
like is there a pytorch function that returns True is 1 is an element of A, and returns False if 1 is not an element of A?
Thank you,
| torch.Tensor implements __contains__. So, you can just use:
1 in A
This returns True if the element 1 is in A, and False otherwise.
| https://stackoverflow.com/questions/60153144/ |
How much is the dimension of some bidirectional LSTM layers? | I read a paper about machine translation, and it uses projection layer. Its encoder has 6 bidirectional LSTM layers. If input embedding dimension is 512, how much will be the dimension of the encoder output? 512*2**5?
The paper's link: https://www.aclweb.org/anthology/P18-1008.pdf
| Not quite. Unfortunately, Figure 1 in the mentioned paper is a bit misleading. It is not that the six encoding layers are in parallel, as it might be understood from the figure, but rather that these layers are successive, meaning that the hidden state/output from the previous layer is used in the subsequent layer as a... | https://stackoverflow.com/questions/60164056/ |
How to debug if weight keep increasing. Pytorch program | I m having some doubt when practicing Pytorch program.
I have function like y = m1x1 + m2x2 + c (just 2 weights to learn here). The expected values of weight should be 16,-14 and bias should be 36. But in every epoch the learned wight goes very big. Can any one help me to debug and understand this 20 lines of code, wh... | You have a very large learning rate.
This is an illustration from Jeremy Jordan's blog that explains exactly what is going on in your case.
| https://stackoverflow.com/questions/60164779/ |
AttributeError: 'NoneType' object has no attribute 'zero_' | The Grad sub object becomes "None" if expand the expression. Not sure why? Can somebody give some clue.
If expand the w.grand.zero_() throw error as "AttributeError: 'NoneType' object has no attribute 'zero_'"
Thanks,
Ganesh
import torch
x = torch.randint(size = (1,2), high = 10)
w = torch.Tensor([16,-14])
b = 36
... | The thing is that in your working code you are modifying existing variable which has grad attribute, while in the non-working case you are creating a new variable.
As new w1/b1 variable is created it has no gradient attribute as you didn't call backward() on it, but on the "original" variable.
First, let's check whet... | https://stackoverflow.com/questions/60166866/ |
Albumentations RandomCrop with mask different size as image | is it possible to RandomCrop an image with the size 256x256 and the mask with the size 100x100?
Or RandomGridShuffle and RandomSizedCrop?
https://albumentations.readthedocs.io/en/latest/api/augmentations.html
Thank you
| This functionality is not supported.
The application of RandomCrop or RandomGridShuffle can lead to very strange corner cases.
It is just easier to resize the mask and image to the same size and resize it back when needed.
Two extra lines of code, but you will not get unexpected bugs.
| https://stackoverflow.com/questions/60187803/ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.