prompt stringlengths 179 2.8k | reference_code stringlengths 16 685 | metadata dict | code_context stringlengths 747 5.45k |
|---|---|---|---|
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 classes (0, 1... | # def solve(softmax_output):
### BEGIN SOLUTION
y = torch.argmin(softmax_output, dim=1).detach()
### END SOLUTION
# return y
# y = solve(softmax_output)
| {
"problem_id": 978,
"library_problem_id": 46,
"library": "Pytorch",
"test_case_cnt": 2,
"perturbation_type": "Difficult-Rewrite",
"perturbation_origin_id": 42
} | import torch
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
softmax_output = torch.FloatTensor(
[[0.2, 0.1, 0.7], [0.6, 0.1, 0.3], [0.4, 0.5, 0.1]]
)
elif test_case_id == 2:
softmax_ou... |
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, however, that is ... | for param_group in optim.param_groups:
param_group['lr'] = 0.001
| {
"problem_id": 933,
"library_problem_id": 1,
"library": "Pytorch",
"test_case_cnt": 1,
"perturbation_type": "Surface",
"perturbation_origin_id": 0
} | import torch
import copy
from torch import nn
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
class MyAttentionBiLSTM(nn.Module):
def __init__(self):
super(MyAttentionBiLSTM, self).__init__()
... |
Problem:
look at my code below:
import pandas as pd
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import SelectFromModel
import numpy as np
df = pd.read_csv('los_10_one_encoder.csv')
y = df['LOS'] # target
X= df.drop('LOS',axis=1) # drop LOS column
clf = ExtraTreesClassifier(rando... | model = SelectFromModel(clf, prefit=True)
column_names = X.columns[model.get_support()] | {
"problem_id": 859,
"library_problem_id": 42,
"library": "Sklearn",
"test_case_cnt": 1,
"perturbation_type": "Surface",
"perturbation_origin_id": 41
} | import numpy as np
import pandas as pd
import copy
import tokenize, io
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.feature_selection import SelectFromModel
import sklearn
from sklearn.datasets import make_classification
def generate_test_case(test_case_id):
def define_test_input(test_case_id):... |
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?
Note I need... | from sklearn.feature_extraction import DictVectorizer
X = [dict(enumerate(x)) for x in X]
vect = DictVectorizer(sparse=False)
new_X = vect.fit_transform(X) | {
"problem_id": 916,
"library_problem_id": 99,
"library": "Sklearn",
"test_case_cnt": 0,
"perturbation_type": "Origin",
"perturbation_origin_id": 99
} | def generate_test_case(test_case_id):
return None, None
def exec_test(result, ans):
try:
assert len(result[0]) > 1 and len(result[1]) > 1
return 1
except:
return 0
exec_context = r"""
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
X = [['as... |
Problem:
I have a pandas Dataframe like below:
UserId ProductId Quantity
1 1 6
1 4 1
1 7 3
2 4 2
3 2 7
3 1 2
Now, I want to randomly select the 20% of rows of this DataFrame, using df.sample(n), set... | def g(df):
l = int(0.2 * len(df))
dfupdate = df.sample(l, random_state=0)
dfupdate.Quantity = 0
df.update(dfupdate)
return df
df = g(df.copy())
| {
"problem_id": 127,
"library_problem_id": 127,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Origin",
"perturbation_origin_id": 127
} | import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
l = int(0.2 * len(df))
dfupdate = df.sample(l, random_state=0)
dfupdate.Quantity = 0
df.update(dfupdate)
return df
def... |
import pandas as pd
import matplotlib.pyplot as plt
values = [[1, 2], [3, 4]]
df = pd.DataFrame(values, columns=["Type A", "Type B"], index=["Index 1", "Index 2"])
# Plot values in df with line chart
# label the x axis and y axis in this plot as "X" and "Y"
# SOLUTION START
| df.plot()
plt.xlabel("X")
plt.ylabel("Y") | {
"problem_id": 608,
"library_problem_id": 97,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 97
} | import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
values = [[1, 2], [3, 4]]
df = pd.DataFrame(
... |
Problem:
I am new to scikit-learn, but it did what I was hoping for. Now, maddeningly, the only remaining issue is that I don't find how I could print the model's coefficients it estimated. Especially when it comes to a pipeline fitted by a GridSearch. Now I have a pipeline including data scaling, centering, and a cla... | grid.fit(X, y)
coef = grid.best_estimator_.named_steps['model'].coef_
| {
"problem_id": 856,
"library_problem_id": 39,
"library": "Sklearn",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 39
} | import numpy as np
import copy
from sklearn.linear_model import SGDClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
import sklearn
from sklearn.datasets import make_classification
def generate_test_case(test_case_id):
... |
Problem:
i got an issue over ranking of date times. Lets say i have following table.
ID TIME
01 2018-07-11 11:12:20
01 2018-07-12 12:00:23
01 2018-07-13 12:00:00
02 2019-09-11 11:00:00
02 2019-09-12 12:00:00
and i want to add another column to rank the table by time for each id and group. I used
df... | def g(df):
df['TIME'] = pd.to_datetime(df['TIME'])
df['RANK'] = df.groupby('ID')['TIME'].rank(ascending=False)
return df
df = g(df.copy())
| {
"problem_id": 260,
"library_problem_id": 260,
"library": "Pandas",
"test_case_cnt": 1,
"perturbation_type": "Semantic",
"perturbation_origin_id": 259
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["TIME"] = pd.to_datetime(df["TIME"])
df["RANK"] = df.groupby("ID")["TIME"].rank(ascending=False)
return df
def define_test_input(test_case_id):
... |
Problem:
I have
df = pd.DataFrame.from_dict({'id': ['A', 'B', 'A', 'C', 'D', 'B', 'C'], 'val': [1,2,-3,1,5,6,-2], 'stuff':['12','23232','13','1234','3235','3236','732323']})
id stuff val
0 A 12 1
1 B 23232 2
2 A 13 -3
3 C 1234 1
4 D 3235 5
5 B 3236 6
6 C 732323 -2
... | def g(df):
df['cumsum'] = df.groupby('id')['val'].transform(pd.Series.cumsum)
df['cumsum'] = df['cumsum'].where(df['cumsum'] > 0, 0)
return df
df = g(df.copy())
| {
"problem_id": 147,
"library_problem_id": 147,
"library": "Pandas",
"test_case_cnt": 3,
"perturbation_type": "Difficult-Rewrite",
"perturbation_origin_id": 143
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["cumsum"] = df.groupby("id")["val"].transform(pd.Series.cumsum)
df["cumsum"] = df["cumsum"].where(df["cumsum"] > 0, 0)
return df
def define_test_input(... |
Problem:
I want to capture an integral of a column of my dataframe with a time index. This works fine for a grouping that happens every time interval.
from scipy import integrate
>>> df
Time A
2017-12-18 19:54:40 -50187.0
2017-12-18 19:54:45 -60890.5
2017-12-18 19:54:50 -28258.5
2017-12-18 19... | df.Time = pd.to_datetime(df.Time, format='%Y-%m-%d-%H:%M:%S')
df = df.set_index('Time')
integral_df = df.rolling('25S').apply(integrate.trapz)
| {
"problem_id": 810,
"library_problem_id": 99,
"library": "Scipy",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 99
} | import pandas as pd
import io
import copy
from scipy import integrate
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
string = """
Time A
2017-12-18-19:54:40 -50187.0
2017-12-18-19:54:45 -60890.5
2017-12-... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.arange(10)
plt.plot(x, y, marker="*", label="Line")
# Show a legend of this plot and show two markers on the line
# SOLUTION START
| plt.legend(numpoints=2) | {
"problem_id": 635,
"library_problem_id": 124,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Semantic",
"perturbation_origin_id": 121
} | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
x = np.arange(10)
y = np.arange(10)
plt.plot(x,... |
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 scores (shape... | idx = ids.repeat(1, 114).view(30, 1, 114)
result = torch.gather(x, 1, idx)
result = result.squeeze(1) | {
"problem_id": 972,
"library_problem_id": 40,
"library": "Pytorch",
"test_case_cnt": 1,
"perturbation_type": "Surface",
"perturbation_origin_id": 39
} | import torch
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
torch.random.manual_seed(42)
if test_case_id == 1:
x = torch.arange(30 * 3 * 114).view(30, 3, 114)
ids = torch.randint(0, 3, size=(30, 1))
return ids, x
def gene... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.arange(0, 1000, 50)
y = np.arange(0, 1000, 50)
# plot y over x on a log-log plot
# mark the axes with numbers like 1, 10, 100. do not use scientific notation
# SOLUTION START
| fig, ax = plt.subplots()
ax.plot(x, y)
ax.axis([1, 1000, 1, 1000])
ax.loglog()
from matplotlib.ticker import ScalarFormatter
for axis in [ax.xaxis, ax.yaxis]:
formatter = ScalarFormatter()
formatter.set_scientific(False)
axis.set_major_formatter(formatter) | {
"problem_id": 593,
"library_problem_id": 82,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 82
} | import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
from matplotlib.ticker import ScalarFormatter
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
x = np.arange(0, 1000, 50)
... |
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 partially overlap by... | c = (a[:, -1:] + b[:, :1]) / 2
result = torch.cat((a[:, :-1], c, b[:, 1:]), dim=1) | {
"problem_id": 994,
"library_problem_id": 62,
"library": "Pytorch",
"test_case_cnt": 3,
"perturbation_type": "Origin",
"perturbation_origin_id": 62
} | import torch
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
a = torch.Tensor([[1, 2, 3], [1, 2, 3]])
b = torch.Tensor([[5, 6, 7], [5, 6, 7]])
elif test_case_id == 2:
a = torch.Tensor([[3, 2, 1], [1, 2... |
Problem:
I have a dataset with integer values. I want to find out frequent value in each row. This dataset have couple of millions records. What would be the most efficient way to do it? Following is the sample of the dataset.
import pandas as pd
data = pd.read_csv('myData.csv', sep = ',')
data.head()
bit1 bit2 b... | def g(df):
df['frequent'] = df.mode(axis=1)
for i in df.index:
df.loc[i, 'freq_count'] = (df.iloc[i]==df.loc[i, 'frequent']).sum() - 1
return df
df = g(df.copy())
| {
"problem_id": 285,
"library_problem_id": 285,
"library": "Pandas",
"test_case_cnt": 1,
"perturbation_type": "Semantic",
"perturbation_origin_id": 284
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["frequent"] = df.mode(axis=1)
for i in df.index:
df.loc[i, "freq_count"] = (df.iloc[i] == df.loc[i, "frequent"]).sum() - 1
return df
def de... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
x = np.arange(10)
y = np.random.randn(10)
plt.scatter(x, y)
# show yticks and horizontal grid at y positions 3 and 4
# SOLUTION START
| ax = plt.gca()
ax.yaxis.set_ticks([3, 4])
ax.yaxis.grid(True) | {
"problem_id": 554,
"library_problem_id": 43,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Semantic",
"perturbation_origin_id": 42
} | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from PIL import Image
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
x = np.arange(10)
y = np.rand... |
Problem:
I realize my question is fairly similar to Vectorized moving window on 2D array in numpy , but the answers there don't quite satisfy my needs.
Is it possible to do a vectorized 2D moving window (rolling window) which includes so-called edge effects? What would be the most efficient way to do this?
That is, I w... | def window(arr, shape=(3, 3)):
ans = []
# Find row and column window sizes
r_win = np.floor(shape[0] / 2).astype(int)
c_win = np.floor(shape[1] / 2).astype(int)
x, y = arr.shape
for i in range(x):
xmin = max(0, i - r_win)
xmax = min(x, i + r_win + 1)
for j in range(y):
... | {
"problem_id": 467,
"library_problem_id": 176,
"library": "Numpy",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 176
} | import numpy as np
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
a = np.array([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7]])
size = (3, 3)
return a, size
def generate_ans(data):
_a = data... |
Problem:
I have a MultiIndexed pandas DataFrame that needs sorting by one of the indexers. Here is a snippet of the data:
gene VIM
treatment dose time
TGFb 0.1 2 -0.158406
1 2 0.039158
10 2 -0.052608
0.1 24 0.157153
... | def g(df):
return df.sort_index(level='time')
result = g(df.copy())
| {
"problem_id": 276,
"library_problem_id": 276,
"library": "Pandas",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 276
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.sort_index(level="time")
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
{
... |
Problem:
The title might not be intuitive--let me provide an example. Say I have df, created with:
a = np.array([[ 1. , 0.9, 1. ],
[ 0.9, 0.9, 1. ],
[ 0.8, 1. , 0.5],
[ 1. , 0.3, 0.2],
[ 1. , 0.2, 0.1],
[ 0.9, 1. , 1. ],
[ ... | def g(df):
return df.mask(~(df == df.min()).cumsum().astype(bool)).idxmax()
result = g(df.copy())
| {
"problem_id": 55,
"library_problem_id": 55,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Semantic",
"perturbation_origin_id": 54
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.mask(~(df == df.min()).cumsum().astype(bool)).idxmax()
def define_test_input(test_case_id):
if test_case_id == 1:
a = np.array(
... |
Problem:
I am using Pandas to get a dataframe like this:
name a b c
0 Aaron 3 5 7
1 Aaron 3 6 9
2 Aaron 3 6 10
3 Brave 4 6 0
4 Brave 3 6 1
I want to replace each name with a unique ID so output looks like:
name a b c
0 1 3 5 7
1 1 3 6 9
2 1 3 6 10
3 2 4 6... | def g(df):
F = {}
cnt = 0
for i in range(len(df)):
if df['name'].iloc[i] not in F.keys():
cnt += 1
F[df['name'].iloc[i]] = cnt
df.loc[i,'name'] = F[df.loc[i,'name']]
return df
result = g(df.copy())
| {
"problem_id": 61,
"library_problem_id": 61,
"library": "Pandas",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 61
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
F = {}
cnt = 0
for i in range(len(df)):
if df["name"].iloc[i] not in F.keys():
cnt += 1
F[df["name"].iloc[i]] = cnt... |
Problem:
I would like to predict the probability from Logistic Regression model with cross-validation. I know you can get the cross-validation scores, but is it possible to return the values from predict_proba instead of the scores? please save the probabilities into a list or an array.
A:
<code>
import numpy as np
... | from sklearn.model_selection import cross_val_predict
proba = cross_val_predict(logreg, X, y, cv=cv, method='predict_proba') | {
"problem_id": 839,
"library_problem_id": 22,
"library": "Sklearn",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 22
} | import numpy as np
import copy
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_predict, StratifiedKFold
import sklearn
from sklearn import datasets
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
... |
Problem:
I have integers in the range 0..2**m - 1 and I would like to convert them to binary numpy arrays of length m. For example, say m = 4. Now 15 = 1111 in binary and so the output should be (1,1,1,1). 2 = 10 in binary and so the output should be (0,0,1,0). If m were 3 then 2 should be converted to (0,1,0).
I tried... | result = (((a[:,None] & (1 << np.arange(m))[::-1])) > 0).astype(int)
| {
"problem_id": 425,
"library_problem_id": 134,
"library": "Numpy",
"test_case_cnt": 2,
"perturbation_type": "Origin",
"perturbation_origin_id": 134
} | import numpy as np
import pandas as pd
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
a = np.array([1, 2, 3, 4, 5])
m = 8
elif test_case_id == 2:
np.random.seed(42)
a = np.random.randint(0... |
Problem:
I have the following dataframe:
index = range(14)
data = [1, 0, 0, 2, 0, 4, 6, 8, 0, 0, 0, 0, 2, 1]
df = pd.DataFrame(data=data, index=index, columns = ['A'])
How can I fill the zeros with the previous non-zero value using pandas? Is there a fillna that is not just for "NaN"?.
The output should look like:
... | def g(df):
df['A'].replace(to_replace=0, method='ffill', inplace=True)
return df
df = g(df.copy())
| {
"problem_id": 82,
"library_problem_id": 82,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Origin",
"perturbation_origin_id": 82
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df["A"].replace(to_replace=0, method="ffill", inplace=True)
return df
def define_test_input(test_case_id):
if test_case_id == 1:
index = range... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.arange(10)
# Plot y over x
# Turn minor ticks on and show gray dashed minor grid lines
# Do not show any major grid lines
# SOLUTION START
| plt.plot(y, x)
plt.minorticks_on()
plt.grid(color="gray", linestyle="dashed", which="minor") | {
"problem_id": 620,
"library_problem_id": 109,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 109
} | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
x = np.arange(10)
y = np.arange(10)
plt.plot(y,... |
Problem:
I am having a problem with minimization procedure. Actually, I could not create a correct objective function for my problem.
Problem definition
• My function: yn = a_11*x1**2 + a_12*x2**2 + ... + a_m*xn**2,where xn- unknowns, a_m - coefficients. n = 1..N, m = 1..M
• In my case, N=5 for x1,..,x5 and M=3 for y... | def residual_ans(x, a, y):
s = ((y - a.dot(x**2))**2).sum()
return s
bounds = [[x, None] for x in x_lower_bounds]
out = scipy.optimize.minimize(residual_ans, x0=x0, args=(a, y), method= 'L-BFGS-B', bounds=bounds).x | {
"problem_id": 787,
"library_problem_id": 76,
"library": "Scipy",
"test_case_cnt": 1,
"perturbation_type": "Difficult-Rewrite",
"perturbation_origin_id": 75
} | import numpy as np
import copy
import scipy.optimize
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
np.random.seed(42)
a = np.random.rand(3, 5)
x_true = np.array([10, 13, 5, 8, 40])
y = a.dot(x_true**2)
... |
Problem:
I have following pandas dataframe :
import pandas as pd
from pandas import Series, DataFrame
data = DataFrame({'Qu1': ['apple', 'potato', 'cheese', 'banana', 'cheese', 'banana', 'cheese', 'potato', 'egg'],
'Qu2': ['sausage', 'banana', 'apple', 'apple', 'apple', 'sausage', 'banana', 'banana', '... | def g(df):
return df.where(df.apply(lambda x: x.map(x.value_counts())) >= 2, "other")
result = g(df.copy())
| {
"problem_id": 2,
"library_problem_id": 2,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Origin",
"perturbation_origin_id": 2
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.where(df.apply(lambda x: x.map(x.value_counts())) >= 2, "other")
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFram... |
Problem:
How do we pass four datasets in scipy.stats.anderson_ksamp?
The anderson function asks only for one parameter and that should be 1-d array. So I am wondering how to pass four different arrays to be compared in it? Thanks
A:
<code>
import numpy as np
import scipy.stats as ss
x1=[38.7, 41.5, 43.8, 44.5, 45.... | statistic, critical_values, significance_level = ss.anderson_ksamp([x1,x2,x3,x4])
| {
"problem_id": 753,
"library_problem_id": 42,
"library": "Scipy",
"test_case_cnt": 2,
"perturbation_type": "Origin",
"perturbation_origin_id": 42
} | import numpy as np
import copy
import scipy.stats as ss
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
x1 = [38.7, 41.5, 43.8, 44.5, 45.5, 46.0, 47.7, 58.0]
x2 = [39.2, 39.3, 39.7, 41.4, 41.8, 42.9, 43.3, 45.8]
x3 = [34.... |
Problem:
I have a dataset :
id url keep_if_dup
1 A.com Yes
2 A.com Yes
3 B.com No
4 B.com No
5 C.com No
I want to remove duplicates, i.e. keep first occurence of "url" field, BUT keep duplicates if the field "keep_if_dup" is YES.
Expected output :
id url keep_if_dup
1 ... | def g(df):
return df.loc[(df['keep_if_dup'] =='Yes') | ~df['url'].duplicated()]
result = g(df.copy())
| {
"problem_id": 7,
"library_problem_id": 7,
"library": "Pandas",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 7
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.loc[(df["keep_if_dup"] == "Yes") | ~df["url"].duplicated()]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
... |
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 document?',
]... | vectorizer = CountVectorizer(stop_words="english", binary=True, lowercase=False,
vocabulary=['Jscript', '.Net', 'TypeScript', 'NodeJS', 'Angular', 'Mongo',
'CSS',
'Python', 'PHP', 'Photoshop', 'Oracle', 'Linux... | {
"problem_id": 903,
"library_problem_id": 86,
"library": "Sklearn",
"test_case_cnt": 1,
"perturbation_type": "Surface",
"perturbation_origin_id": 85
} | import numpy as np
import copy
from sklearn.feature_extraction.text import CountVectorizer
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
corpus = [
"We are looking for Java developer",
"Frontend developer with k... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.random.rand(10)
z = np.random.rand(10)
a = np.arange(10)
# Make two subplots
# Plot y over x in the first subplot and plot z over a in the second subplot
# Label each line chart and put them into a single legend on the fir... | fig, ax = plt.subplots(2, 1)
(l1,) = ax[0].plot(x, y, color="red", label="y")
(l2,) = ax[1].plot(a, z, color="blue", label="z")
ax[0].legend([l1, l2], ["z", "y"]) | {
"problem_id": 626,
"library_problem_id": 115,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 115
} | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
x = np.arange(10)
y = np.random.rand(10)
z = np... |
Problem:
Sample dataframe:
df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]})
I'd like to add exponentials of each existing column to the dataframe and name them based on existing column names with a prefix, e.g. exp_A is an exponential of column A and so on.
The resulting dataframe should look like so:
result = pd.D... | import math
def g(df):
return df.join(df.apply(lambda x: math.e**x).add_prefix('exp_'))
result = g(df.copy())
| {
"problem_id": 51,
"library_problem_id": 51,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Semantic",
"perturbation_origin_id": 50
} | import pandas as pd
import numpy as np
import math
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.join(df.apply(lambda x: math.e**x).add_prefix("exp_"))
def define_test_input(test_case_id):
if test_case_id == 1:
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
x = 10 * np.random.randn(10)
y = x
plt.plot(x, y, label="x-y")
# put legend in the lower right
# SOLUTION START
| plt.legend(loc="lower right") | {
"problem_id": 557,
"library_problem_id": 46,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 46
} | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from PIL import Image
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
x = 10 * np.random.randn(10)
... |
Problem:
How can I get get the position (indices) of the smallest value in a multi-dimensional NumPy array `a`?
Note that I want to get the raveled index of it, in C order.
A:
<code>
import numpy as np
a = np.array([[10,50,30],[60,20,40]])
</code>
result = ... # put solution in this variable
BEGIN SOLUTION
<code>
| result = a.argmin()
| {
"problem_id": 310,
"library_problem_id": 19,
"library": "Numpy",
"test_case_cnt": 2,
"perturbation_type": "Semantic",
"perturbation_origin_id": 18
} | import numpy as np
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
a = np.array([[10, 50, 30], [60, 20, 40]])
elif test_case_id == 2:
np.random.seed(42)
a = np.random.rand(np.random.randint(5, 10), np.... |
Problem:
In pandas, how do I replace & with '&' from all columns where & could be in any position in a string?
For example, in column Title if there is a value 'Good & bad', how do I replace it with 'Good & bad'?
A:
<code>
import pandas as pd
df = pd.DataFrame({'A': ['Good & bad', 'BB', 'CC', 'DD', '... | def g(df):
return df.replace('&','&', regex=True)
df = g(df.copy())
| {
"problem_id": 100,
"library_problem_id": 100,
"library": "Pandas",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 100
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.replace("&", "&", regex=True)
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
{
... |
Problem:
Given the following example:
from sklearn.feature_selection import SelectKBest
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
import pandas as pd
pipe = Pipeline(steps=[
('select', SelectKBest(k=2)),
('clf', LogisticRegression())]
)
pipe.fit(data, target)
... | select_out = pipe.named_steps['select'].fit_transform(data, target) | {
"problem_id": 848,
"library_problem_id": 31,
"library": "Sklearn",
"test_case_cnt": 1,
"perturbation_type": "Surface",
"perturbation_origin_id": 29
} | import numpy as np
import copy
import tokenize, io
from sklearn.feature_selection import SelectKBest
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
import sklearn
from sklearn.datasets import load_iris
def generate_test_case(test_case_id):
def define_test_input(test_cas... |
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, ..., n.
The numb... | n = features_dataframe.shape[0]
train_size = 0.2
train_dataframe = features_dataframe.iloc[:int(n * train_size)]
test_dataframe = features_dataframe.iloc[int(n * train_size):] | {
"problem_id": 921,
"library_problem_id": 104,
"library": "Sklearn",
"test_case_cnt": 2,
"perturbation_type": "Origin",
"perturbation_origin_id": 104
} | import pandas as pd
import datetime
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
{
"date": [
"2017-03-01",
"2017-03-02",
... |
Problem:
I have a DataFrame like :
0 1 2
0 0.0 1.0 2.0
1 1.0 2.0 NaN
2 2.0 NaN NaN
What I want to get is
Out[116]:
0 1 2
0 0.0 1.0 2.0
1 Nan 1.0 2.0
2 NaN NaN 2.0
This is my approach as of now.
df.apply(lambda x : (x[x.isnull()].values.tolist()+x[x.notnull()].values.tolist())... | def justify(a, invalid_val=0, axis=1, side='left'):
if invalid_val is np.nan:
mask = ~np.isnan(a)
else:
mask = a!=invalid_val
justified_mask = np.sort(mask,axis=axis)
if (side=='up') | (side=='left'):
justified_mask = np.flip(justified_mask,axis=axis)
out = np.full(a.shape, i... | {
"problem_id": 45,
"library_problem_id": 45,
"library": "Pandas",
"test_case_cnt": 1,
"perturbation_type": "Semantic",
"perturbation_origin_id": 44
} | import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
def justify(a, invalid_val=0, axis=1, side="left"):
if invalid_val is np.nan:
mask = ~np.isnan(a)
else:
... |
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 classes (0, 1... | y = torch.argmin(softmax_output, dim=1).view(-1, 1)
| {
"problem_id": 976,
"library_problem_id": 44,
"library": "Pytorch",
"test_case_cnt": 2,
"perturbation_type": "Semantic",
"perturbation_origin_id": 42
} | import torch
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
softmax_output = torch.FloatTensor(
[[0.2, 0.1, 0.7], [0.6, 0.1, 0.3], [0.4, 0.5, 0.1]]
)
elif test_case_id == 2:
softmax_ou... |
Problem:
How do I find all rows in a pandas DataFrame which have the max value for count column, after grouping by ['Sp','Mt'] columns?
Example 1: the following DataFrame, which I group by ['Sp','Mt']:
Sp Mt Value count
0 MM1 S1 a **3**
1 MM1 S1 n 2
2 MM1 S3 cb **5**
3 MM2 S3 mk ... | def g(df):
return df[df.groupby(['Sp', 'Mt'])['count'].transform(max) == df['count']]
result = g(df.copy())
| {
"problem_id": 136,
"library_problem_id": 136,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Surface",
"perturbation_origin_id": 135
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df[df.groupby(["Sp", "Mt"])["count"].transform(max) == df["count"]]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFram... |
Problem:
I have a pandas Dataframe like below:
UserId ProductId Quantity
1 1 6
1 4 1
1 7 3
2 4 2
3 2 7
3 1 2
Now, I want to randomly select the 20% of rows of this DataFrame, using df.sample(n), set... | def g(df):
l = int(0.2 * len(df))
dfupdate = df.sample(l, random_state=0)
dfupdate.ProductId = 0
df.update(dfupdate)
return df
df = g(df.copy())
| {
"problem_id": 128,
"library_problem_id": 128,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Semantic",
"perturbation_origin_id": 127
} | import pandas as pd
import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
l = int(0.2 * len(df))
dfupdate = df.sample(l, random_state=0)
dfupdate.ProductId = 0
df.update(dfupdate)
return df
de... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.arange(10)
plt.plot(x, y)
# Remove the margin before the first xtick but use greater than zero margin for the yaxis
# SOLUTION START
| plt.margins(x=0) | {
"problem_id": 605,
"library_problem_id": 94,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 94
} | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
x = np.arange(10)
y = np.arange(10)
plt.plot(x,... |
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: indexing a tenso... | # def solve(A_log, B):
### BEGIN SOLUTION
C = B[:, A_log.bool()]
### END SOLUTION
# return C
return C
| {
"problem_id": 945,
"library_problem_id": 13,
"library": "Pytorch",
"test_case_cnt": 3,
"perturbation_type": "Surface",
"perturbation_origin_id": 9
} | import torch
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
A_log = torch.LongTensor([0, 1, 0])
B = torch.LongTensor([[1, 2, 3], [4, 5, 6]])
elif test_case_id == 2:
A_log = torch.BoolTensor([True, Fal... |
Problem:
I'm trying to integrate X (X ~ N(u, o2)) to calculate the probability up to position `x`.
However I'm running into an error of:
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
File "siestats.py", line 349, in NormalDistro
P_inner = scipy.integrate(NDfx,-dev,dev)
TypeEr... | norm = (x-u)/o2
prob = scipy.integrate.quad(NDfx, -np.inf, norm)[0]
return prob
| {
"problem_id": 773,
"library_problem_id": 62,
"library": "Scipy",
"test_case_cnt": 2,
"perturbation_type": "Surface",
"perturbation_origin_id": 61
} | import numpy as np
import math
import copy
import scipy.integrate
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
x = 2.5
u = 1
o2 = 3
elif test_case_id == 2:
x = -2.5
u = 2
o2 ... |
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: indexing a tenso... | C = B[:, A_log.bool()] | {
"problem_id": 941,
"library_problem_id": 9,
"library": "Pytorch",
"test_case_cnt": 3,
"perturbation_type": "Origin",
"perturbation_origin_id": 9
} | import torch
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
A_log = torch.LongTensor([0, 1, 0])
B = torch.LongTensor([[1, 2, 3], [4, 5, 6]])
elif test_case_id == 2:
A_log = torch.BoolTensor([True, Fal... |
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random((10, 10))
# Set xlim and ylim to be between 0 and 10
# Plot a heatmap of data in the rectangle where right is 5, left is 1, bottom is 1, and top is 4.
# SOLUTION START
| plt.xlim(0, 10)
plt.ylim(0, 10)
plt.imshow(data, extent=[1, 5, 1, 4]) | {
"problem_id": 613,
"library_problem_id": 102,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 102
} | import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import matplotlib
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
data = np.random.random((10, 10))
plt.xlim(0, 10)
... |
Problem:
I have a data frame like below
A_Name B_Detail Value_B Value_C Value_D ......
0 AA X1 1.2 0.5 -1.3 ......
1 BB Y1 0.76 -0.7 0.8 ......
2 CC Z1 0.7 -1.3 2.5 ......
3 DD L1 0.9 -0.5 0.4 ......... | def g(df):
mask = (df.filter(like='Value').abs() > 1).any(axis=1)
return df[mask]
df = g(df.copy())
| {
"problem_id": 98,
"library_problem_id": 98,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Semantic",
"perturbation_origin_id": 97
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
mask = (df.filter(like="Value").abs() > 1).any(axis=1)
return df[mask]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.Data... |
Problem:
I am looking for a way to convert a nXaXb numpy array into a block diagonal matrix. I have already came across scipy.linalg.block_diag, the down side of which (for my case) is it requires each blocks of the matrix to be given separately. However, this is challenging when n is very high, so to make things more ... | result = block_diag(*a) | {
"problem_id": 758,
"library_problem_id": 47,
"library": "Scipy",
"test_case_cnt": 2,
"perturbation_type": "Origin",
"perturbation_origin_id": 47
} | import numpy as np
import copy
from scipy.linalg import block_diag
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
np.random.seed(10)
a = np.random.rand(100, 2, 2)
elif test_case_id == 2:
np.random.seed(20)
... |
import numpy as np
import matplotlib.pyplot as plt
data = [1000, 1000, 5000, 3000, 4000, 16000, 2000]
# Make a histogram of data and renormalize the data to sum up to 1
# Format the y tick labels into percentage and set y tick labels as 10%, 20%, etc.
# SOLUTION START
| plt.hist(data, weights=np.ones(len(data)) / len(data))
from matplotlib.ticker import PercentFormatter
ax = plt.gca()
ax.yaxis.set_major_formatter(PercentFormatter(1)) | {
"problem_id": 595,
"library_problem_id": 84,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 84
} | import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import matplotlib
from matplotlib.ticker import PercentFormatter
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
data = [10... |
Problem:
numpy seems to not be a good friend of complex infinities
How do I compute mean of an array of complex numbers?
While we can evaluate:
In[2]: import numpy as np
In[3]: np.mean([1, 2, np.inf])
Out[3]: inf
The following result is more cumbersome:
In[4]: np.mean([1 + 0j, 2 + 0j, np.inf + 0j])
Out[4]: (inf+nan*j)
... | n = len(a)
s = np.sum(a)
result = np.real(s) / n + 1j * np.imag(s) / n
return result
| {
"problem_id": 470,
"library_problem_id": 179,
"library": "Numpy",
"test_case_cnt": 1,
"perturbation_type": "Surface",
"perturbation_origin_id": 178
} | import numpy as np
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
a = np.array([1 + 0j, 2 + 0j, np.inf + 0j])
return a
def generate_ans(data):
_a = data
a = _a
n = len(a)
s = np.sum(a)
... |
Problem:
I have the following DF
Date
0 2018-01-01
1 2018-02-08
2 2018-02-08
3 2018-02-08
4 2018-02-08
I have another list of two date:
[2017-08-17, 2018-01-31]
For data between 2017-08-17 to 2018-01-31,I want to extract the month name and year and day in a simple way in the following format:
... | df = df[df['Date'] >= List[0]]
df = df[df['Date'] <= List[1]]
df['Date'] = df['Date'].dt.strftime('%d-%b-%Y %A') | {
"problem_id": 25,
"library_problem_id": 25,
"library": "Pandas",
"test_case_cnt": 1,
"perturbation_type": "Difficult-Rewrite",
"perturbation_origin_id": 23
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
df, List = data
df = df[df["Date"] >= List[0]]
df = df[df["Date"] <= List[1]]
df["Date"] = df["Date"].dt.strftime("%d-%b-%Y %A")
return df
... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.rand(10)
y = np.random.rand(10)
plt.scatter(x, y)
# how to turn on minor ticks on x axis only
# SOLUTION START
| plt.minorticks_on()
ax = plt.gca()
ax.tick_params(axis="y", which="minor", tick1On=False) | {
"problem_id": 514,
"library_problem_id": 3,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Semantic",
"perturbation_origin_id": 1
} | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from PIL import Image
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
x = np.random.rand(10)
y = np... |
Problem:
I have dfs as follows:
df1:
id city district date value
0 1 bj ft 2019/1/1 1
1 2 bj ft 2019/1/1 5
2 3 sh hp 2019/1/1 9
3 4 sh hp 2019/1/1 13
4 5 sh hp 2019/1/1 17
df2
id date value
0 3 2019/2/1 1
1 4 20... | def g(df1, df2):
df = pd.concat([df1,df2.merge(df1[['id','city','district']], how='left', on='id')],sort=False).reset_index(drop=True)
return df.sort_values(by=['id','date']).reset_index(drop=True)
result = g(df1.copy(),df2.copy())
| {
"problem_id": 239,
"library_problem_id": 239,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Difficult-Rewrite",
"perturbation_origin_id": 237
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
data = data
df1, df2 = data
df = pd.concat(
[df1, df2.merge(df1[["id", "city", "district"]], how="left", on="id")],
sort=False,
).reset_index(dro... |
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()
</code>
cn... | cnt_equal = int((A == B).sum()) | {
"problem_id": 980,
"library_problem_id": 48,
"library": "Pytorch",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 48
} | import numpy as np
import torch
import copy
import tokenize, io
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
torch.random.manual_seed(42)
A = torch.randint(2, (1000,))
torch.random.manual_seed(7)
B = torch.... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.arange(10)
# Plot y over x in a line chart but use transparent marker with non-transparent edge
# SOLUTION START
| plt.plot(
x, y, "-o", ms=14, markerfacecolor="None", markeredgecolor="red", markeredgewidth=5
) | {
"problem_id": 623,
"library_problem_id": 112,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 112
} | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
x = np.arange(10)
y = np.arange(10)
plt.plot(
... |
Problem:
I have a Pandas dataframe that looks like the below:
codes
1 [71020]
2 [77085]
3 [36415]
4 [99213, 99287]
5 [99233, 99233, 99233]
I'm trying to split the lists in df['codes'] into columns, like the below:
... | def g(df):
df = df.codes.apply(pd.Series)
cols = list(df)
for i in range(len(cols)):
cols[i]+=1
df.columns = cols
return df.add_prefix('code_')
result = g(df.copy())
| {
"problem_id": 252,
"library_problem_id": 252,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Semantic",
"perturbation_origin_id": 251
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
df = df.codes.apply(pd.Series)
cols = list(df)
for i in range(len(cols)):
cols[i] += 1
df.columns = cols
return df.add_prefix("code... |
import seaborn as sns
import matplotlib.pylab as plt
import pandas
import numpy as np
df = pandas.DataFrame(
{
"a": np.arange(1, 31),
"b": ["A",] * 10 + ["B",] * 10 + ["C",] * 10,
"c": np.random.rand(30),
}
)
# Use seaborn FaceGrid for rows in "b" and plot seaborn pointplots of "c" ove... | g = sns.FacetGrid(df, row="b")
g.map(sns.pointplot, "a", "c")
for ax in g.axes.flat:
labels = ax.get_xticklabels() # get x labels
for i, l in enumerate(labels):
if i % 2 == 0:
labels[i] = "" # skip even labels
ax.set_xticklabels(labels) # set new labels | {
"problem_id": 662,
"library_problem_id": 151,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 151
} | import seaborn as sns
import matplotlib.pylab as plt
import pandas
import numpy as np
from PIL import Image
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
df = pandas.DataFrame(
{
... |
Problem:
I have a dataFrame with rows and columns that max value is 2.
A B C D
0 1 2 0 1
1 0 0 0 0
2 1 0 0 1
3 0 1 2 0
4 1 1 0 1
The end result should be
A D
1 0 0
2 1 1
4 1 1
Notice the rows and columns that had maximum 2 have been removed.
A:
<code>
import pandas as pd
df =... | def g(df):
return df.loc[(df.max(axis=1) != 2), (df.max(axis=0) != 2)]
result = g(df.copy())
| {
"problem_id": 171,
"library_problem_id": 171,
"library": "Pandas",
"test_case_cnt": 2,
"perturbation_type": "Semantic",
"perturbation_origin_id": 169
} | import pandas as pd
import numpy as np
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
df = data
return df.loc[(df.max(axis=1) != 2), (df.max(axis=0) != 2)]
def define_test_input(test_case_id):
if test_case_id == 1:
df = pd.DataFrame(
... |
Problem:
I'm looking for a fast solution to compute minimum of the elements of an array which belong to the same index.
Note that there might be negative indices in index, and we treat them like list indices in Python.
An example:
a = np.arange(1,11)
# array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
index = np.array([... | add = np.max(index)
mask =index < 0
index[mask] += add+1
uni = np.unique(index)
result = np.zeros(np.amax(index)+1)
for i in uni:
result[i] = np.min(a[index==i])
| {
"problem_id": 408,
"library_problem_id": 117,
"library": "Numpy",
"test_case_cnt": 2,
"perturbation_type": "Difficult-Rewrite",
"perturbation_origin_id": 114
} | import numpy as np
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
a = np.arange(1, 11)
index = np.array([0, 1, 0, 0, 0, -1, -1, 2, 2, 1])
elif test_case_id == 2:
np.random.seed(42)
index =... |
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), 1)
My code... | '''
training part
'''
# X, Y = load_iris(return_X_y=True)
# lossFunc = torch.nn.CrossEntropyLoss()
# opt = torch.optim.Adam(MyNet.parameters(), lr=0.001)
# for batch in range(0, 50):
# for i in range(len(X)):
# x = MyNet(torch.from_numpy(X[i]).float()).reshape(1, 3)
# y = torch.tensor(Y[i]).long().u... | {
"problem_id": 993,
"library_problem_id": 61,
"library": "Pytorch",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 61
} | import torch
import copy
import sklearn
from sklearn.datasets import load_iris
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
X, y = load_iris(return_X_y=True)
input = torch.from_numpy(X[42]).float()
torch.manual_seed(4... |
import numpy as np
import matplotlib.pyplot as plt
lines = [[(0, 1), (1, 1)], [(2, 3), (3, 3)], [(1, 2), (1, 3)]]
c = np.array([(1, 0, 0, 1), (0, 1, 0, 1), (0, 0, 1, 1)])
# Plot line segments according to the positions specified in lines
# Use the colors specified in c to color each line segment
# SOLUTION START
| for i in range(len(lines)):
plt.plot([lines[i][0][0], lines[i][1][0]], [lines[i][0][1], lines[i][1][1]], c=c[i]) | {
"problem_id": 592,
"library_problem_id": 81,
"library": "Matplotlib",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 81
} | import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
def skip_plt_cmds(l):
return all(
p not in l for p in ["plt.show()", "plt.clf()", "plt.close()", "savefig"]
)
def generate_test_case(test_case_id):
lines = [[(0, 1), (1, 1)], [(2, 3), (3, 3)], [(1, 2), (1, 3)]]
c = np.a... |
Problem:
How would you convert this Tensorflow 1.5 code to Tensorflow 2.3.0?
import tensorflow as tf
try:
Session = tf.Session
except AttributeError:
Session = tf.compat.v1.Session
tf.random.set_seed(10)
A = tf.random.normal([100,100])
B = tf.random.normal([100,100])
with Session() as sess:
result = sess.r... | tf.random.set_seed(10)
def get_values():
A = tf.random.normal([100,100])
B = tf.random.normal([100,100])
return A,B
@tf.function
def compute():
A,B = get_values()
return tf.reduce_sum(tf.matmul(A,B))
result = compute() | {
"problem_id": 701,
"library_problem_id": 35,
"library": "Tensorflow",
"test_case_cnt": 1,
"perturbation_type": "Origin",
"perturbation_origin_id": 35
} | import tensorflow as tf
import copy
def generate_test_case(test_case_id):
def generate_ans(data):
FLAG = data
return -805.02057
def define_test_input(test_case_id):
if test_case_id == 1:
FLAG = 114514
return FLAG
test_input = define_test_input(test_case_id)
... |
Problem:
I have integers in the range 0..2**m - 1 and I would like to convert them to binary numpy arrays of length m. For example, say m = 4. Now 15 = 1111 in binary and so the output should be (1,1,1,1). 2 = 10 in binary and so the output should be (0,0,1,0). If m were 3 then 2 should be converted to (0,1,0).
I tried... | res = np.array([0])
for i in a:
res = res ^ i
result = (((res[:,None] & (1 << np.arange(m))[::-1])) > 0).astype(int)
| {
"problem_id": 427,
"library_problem_id": 136,
"library": "Numpy",
"test_case_cnt": 2,
"perturbation_type": "Difficult-Rewrite",
"perturbation_origin_id": 134
} | import numpy as np
import pandas as pd
import copy
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
a = np.array([1, 2, 3, 4, 5])
m = 6
elif test_case_id == 2:
np.random.seed(42)
a = np.random.randint(0... |
Problem:
I am new to Python and I need to implement a clustering algorithm. For that, I will need to calculate distances between the given input data.
Consider the following input data -
a = np.array([[1,2,8,...],
[7,4,2,...],
[9,1,7,...],
[0,1,5,...],
[6,4,3,...],...])
What I am looking to achieve ... | result = np.linalg.norm(a - a[:, None], axis = -1)
| {
"problem_id": 457,
"library_problem_id": 166,
"library": "Numpy",
"test_case_cnt": 1,
"perturbation_type": "Surface",
"perturbation_origin_id": 165
} | import numpy as np
import copy
import tokenize, io
def generate_test_case(test_case_id):
def define_test_input(test_case_id):
if test_case_id == 1:
np.random.seed(42)
dim = np.random.randint(4, 8)
a = np.random.rand(np.random.randint(5, 10), dim)
return dim, a
... |
End of preview. Expand in Data Studio
README.md exists but content is empty.
- Downloads last month
- 9