content stringlengths 189 4.87k |
|---|
INSTRUCTION:
Problem:
I have a csv file without headers which I'm importing into python using pandas. The last column is the target class, while the rest of the columns are pixel values for images. How can I go ahead and split this dataset into a training set and a testing set (80/20)?
Also, once that is done how wou... |
INSTRUCTION:
Problem:
I'm trying to find a way to iterate code for a linear regression over many many columns, upwards of Z3. Here is a snippet of the dataframe called df1
Time A1 A2 A3 B1 B2 B3
1 1.00 6.64 6.82 6.79 6.70 6.95 7.02
2 2.00 6.70 6.86 6.92 ... |
INSTRUCTION:
Problem:
I performed feature selection using ExtraTreesClassifier and SelectFromModel in data set that loaded as DataFrame, however i want to save these selected feature while maintaining columns name as well. So is there away to get selected columns names from SelectFromModel method? note that output is ... |
INSTRUCTION:
Problem:
Given a list of variant length features:
features = [
['f1', 'f2', 'f3'],
['f2', 'f4', 'f5', 'f6'],
['f1', 'f2']
]
where each sample has variant number of features and the feature dtype is str and already one hot.
In order to use feature selection utilities of sklearn, I have to con... |
INSTRUCTION:
Problem:
I have fitted a k-means algorithm on 5000+ samples using the python scikit-learn library. I want to have the 50 samples closest (data, not just index) to a cluster center "p" (e.g. p=2) as an output, here "p" means the p^th center. How do I perform this task?
A:
<code>
import numpy as np
import... |
INSTRUCTION:
Problem:
Right now, I have my data in a 2 by 2 numpy array. If I was to use MinMaxScaler fit_transform on the array, it will normalize it column by column, whereas I wish to normalize the entire np array all together. Is there anyway to do that?
A:
<code>
import numpy as np
import pandas as pd
from skle... |
INSTRUCTION:
Problem:
My goal is to input 3 queries and find out which query is most similar to a set of 5 documents.
So far I have calculated the tf-idf of the documents doing the following:
from sklearn.feature_extraction.text import TfidfVectorizer
def get_term_frequency_inverse_data_frequency(documents):
ve... |
INSTRUCTION:
Problem:
Is there any way for me to preserve punctuation marks of !, ?, " and ' from my text documents using text CountVectorizer parameters in scikit-learn?
Assume that I have 'text' of str type now, how can I reach this target?
A:
<code>
import numpy as np
import pandas as pd
from sklearn.feature_ext... |
INSTRUCTION:
Problem:
Say that I want to train BaggingClassifier that uses DecisionTreeClassifier:
dt = DecisionTreeClassifier(max_depth = 1)
bc = BaggingClassifier(dt, n_estimators = 20, max_samples = 0.5, max_features = 0.5)
bc = bc.fit(X_train, y_train)
I would like to use GridSearchCV to find the best parameters ... |
INSTRUCTION:
Problem:
I would like to apply minmax scaler to column X2 and X3 in dataframe df and add columns X2_scale and X3_scale for each month.
df = pd.DataFrame({
'Month': [1,1,1,1,1,1,2,2,2,2,2,2,2],
'X1': [12,10,100,55,65,60,35,25,10,15,30,40,50],
'X2': [10,15,24,32,8,6,10,23,24,56,45,10,56],
'... |
INSTRUCTION:
Problem:
Given a list of variant length features, for example:
f = [
['t1'],
['t2', 't5', 't7'],
['t1', 't2', 't3', 't4', 't5'],
['t4', 't5', 't6']
]
where each sample has variant number of features and the feature dtype is str and already one hot.
In order to use feature selection utili... |
INSTRUCTION:
Problem:
Given a distance matrix, with similarity between various professors :
prof1 prof2 prof3
prof1 0 0.8 0.9
prof2 0.8 0 0.2
prof3 0.9 0.2 0
I need to perform hierarchical clustering on this data, where the above da... |
INSTRUCTION:
Problem:
Right now, I have my data in a 2 by 2 numpy array. If I was to use MinMaxScaler fit_transform on the array, it will normalize it column by column, whereas I wish to normalize the entire np array all together. Is there anyway to do that?
A:
<code>
import numpy as np
import pandas as pd
from skle... |
INSTRUCTION:
Problem:
I'm using the excellent read_csv()function from pandas, which gives:
In [31]: data = pandas.read_csv("lala.csv", delimiter=",")
In [32]: data
Out[32]:
<class 'pandas.core.frame.DataFrame'>
Int64Index: 12083 entries, 0 to 12082
Columns: 569 entries, REGIONC to SCALEKER
dtypes: float64(51), int64... |
INSTRUCTION:
Problem:
Given the following example:
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import NMF
from sklearn.pipeline import Pipeline
import pandas as pd
pipe = Pipeline([
("tf_idf", TfidfVectorizer()),
("nmf", NMF())
])
data = pd.DataFrame([["Salut comme... |
INSTRUCTION:
Problem:
Are you able to train a DecisionTreeClassifier with string data?
When I try to use String data I get a ValueError: could not converter string to float
X = [['dsa', '2'], ['sato', '3']]
clf = DecisionTreeClassifier()
clf.fit(X, ['4', '5'])
So how can I use this String data to train my model?
... |
INSTRUCTION:
Problem:
Can you give me any suggestion that transforms a sklearn Bunch object (from sklearn.datasets) to a dataframe? I'd like to do it to iris dataset.
Thanks!
from sklearn.datasets import load_iris
import pandas as pd
data = load_iris()
print(type(data))
data1 = pd. # May be you can give me a Pandas m... |
INSTRUCTION:
Problem:
How can I perform regression in sklearn, using SVM and a gaussian kernel?
Note to use default arguments. Thanks.
A:
<code>
import numpy as np
import pandas as pd
import sklearn
X, y = load_data()
assert type(X) == np.ndarray
assert type(y) == np.ndarray
# fit, then predict X
</code>
BEGIN SOLUT... |
INSTRUCTION:
Problem:
I'm trying to find the best hyper-parameters using sklearn function GridSearchCV on XGBoost.
However, I'd like it to do early stop when doing gridsearch, since this could reduce a lot of search time and might gain a better result on my tasks.
Actually, I am using XGBoost via its sklearn API.
... |
INSTRUCTION:
Problem:
How do I convert data from a Scikit-learn Bunch object (from sklearn.datasets) to a Pandas DataFrame?
from sklearn.datasets import load_boston
import pandas as pd
data = load_boston()
print(type(data))
data1 = pd. # Is there a Pandas method to accomplish this?
A:
<code>
import numpy as np
from... |
INSTRUCTION:
Problem:
I want to get the probability of the Logistic Regression model, while use cross-validation.
But now I'm only able to get the scores of the model, can u help me to get the probabilities?
please save the probabilities into a list or an array. thanks.
A:
<code>
import numpy as np
import pandas as ... |
INSTRUCTION:
Problem:
Are you able to train a DecisionTreeClassifier with string data?
When I try to use String data I get a ValueError: could not converter string to float
X = [['asdf', '1'], ['asdf', '0']]
clf = DecisionTreeClassifier()
clf.fit(X, ['2', '3'])
So how can I use this String data to train my model?... |
INSTRUCTION:
Problem:
I am trying to vectorize some data using
sklearn.feature_extraction.text.CountVectorizer.
This is the data that I am trying to vectorize:
corpus = [
'We are looking for Java developer',
'Frontend developer with knowledge in SQL and Jscript',
'And this is the third one.',
'Is this the first ... |
INSTRUCTION:
Problem:
I want to perform a Linear regression fit and prediction, but it doesn't work.
I guess my data shape is not proper, but I don't know how to fix it.
The error message is Found input variables with inconsistent numbers of samples: [1, 9] , which seems to mean that the Y has 9 values and the X only ... |
INSTRUCTION:
Problem:
Is there any package in Python that does data transformation like Yeo-Johnson transformation to eliminate skewness of data?
I know about sklearn, but I was unable to find functions to do Yeo-Johnson transformation.
How can I use sklearn to solve this?
A:
<code>
import numpy as np
import pandas ... |
INSTRUCTION:
Problem:
I am trying to vectorize some data using
sklearn.feature_extraction.text.CountVectorizer.
This is the data that I am trying to vectorize:
corpus = [
'We are looking for Java developer',
'Frontend developer with knowledge in SQL and Jscript',
'And this is the third one.',
'Is this the first ... |
INSTRUCTION:
Problem:
This question and answer demonstrate that when feature selection is performed using one of scikit-learn's dedicated feature selection routines, then the names of the selected features can be retrieved as follows:
np.asarray(vectorizer.get_feature_names())[featureSelector.get_support()]
For examp... |
INSTRUCTION:
Problem:
I am using python and scikit-learn to find cosine similarity between item descriptions.
A have a df, for example:
items description
1fgg abcd ty
2hhj abc r
3jkl r df
I did following procedures:
1) tokenizing each description
2) transform the corpus into vector space using tf-i... |
INSTRUCTION:
Problem:
i am trying to do hyperparemeter search with using scikit-learn's GridSearchCV on XGBoost. During gridsearch i'd like it to early stop, since it reduce search time drastically and (expecting to) have better results on my prediction/regression task. I am using XGBoost via its Scikit-Learn API.
... |
INSTRUCTION:
Problem:
Given a list of variant length features:
features = [
['f1', 'f2', 'f3'],
['f2', 'f4', 'f5', 'f6'],
['f1', 'f2']
]
where each sample has variant number of features and the feature dtype is str and already one hot.
In order to use feature selection utilities of sklearn, I have to con... |
INSTRUCTION:
Problem:
Is there any package in Python that does data transformation like Box-Cox transformation to eliminate skewness of data? In R this could be done using caret package:
set.seed(1)
predictors = data.frame(x1 = rnorm(1000,
mean = 5,
... |
INSTRUCTION:
Problem:
I have a data which include dates in sorted order.
I would like to split the given data to train and test set. However, I must to split the data in a way that the test have to be newer than the train set.
Please look at the given example:
Let's assume that we have data by dates:
1, 2, 3, ...,... |
INSTRUCTION:
Problem:
Is it possible to delete or insert a step in a sklearn.pipeline.Pipeline object?
I am trying to do a grid search with or without one step in the Pipeline object. And wondering whether I can insert or delete a step in the pipeline. I saw in the Pipeline source code, there is a self.steps object h... |
INSTRUCTION:
Problem:
I'd like to use LabelEncoder to transform a dataframe column 'Sex', originally labeled as 'male' into '1' and 'female' into '0'.
I tried this below:
df = pd.read_csv('data.csv')
df['Sex'] = LabelEncoder.fit_transform(df['Sex'])
However, I got an error:
TypeError: fit_transform() missing 1 requi... |
INSTRUCTION:
Problem:
Does scikit-learn provide facility to use SVM for regression, using a gaussian kernel? I looked at the APIs and I don't see any. Has anyone built a package on top of scikit-learn that does this?
Note to use default arguments
A:
<code>
import numpy as np
import pandas as pd
import sklearn
X, y =... |
INSTRUCTION:
Problem:
I have been trying this for the last few days and not luck. What I want to do is do a simple Linear regression fit and predict using sklearn, but I cannot get the data to work with the model. I know I am not reshaping my data right I just dont know how to do that.
Any help on this will be appreci... |
INSTRUCTION:
Problem:
I want to load a pre-trained word2vec embedding with gensim into a PyTorch embedding layer.
How do I get the embedding weights loaded by gensim into the PyTorch embedding layer?
here is my current code
And I need to embed my input data use this weights. Thanks
A:
runnable code
<code>
import nu... |
INSTRUCTION:
Problem:
I have a trained PyTorch model and I want to get the confidence score of predictions in range (0-1). The code below is giving me a score but its range is undefined. I want the score in a defined range of (0-1) using softmax. Any idea how to get this?
conf, classes = torch.max(output.reshape(1, 3... |
INSTRUCTION:
Problem:
I'm trying to slice a PyTorch tensor using a logical index on the columns. I want the columns that correspond to a 0 value in the index vector. Both slicing and logical indexing are possible, but are they possible together? If so, how? My attempt keeps throwing the unhelpful error
TypeError: ind... |
INSTRUCTION:
Problem:
In pytorch, given the tensors a of shape (1X11) and b of shape (1X11), torch.stack((a,b),0) would give me a tensor of shape (2X11)
However, when a is of shape (2X11) and b is of shape (1X11), torch.stack((a,b),0) will raise an error cf. "the two tensor size must exactly be the same".
Because th... |
INSTRUCTION:
Problem:
I have a tensor t, for example
1 2
3 4
And I would like to make it
0 0 0 0
0 1 2 0
0 3 4 0
0 0 0 0
I tried stacking with new=torch.tensor([0. 0. 0. 0.]) tensor four times but that did not work.
t = torch.arange(4).reshape(1,2,2).float()
print(t)
new=torch.tensor([[0., 0., 0.,0.]])
print(new)
r... |
INSTRUCTION:
Problem:
I am doing an image segmentation task. There are 7 classes in total so the final outout is a tensor like [batch, 7, height, width] which is a softmax output. Now intuitively I wanted to use CrossEntropy loss but the pytorch implementation doesn't work on channel wise one-hot encoded vector
So I ... |
INSTRUCTION:
Problem:
Is it possible in PyTorch to change the learning rate of the optimizer in the middle of training dynamically (I don't want to define a learning rate schedule beforehand)?
So let's say I have an optimizer:
optim = torch.optim.SGD(..., lr=0.01)
Now due to some tests which I perform during trainin... |
INSTRUCTION:
Problem:
Let's say I have a 5D tensor which has this shape for example : (1, 3, 10, 40, 1). I want to split it into smaller equal tensors (if possible) according to a certain dimension with a step equal to 1 while preserving the other dimensions.
Let's say for example I want to split it according to the ... |
INSTRUCTION:
Problem:
Let's say I have a 5D tensor which has this shape for example : (1, 3, 40, 10, 1). I want to split it into smaller equal tensors (if possible) according to a certain dimension with a step equal to 1 while preserving the other dimensions.
Let's say for example I want to split it according to the ... |
INSTRUCTION:
Problem:
I have two tensors of dimension 11 * 1. I want to check how many of the 11 elements are equal in the two tensors. I think I should be able to do this in few lines like Numpy but couldn't find a similar function.
A:
<code>
import numpy as np
import pandas as pd
import torch
A, B = load_data()
<... |
INSTRUCTION:
Problem:
I'm trying to convert a torch tensor to pandas DataFrame.
However, the numbers in the data is still tensors, what I actually want is numerical values.
This is my code
import torch
import pandas as pd
x = torch.rand(4,4)
px = pd.DataFrame(x)
And px looks like
0 1 2 3
tensor(0.3880) tensor... |
INSTRUCTION:
Problem:
I have a logistic regression model using Pytorch, where my input is high-dimensional and my output must be a scalar - 0, 1 or 2.
I'm using a linear layer combined with a softmax layer to return a n x 3 tensor, where each column represents the probability of the input falling in one of the three ... |
INSTRUCTION:
Problem:
Given a 3d tenzor, say: batch x sentence length x embedding dim
a = torch.rand((10, 1000, 23))
and an array(or tensor) of actual lengths for each sentence
lengths = torch .randint(1000,(10,))
outputs tensor([ 137., 152., 165., 159., 145., 264., 265., 276.,1000., 203.])
How to fill tensor ‘a’ ... |
INSTRUCTION:
Problem:
I have the following torch tensor:
tensor([[-0.2, 0.3],
[-0.5, 0.1],
[-0.4, 0.2]])
and the following numpy array: (I can convert it to something else if necessary)
[1 0 1]
I want to get the following tensor:
tensor([0.3, -0.5, 0.2])
i.e. I want the numpy array to index each sub-elem... |
INSTRUCTION:
Problem:
How to batch convert sentence lengths to masks in PyTorch?
For example, from
lens = [3, 5, 4]
we want to get
mask = [[1, 1, 1, 0, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 0]]
Both of which are torch.LongTensors.
A:
<code>
import numpy as np
import pandas as pd
import torch
lens = lo... |
INSTRUCTION:
Problem:
I have a logistic regression model using Pytorch, where my input is high-dimensional and my output must be a scalar - 0, 1 or 2.
I'm using a linear layer combined with a softmax layer to return a n x 3 tensor, where each column represents the probability of the input falling in one of the three ... |
INSTRUCTION:
Problem:
How to convert a list of tensors to a tensor of tensors?
I have tried torch.tensor() but it gave me this error message
ValueError: only one element tensors can be converted to Python scalars
my current code is here:
import torch
list = [ torch.randn(3), torch.randn(3), torch.randn(3)]
new_tenso... |
INSTRUCTION:
Problem:
I have two tensors of dimension 1000 * 1. I want to check how many of the 1000 elements are equal in the two tensors. I think I should be able to do this in few lines like Numpy but couldn't find a similar function.
A:
<code>
import numpy as np
import pandas as pd
import torch
A, B = load_data... |
INSTRUCTION:
Problem:
Given a 3d tenzor, say: batch x sentence length x embedding dim
a = torch.rand((10, 1000, 23))
and an array(or tensor) of actual lengths for each sentence
lengths = torch .randint(1000,(10,))
outputs tensor([ 137., 152., 165., 159., 145., 264., 265., 276.,1000., 203.])
How to fill tensor ‘a’ ... |
INSTRUCTION:
Problem:
I'm trying to slice a PyTorch tensor using a logical index on the columns. I want the columns that correspond to a 1 value in the index vector. Both slicing and logical indexing are possible, but are they possible together? If so, how? My attempt keeps throwing the unhelpful error
TypeError: ind... |
INSTRUCTION:
Problem:
I have two tensors that should together overlap each other to form a larger tensor. To illustrate:
a = torch.Tensor([[1, 2, 3], [1, 2, 3]])
b = torch.Tensor([[5, 6, 7], [5, 6, 7]])
a = [[1 2 3] b = [[5 6 7]
[1 2 3]] [5 6 7]]
I want to combine the two tensors and have them partial... |
INSTRUCTION:
Problem:
I have the tensors:
ids: shape (30,1) containing indices like [[2],[1],[0],...]
x: shape(30,3,114)
ids tensor encodes the index of bold marked dimension of x which should be selected. I want to gather the selected slices in a resulting vector:
result: shape (30,114)
Background:
I have some ... |
INSTRUCTION:
Problem:
I have written a custom model where I have defined a custom optimizer. I would like to update the learning rate of the optimizer when loss on training set increases.
I have also found this: https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate where I can write a scheduler, howe... |
INSTRUCTION:
Problem:
How to convert a numpy array of dtype=object to torch Tensor?
x = np.array([
np.array([1.23, 4.56, 9.78, 1.23, 4.56, 9.78], dtype=np.double),
np.array([4.0, 4.56, 9.78, 1.23, 4.56, 77.77], dtype=np.double),
np.array([1.23, 4.56, 9.78, 1.23, 4.56, 9.78], dtype=np.double),
np.array... |
INSTRUCTION:
Problem:
I have this code:
import torch
list_of_tensors = [ torch.randn(3), torch.randn(3), torch.randn(3)]
tensor_of_tensors = torch.tensor(list_of_tensors)
I am getting the error:
ValueError: only one element tensors can be converted to Python scalars
How can I convert the list of tensors to a tenso... |
INSTRUCTION:
Problem:
I'd like to convert a torch tensor to pandas dataframe but by using pd.DataFrame I'm getting a dataframe filled with tensors instead of numeric values.
import torch
import pandas as pd
x = torch.rand(6,6)
px = pd.DataFrame(x)
Here's what I get when clicking on px in the variable explorer:
... |
INSTRUCTION:
Problem:
I have a logistic regression model using Pytorch, where my input is high-dimensional and my output must be a scalar - 0, 1 or 2.
I'm using a linear layer combined with a softmax layer to return a n x 3 tensor, where each column represents the probability of the input falling in one of the three ... |
INSTRUCTION:
Problem:
I'd like to convert a torch tensor to pandas dataframe but by using pd.DataFrame I'm getting a dataframe filled with tensors instead of numeric values.
import torch
import pandas as pd
x = torch.rand(4,4)
px = pd.DataFrame(x)
Here's what I get when clicking on px in the variable explorer:
0 ... |
INSTRUCTION:
Problem:
This question may not be clear, so please ask for clarification in the comments and I will expand.
I have the following tensors of the following shape:
mask.size() == torch.Size([1, 400])
clean_input_spectrogram.size() == torch.Size([1, 400, 161])
output.size() == torch.Size([1, 400, 161])
mask... |
INSTRUCTION:
Problem:
I have a tensor t, for example
1 2
3 4
5 6
7 8
And I would like to make it
-1 -1 -1 -1
-1 1 2 -1
-1 3 4 -1
-1 5 6 -1
-1 7 8 -1
-1 -1 -1 -1
I tried stacking with new=torch.tensor([-1, -1, -1, -1,]) tensor four times but that did not work.
t = torch.arange(8).reshape(1,4,2).float()
print(t)
new=... |
INSTRUCTION:
Problem:
I'm trying to slice a PyTorch tensor using an index on the columns. The index, contains a list of columns that I want to select in order. You can see the example later.
I know that there is a function index_select. Now if I have the index, which is a LongTensor, how can I apply index_select to ge... |
INSTRUCTION:
Problem:
In pytorch, given the tensors a of shape (1X11) and b of shape (1X11), torch.stack((a,b),0) would give me a tensor of shape (2X11)
However, when a is of shape (2X11) and b is of shape (1X11), torch.stack((a,b),0) will raise an error cf. "the two tensor size must exactly be the same".
Because th... |
INSTRUCTION:
Problem:
In pytorch, given the tensors a of shape (114X514) and b of shape (114X514), torch.stack((a,b),0) would give me a tensor of shape (228X514)
However, when a is of shape (114X514) and b is of shape (24X514), torch.stack((a,b),0) will raise an error cf. "the two tensor size must exactly be the same... |
INSTRUCTION:
Problem:
Consider I have 2D Tensor, index_in_batch * diag_ele. How can I get a 3D Tensor index_in_batch * Matrix (who is a diagonal matrix, construct by drag_ele)?
The torch.diag() construct diagonal matrix only when input is 1D, and return diagonal element when input is 2D.
A:
<code>
import numpy as ... |
INSTRUCTION:
Problem:
I have batch data and want to dot() to the data. W is trainable parameters. How to dot between batch data and weights?
Here is my code below, how to fix it?
hid_dim = 32
data = torch.randn(10, 2, 3, hid_dim)
data = data.view(10, 2*3, hid_dim)
W = torch.randn(hid_dim) # assume trainable parameter... |
INSTRUCTION:
Problem:
I'm trying to slice a PyTorch tensor using a logical index on the columns. I want the columns that correspond to a 1 value in the index vector. Both slicing and logical indexing are possible, but are they possible together? If so, how? My attempt keeps throwing the unhelpful error
TypeError: ind... |
INSTRUCTION:
Problem:
I have this code:
import torch
list_of_tensors = [ torch.randn(3), torch.randn(3), torch.randn(3)]
tensor_of_tensors = torch.tensor(list_of_tensors)
I am getting the error:
ValueError: only one element tensors can be converted to Python scalars
How can I convert the list of tensors to a tenso... |
INSTRUCTION:
Problem:
I have a tensor t, for example
1 2
3 4
5 6
7 8
And I would like to make it
0 0 0 0
0 1 2 0
0 3 4 0
0 5 6 0
0 7 8 0
0 0 0 0
I tried stacking with new=torch.tensor([0. 0. 0. 0.]) tensor four times but that did not work.
t = torch.arange(8).reshape(1,4,2).float()
print(t)
new=torch.tensor([[0., 0... |
INSTRUCTION:
Problem:
I have two tensors of dimension like 1000 * 1. I want to check how many of the elements are not equal in the two tensors. I think I should be able to do this in few lines like Numpy but couldn't find a similar function.
A:
<code>
import numpy as np
import pandas as pd
import torch
A, B = load_... |
INSTRUCTION:
Problem:
I have the following torch tensor:
tensor([[-22.2, 33.3],
[-55.5, 11.1],
[-44.4, 22.2]])
and the following numpy array: (I can convert it to something else if necessary)
[1 1 0]
I want to get the following tensor:
tensor([33.3, 11.1, -44.4])
i.e. I want the numpy array to index each... |
INSTRUCTION:
Problem:
Given a 3d tenzor, say: batch x sentence length x embedding dim
a = torch.rand((10, 1000, 96))
and an array(or tensor) of actual lengths for each sentence
lengths = torch .randint(1000,(10,))
outputs tensor([ 370., 502., 652., 859., 545., 964., 566., 576.,1000., 803.])
How to fill tensor ‘a’ ... |
INSTRUCTION:
Problem:
I have a logistic regression model using Pytorch, where my input is high-dimensional and my output must be a scalar - 0, 1 or 2.
I'm using a linear layer combined with a softmax layer to return a n x 3 tensor, where each column represents the probability of the input falling in one of the three ... |
INSTRUCTION:
Problem:
I have two tensors of dimension (2*x, 1). I want to check how many of the last x elements are not equal in the two tensors. I think I should be able to do this in few lines like Numpy but couldn't find a similar function.
A:
<code>
import numpy as np
import pandas as pd
import torch
A, B = loa... |
INSTRUCTION:
Problem:
I have written a custom model where I have defined a custom optimizer. I would like to update the learning rate of the optimizer when loss on training set increases.
I have also found this: https://pytorch.org/docs/stable/optim.html#how-to-adjust-learning-rate where I can write a scheduler, howe... |
INSTRUCTION:
Problem:
How to batch convert sentence lengths to masks in PyTorch?
For example, from
lens = [3, 5, 4]
we want to get
mask = [[0, 0, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 1, 1, 1, 1]]
Both of which are torch.LongTensors.
A:
<code>
import numpy as np
import pandas as pd
import torch
lens = lo... |
INSTRUCTION:
Problem:
Is it possible in PyTorch to change the learning rate of the optimizer in the middle of training dynamically (I don't want to define a learning rate schedule beforehand)?
So let's say I have an optimizer:
optim = torch.optim.SGD(..., lr=0.005)
Now due to some tests which I perform during traini... |
INSTRUCTION:
Problem:
I have two tensors that should together overlap each other to form a larger tensor. To illustrate:
a = torch.Tensor([[1, 2, 3], [1, 2, 3]])
b = torch.Tensor([[5, 6, 7], [5, 6, 7]])
a = [[1 2 3] b = [[5 6 7]
[1 2 3]] [5 6 7]]
I want to combine the two tensors and have them partial... |
INSTRUCTION:
Problem:
I have the tensors:
ids: shape (70,1) containing indices like [[1],[0],[2],...]
x: shape(70,3,2)
ids tensor encodes the index of bold marked dimension of x which should be selected. I want to gather the selected slices in a resulting vector:
result: shape (70,2)
Background:
I have some scor... |
INSTRUCTION:
Problem:
I have this code:
import torch
list_of_tensors = [ torch.randn(3), torch.randn(3), torch.randn(3)]
tensor_of_tensors = torch.tensor(list_of_tensors)
I am getting the error:
ValueError: only one element tensors can be converted to Python scalars
How can I convert the list of tensors to a tenso... |
INSTRUCTION:
Problem:
I have two tensors of dimension (2*x, 1). I want to check how many of the last x elements are equal in the two tensors. I think I should be able to do this in few lines like Numpy but couldn't find a similar function.
A:
<code>
import numpy as np
import pandas as pd
import torch
A, B = load_da... |
INSTRUCTION:
Problem:
Consider I have 2D Tensor, index_in_batch * diag_ele. How can I get a 3D Tensor index_in_batch * Matrix (who is a diagonal matrix, construct by drag_ele)?
The torch.diag() construct diagonal matrix only when input is 1D, and return diagonal element when input is 2D.
A:
<code>
import numpy as ... |
INSTRUCTION:
Problem:
I may be missing something obvious, but I can't find a way to compute this.
Given two tensors, I want to keep elements with the maximum absolute values, in each one of them as well as the sign.
I thought about
sign_x = torch.sign(x)
sign_y = torch.sign(y)
max = torch.max(torch.abs(x), torch.ab... |
INSTRUCTION:
Problem:
I want to use a logical index to slice a torch tensor. Which means, I want to select the columns that get a '1' in the logical index.
I tried but got some errors:
TypeError: indexing a tensor with an object of type ByteTensor. The only supported types are integers, slices, numpy scalars and torch... |
INSTRUCTION:
Problem:
How to batch convert sentence lengths to masks in PyTorch?
For example, from
lens = [3, 5, 4]
we want to get
mask = [[1, 1, 1, 0, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 0]]
Both of which are torch.LongTensors.
A:
<code>
import numpy as np
import pandas as pd
import torch
lens = lo... |
INSTRUCTION:
Problem:
How to convert a numpy array of dtype=object to torch Tensor?
array([
array([0.5, 1.0, 2.0], dtype=float16),
array([4.0, 6.0, 8.0], dtype=float16)
], dtype=object)
A:
<code>
import pandas as pd
import torch
import numpy as np
x_array = load_data()
def Convert(a):
</code>
BEGIN SOLUTION
... |
INSTRUCTION:
Problem:
This question may not be clear, so please ask for clarification in the comments and I will expand.
I have the following tensors of the following shape:
mask.size() == torch.Size([1, 400])
clean_input_spectrogram.size() == torch.Size([1, 400, 161])
output.size() == torch.Size([1, 400, 161])
mask... |
INSTRUCTION:
Problem:
I have the following torch tensor:
tensor([[-0.2, 0.3],
[-0.5, 0.1],
[-0.4, 0.2]])
and the following numpy array: (I can convert it to something else if necessary)
[1 0 1]
I want to get the following tensor:
tensor([-0.2, 0.1, -0.4])
i.e. I want the numpy array to index each sub-ele... |
INSTRUCTION:
Problem:
How to batch convert sentence lengths to masks in PyTorch?
For example, from
lens = [1, 9, 3, 5]
we want to get
mask = [[1, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 0, 0, 0, 0]]
Both of which are torch.LongTensors... |
INSTRUCTION:
Problem:
I may be missing something obvious, but I can't find a way to compute this.
Given two tensors, I want to keep elements with the minimum absolute values, in each one of them as well as the sign.
I thought about
sign_x = torch.sign(x)
sign_y = torch.sign(y)
min = torch.min(torch.abs(x), torch.ab... |
INSTRUCTION:
Problem:
I want to use a logical index to slice a torch tensor. Which means, I want to select the columns that get a '0' in the logical index.
I tried but got some errors:
TypeError: indexing a tensor with an object of type ByteTensor. The only supported types are integers, slices, numpy scalars and torch... |
INSTRUCTION:
Problem:
I have two tensors of dimension 1000 * 1. I want to check how many of the 1000 elements are equal in the two tensors. I think I should be able to do this in few lines like Numpy but couldn't find a similar function.
A:
<code>
import numpy as np
import pandas as pd
import torch
A, B = load_data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.