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 &AMP; with '&' from all columns where &AMP could be in any position in a string? For example, in column Title if there is a value 'Good &AMP; bad', how do I replace it with 'Good & bad'? A: <code> import pandas as pd df = pd.DataFrame({'A': ['Good &AMP; bad', 'BB', 'CC', 'DD', '...
def g(df): return df.replace('&AMP;','&', 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("&AMP;", "&", 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 ...
Problem: Given a 2-dimensional array in python, I would like to normalize each row with L∞ Norm. I have started this code: from numpy import linalg as LA X = np.array([[1, 2, 3, 6], [4, 5, 6, 5], [1, 2, 5, 5], [4, 5,10,25], [5, 2,10,25]]) print X.shape x = np.arra...
linf = np.abs(X).max(axis = 1) result = X / linf.reshape(-1, 1)
{ "problem_id": 454, "library_problem_id": 163, "library": "Numpy", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 161 }
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: X = np.array( [ [1, -2, 3, 6], [4, 5, -6, 5], [-1, 2, 5, 5], ...
Problem: Let's say I have 5 columns. pd.DataFrame({ 'Column1': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'Column2': [4, 3, 6, 8, 3, 4, 1, 4, 3], 'Column3': [7, 3, 3, 1, 2, 2, 3, 2, 7], 'Column4': [9, 8, 7, 6, 5, 4, 3, 2, 1], 'Column5': [1, 1, 1, 1, 1, 1, 1, 1, 1]}) Is there a function to know the type of relationship each par of ...
def get_relation(df, col1, col2): first_max = df[[col1, col2]].groupby(col1).count().max()[0] second_max = df[[col1, col2]].groupby(col2).count().max()[0] if first_max==1: if second_max==1: return 'one-to-one' else: return 'one-to-many' else: if second_max...
{ "problem_id": 151, "library_problem_id": 151, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 151 }
import pandas as pd import numpy as np from itertools import product import copy def generate_test_case(test_case_id): def generate_ans(data): df = data def get_relation(df, col1, col2): first_max = df[[col1, col2]].groupby(col1).count().max()[0] second_max = df[[col1, col...
Problem: What is the canonical way to check if a SciPy CSR matrix is empty (i.e. contains only zeroes)? I use nonzero(): def is_csr_matrix_only_zeroes(my_csr_matrix): return(len(my_csr_matrix.nonzero()[0]) == 0) from scipy.sparse import csr_matrix print(is_csr_matrix_only_zeroes(csr_matrix([[1,2,0],[0,0,3],[4,0,5]]...
result = (sa.count_nonzero()==0)
{ "problem_id": 756, "library_problem_id": 45, "library": "Scipy", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 45 }
import copy from scipy import sparse def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: sa = sparse.random(10, 10, density=0.01, format="csr", random_state=42) elif test_case_id == 2: sa = sparse.csr_matrix([]) return sa...
Problem: I have a dataframe with column names, and I want to find the one that contains a certain string, but does not exactly match it. I'm searching for 'spike' in column names like 'spike-2', 'hey spike', 'spiked-in' (the 'spike' part is always continuous). I want the column name to be returned as a string or a var...
def g(df, s): spike_cols = [s for col in df.columns if s in col and s != col] for i in range(len(spike_cols)): spike_cols[i] = spike_cols[i]+str(i+1) result = df[[col for col in df.columns if s in col and col != s]] result.columns = spike_cols return result result = g(df.copy(),s)
{ "problem_id": 250, "library_problem_id": 250, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 248 }
import pandas as pd import numpy as np import copy def generate_test_case(test_case_id): def generate_ans(data): data = data df, s = data spike_cols = [s for col in df.columns if s in col and s != col] for i in range(len(spike_cols)): spike_cols[i] = spike_cols[i] + str...
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', 'SQL', 'NodeJS', 'Angular', 'Mongo', 'CSS', 'Python', 'PHP', 'Photoshop', 'Oracle',...
{ "problem_id": 904, "library_problem_id": 87, "library": "Sklearn", "test_case_cnt": 1, "perturbation_type": "Semantic", "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...
Problem: I'm working on a problem that has to do with calculating angles of refraction and what not. However, it seems that I'm unable to use the numpy.cos() function in degrees. I have tried to use numpy.degrees() and numpy.rad2deg(). degree = 90 numpy.cos(degree) numpy.degrees(numpy.cos(degree)) But with no help. Ho...
result = np.cos(np.deg2rad(degree))
{ "problem_id": 324, "library_problem_id": 33, "library": "Numpy", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 32 }
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: degree = 90 elif test_case_id == 2: np.random.seed(42) degree = np.random.randint(0, 360) return degree def generate_ans(...
Problem: Let X be a M x N matrix. Denote xi the i-th column of X. I want to create a 3 dimensional N x M x M array consisting of M x M matrices xi.dot(xi.T). How can I do it most elegantly with numpy? Is it possible to do this using only matrix operations, without loops? A: <code> import numpy as np X = np.random.randi...
result = X.T[:, :, None] * X.T[:, None]
{ "problem_id": 439, "library_problem_id": 148, "library": "Numpy", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 148 }
import numpy as np import pandas as pd 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) X = np.random.randint(2, 10, (5, 6)) elif test_case_id == 2: np.random.seed...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = sns.load_dataset("penguins")[ ["bill_length_mm", "bill_depth_mm", "flipper_length_mm", "body_mass_g"] ].head(10) # Plot df as a matplotlib table. Set the bbox of the table to [0, 0, 1, 1] # SOLUTION START
bbox = [0, 0, 1, 1] plt.table(cellText=df.values, rowLabels=df.index, bbox=bbox, colLabels=df.columns)
{ "problem_id": 650, "library_problem_id": 139, "library": "Matplotlib", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 139 }
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns 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): df = sns.load_d...
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) df['date'] = pd.to_datetime(df['date']) df['date'] = df['date'].dt.strftime('%d-%b-%Y') return df.sort_values(by=['id','date']).reset_index(drop=True) result = g(df1.co...
{ "problem_id": 238, "library_problem_id": 238, "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 a file with arrays or different shapes. I want to zeropad all the array to match the largest shape. The largest shape is (93,13). To test this I have the following code: arr = np.ones((41,13)) how can I zero pad this array to match the shape of (93,13)? And ultimately, how can I do it for thousands of r...
result = np.pad(arr, ((0, shape[0]-arr.shape[0]), (0, shape[1]-arr.shape[1])), 'constant') return result
{ "problem_id": 498, "library_problem_id": 207, "library": "Numpy", "test_case_cnt": 1, "perturbation_type": "Surface", "perturbation_origin_id": 204 }
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.ones((41, 13)) shape = (93, 13) return a, shape def generate_ans(data): _a = data arr, shape = _a ...
Problem: Scipy offers many useful tools for root finding, notably fsolve. Typically a program has the following form: def eqn(x, a, b): return x + 2*a - b**2 fsolve(eqn, x0=0.5, args = (a,b)) and will find a root for eqn(x) = 0 given some arguments a and b. However, what if I have a problem where I want to solve fo...
result = np.array([fsolve(lambda a,x,b: eqn(x, a, b), x0=0.5, args=(x,b))[0] for x, b in zip(xdata, bdata)])
{ "problem_id": 806, "library_problem_id": 95, "library": "Scipy", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 95 }
import numpy as np import copy from scipy.optimize import fsolve def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: np.random.seed(42) xdata = np.arange(4) + 3 bdata = np.random.randint(0, 10, (4,)) return xdata, bda...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns df = sns.load_dataset("penguins")[["bill_length_mm", "species", "sex"]] # Use seaborn catplot to plot multiple barplots of "bill_length_mm" over "sex" and separate into different subplot columns by "species" # Do not share y ...
sns.catplot( x="sex", col="species", y="bill_length_mm", data=df, kind="bar", sharey=False )
{ "problem_id": 629, "library_problem_id": 118, "library": "Matplotlib", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 118 }
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): df = sns.load_dataset("penguins")...
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 j in range(y): ymin = max(0, j - c_win) ymax = min(y, j + c_win + 1) for i in range(x): ...
{ "problem_id": 468, "library_problem_id": 177, "library": "Numpy", "test_case_cnt": 1, "perturbation_type": "Semantic", "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 created a multidimensional array in Python like this: self.cells = np.empty((r,c),dtype=np.object) Now I want to iterate through all elements of my two-dimensional array `X` and store element at each moment in result (an 1D list), in 'Fortran' order. How do I achieve this? A: <code> import numpy as np X...
result = [] for value in X.T.flat: result.append(value)
{ "problem_id": 343, "library_problem_id": 52, "library": "Numpy", "test_case_cnt": 1, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 49 }
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: np.random.seed(42) X = np.random.randint(2, 10, (5, 6)) return X def generate_ans(data): _a = data X = _a...
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 and name axis with labels ("x" and "y") # Hide tick labels but keep axis labels # SOLUTION START
fig, ax = plt.subplots() ax.plot(x, y) ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_xlabel("x") ax.set_ylabel("y")
{ "problem_id": 664, "library_problem_id": 153, "library": "Matplotlib", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 153 }
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) fig, ax = p...
Problem: I'm using tensorflow 2.10.0. I am building a custom metric to measure the accuracy of one class in my multi-class dataset during training. I am having trouble selecting the class. The targets are one hot (e.g: the class 0 label is [1 0 0 0 0]): I have 10 classes in total, so I need a n*10 tensor as result. No...
result = tf.one_hot(indices=labels, depth=10, on_value=1, off_value=0, axis=-1) return result
{ "problem_id": 671, "library_problem_id": 5, "library": "Tensorflow", "test_case_cnt": 2, "perturbation_type": "Surface", "perturbation_origin_id": 2 }
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): labels = data return tf.one_hot(indices=labels, depth=10, on_value=1, off_value=0, axis=-1) def define_test_input(test_case_id): if test_case_id == 1: labels = [0, 6, 5, 4, 2]...
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. Show x axis ticks on both top and bottom of the figure. # SOLUTION START
plt.plot(x, y) plt.tick_params(top=True)
{ "problem_id": 652, "library_problem_id": 141, "library": "Matplotlib", "test_case_cnt": 1, "perturbation_type": "Semantic", "perturbation_origin_id": 140 }
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 need to do some analysis on a large dataset from a hydrolgeology field work. I am using NumPy. I want to know how I can: 1. multiply e.g. the row-th row of my array by a number (e.g. 5.2). And then 2. calculate the cumulative sum of the numbers in that row. As I mentioned I only want to work on a specific ro...
a[row-1, :] *= multiply_number result = np.cumsum(a[row-1, :])
{ "problem_id": 346, "library_problem_id": 55, "library": "Numpy", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 54 }
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: np.random.seed(42) a = np.random.rand(8, 5) row = 2 const = 5.2 elif test_case_id == 2: np.random.seed(42) ...
Problem: I'm sorry in advance if this is a duplicated question, I looked for this information but still couldn't find it. Is it possible to get a numpy array (or python list) filled with the indexes of the elements in decreasing order? For instance, the array: a = array([4, 1, 0, 8, 5, 2]) The indexes of the elements i...
result = np.argsort(a)[::-1][:len(a)]
{ "problem_id": 381, "library_problem_id": 90, "library": "Numpy", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 90 }
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([4, 1, 0, 8, 5, 2]) elif test_case_id == 2: np.random.seed(42) a = (np.random.rand(100) - 0.5) * 100 return a ...
Problem: I have a list of numpy arrays, and want to check if all the arrays are equal. What is the quickest way of doing this? I am aware of the numpy.array_equal function (https://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.array_equal.html), however as far as I am aware this only applies to two arrays a...
def all_equal(iterator): try: iterator = iter(iterator) first = next(iterator) return all(np.array_equal(first, rest) for rest in iterator) except StopIteration: return True result = all_equal(a)
{ "problem_id": 493, "library_problem_id": 202, "library": "Numpy", "test_case_cnt": 5, "perturbation_type": "Origin", "perturbation_origin_id": 202 }
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]), np.array([1, 2, 3]), np.array([1, 2, 3])] elif test_case_id == 2: a = [np.array([1, 2, 4]), np.array...
Problem: I'm using tensorflow 2.10.0. I would like to generate 114 random integers as a tensor in TensorFlow but I don't which command I should use. In particular, I would like to generate from a uniform random variable which takes values in {2, 3, 4, 5}. I have tried to look among the distributions included in tensorf...
def g(seed_x): tf.random.set_seed(seed_x) return tf.random.uniform(shape=(114,), minval=2, maxval=6, dtype=tf.int32) result = g(seed_x)
{ "problem_id": 708, "library_problem_id": 42, "library": "Tensorflow", "test_case_cnt": 1, "perturbation_type": "Semantic", "perturbation_origin_id": 41 }
import tensorflow as tf import copy def generate_test_case(test_case_id): def generate_ans(data): seed_x = data tf.random.set_seed(seed_x) return tf.random.uniform(shape=(114,), minval=2, maxval=6, dtype=tf.int32) 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 = np.random.rand(10) y = np.random.rand(10) plt.scatter(x, y) # how to turn on minor ticks # SOLUTION START
plt.minorticks_on()
{ "problem_id": 513, "library_problem_id": 2, "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...
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 # move the y axis ticks to the right # SOLUTION START
f = plt.figure() ax = f.add_subplot(111) ax.plot(x, y) ax.yaxis.tick_right()
{ "problem_id": 563, "library_problem_id": 52, "library": "Matplotlib", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 52 }
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) f = plt.fig...
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": 857, "library_problem_id": 40, "library": "Sklearn", "test_case_cnt": 1, "perturbation_type": "Surface", "perturbation_origin_id": 39 }
import numpy as np import copy from sklearn.linear_model import RidgeClassifier 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'm searching for examples of using scipy.optimize.line_search. I do not really understand how this function works with multivariable functions. I wrote a simple example import scipy as sp import scipy.optimize def test_func(x): return (x[0])**2+(x[1])**2 def test_grad(x): return [2*x[0],2*x[1]] sp.o...
result = scipy.optimize.line_search(test_func, test_grad, np.array(starting_point), np.array(direction))[0]
{ "problem_id": 781, "library_problem_id": 70, "library": "Scipy", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 70 }
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: starting_point = [1.8, 1.7] direction = [-1, -1] elif test_case_id == 2: starting_point = [50, 37] d...
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": 135, "library_problem_id": 135, "library": "Pandas", "test_case_cnt": 1, "perturbation_type": "Origin", "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 the following dataframe: text 1 "abc" 2 "def" 3 "ghi" 4 "jkl" How can I merge these rows into a dataframe with a single row like the following one? text 1 "abc, def, ghi, jkl" A: <code> import pandas as pd df = pd.DataFrame({'text': ['abc', 'def', 'ghi', 'jkl']}) </code> result = ... # put...
def g(df): return pd.DataFrame({'text': [', '.join(df['text'].str.strip('"').tolist())]}) result = g(df.copy())
{ "problem_id": 232, "library_problem_id": 232, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 232 }
import pandas as pd import numpy as np import copy def generate_test_case(test_case_id): def generate_ans(data): df = data return pd.DataFrame({"text": [", ".join(df["text"].str.strip('"').tolist())]}) def define_test_input(test_case_id): if test_case_id == 1: df = pd.Data...
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-idf 3) calcul...
from sklearn.metrics.pairwise import cosine_similarity response = tfidf.fit_transform(df['description']).toarray() tf_idf = response cosine_similarity_matrix = np.zeros((len(df), len(df))) for i in range(len(df)): for j in range(len(df)): cosine_similarity_matrix[i, j] = cosine_similarity([tf_idf[i, :]], [...
{ "problem_id": 931, "library_problem_id": 114, "library": "Sklearn", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 114 }
import numpy as np import pandas as pd import copy from sklearn.feature_extraction.text import TfidfVectorizer import sklearn from sklearn.metrics.pairwise import cosine_similarity def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: df = pd.DataFra...
Problem: I have integers 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 np.unpackbits(np.uint8(...
result = (((a[:,None] & (1 << np.arange(m))[::-1])) > 0).astype(int)
{ "problem_id": 426, "library_problem_id": 135, "library": "Numpy", "test_case_cnt": 3, "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(-...
import numpy as np import math import matplotlib import matplotlib.pyplot as plt t = np.linspace(0, 2 * math.pi, 400) a = np.sin(t) b = np.cos(t) c = a + b # Plot a, b, c in the same figure # SOLUTION START
plt.plot(t, a, t, b, t, c)
{ "problem_id": 660, "library_problem_id": 149, "library": "Matplotlib", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 149 }
import numpy as np import math import matplotlib 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): t = np.linspace(0, 2 * math.pi, 400) a = ...
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...
# def solve(a, b): ### BEGIN SOLUTION c = (a[:, -1:] + b[:, :1]) / 2 result = torch.cat((a[:, :-1], c, b[:, 1:]), dim=1) ### END SOLUTION # return result # result = solve(a, b) return result
{ "problem_id": 995, "library_problem_id": 63, "library": "Pytorch", "test_case_cnt": 3, "perturbation_type": "Surface", "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 pandas df with say, 100 rows, 10 columns, (actual data is huge). I also have row_index list which contains, which rows to be considered to take mean. I want to calculate mean on say columns 2,5,6,7 and 8. Can we do it with some function for dataframe object? What I know is do a for loop, get value of ro...
def g(df, row_list, column_list): return df[column_list].iloc[row_list].mean(axis=0) result = g(df.copy(),row_list,column_list)
{ "problem_id": 36, "library_problem_id": 36, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Origin", "perturbation_origin_id": 36 }
import pandas as pd import numpy as np import copy import tokenize, io def generate_test_case(test_case_id): def generate_ans(data): data = data df, row_list, column_list = data return df[column_list].iloc[row_list].mean(axis=0) def define_test_input(test_case_id): if test_cas...
import numpy as np import pandas as pd import matplotlib.pyplot as plt x = np.random.randn(10) y = np.random.randn(10) # in a scatter plot of x, y, make the points have black borders and blue face # SOLUTION START
plt.scatter(x, y, c="blue", edgecolors="black")
{ "problem_id": 545, "library_problem_id": 34, "library": "Matplotlib", "test_case_cnt": 1, "perturbation_type": "Origin", "perturbation_origin_id": 34 }
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.random.randn(10) y = np.random.randn(10) ...
Problem: I have my data in a pandas DataFrame, and it looks like the following: cat val1 val2 val3 val4 A 7 10 0 19 B 10 2 1 14 C 5 15 6 16 I'd like to compute the percentage of the value that each category(cat) has. For example, for val1, A is 7 and the colu...
def g(df): df = df.set_index('cat') res = df.div(df.sum(axis=0), axis=1) return res.reset_index() df = g(df.copy())
{ "problem_id": 116, "library_problem_id": 116, "library": "Pandas", "test_case_cnt": 2, "perturbation_type": "Semantic", "perturbation_origin_id": 115 }
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.set_index("cat") res = df.div(df.sum(axis=0), axis=1) return res.reset_index() def define_test_input(test_case_id): if test_case_id == 1: ...
Problem: I have a 2D array `a` to represent a many-many mapping : 0 3 1 3 3 0 0 0 1 0 0 0 3 0 0 0 What is the quickest way to 'zero' out rows and column entries corresponding to particular indices (e.g. zero_rows = [0, 1], zero_cols = [0, 1] corresponds to the 1st and 2nd row / column) in this a...
a[zero_rows, :] = 0 a[:, zero_cols] = 0
{ "problem_id": 434, "library_problem_id": 143, "library": "Numpy", "test_case_cnt": 1, "perturbation_type": "Semantic", "perturbation_origin_id": 142 }
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([[0, 3, 1, 3], [3, 0, 0, 0], [1, 0, 0, 0], [3, 0, 0, 0]]) zero_rows = [1, 3] zero_cols = [1, 2] retur...
Problem: I have a 2-d numpy array as follows: a = np.array([[1,5,9,13,17], [2,6,10,14,18], [3,7,11,15,19], [4,8,12,16,20]] I want to extract it into patches of 2 by 2 sizes with out repeating the elements. Pay attention that if the shape is indivisible by patch size, we would j...
x = a[:a.shape[0] // patch_size * patch_size, :a.shape[1] // patch_size * patch_size] result = x.reshape(x.shape[0]//patch_size, patch_size, x.shape[1]// patch_size, patch_size).swapaxes(1, 2).transpose(1, 0, 2, 3).reshape(-1, patch_size, patch_size)
{ "problem_id": 390, "library_problem_id": 99, "library": "Numpy", "test_case_cnt": 2, "perturbation_type": "Difficult-Rewrite", "perturbation_origin_id": 94 }
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: a = np.array( [ [1, 5, 9, 13, 17], [2, 6, 10, 14, 18], [3, 7, 11, 15, ...
Problem: I have a raster with a set of unique ID patches/regions which I've converted into a two-dimensional Python numpy array. I would like to calculate pairwise Euclidean distances between all regions to obtain the minimum distance separating the nearest edges of each raster patch. As the array was originally a rast...
import itertools n = example_array.max()+1 indexes = [] for k in range(1, n): tmp = np.nonzero(example_array == k) tmp = np.asarray(tmp).T indexes.append(tmp) result = np.zeros((n-1, n-1)) for i, j in itertools.combinations(range(n-1), 2): d2 = scipy.spatial.di...
{ "problem_id": 751, "library_problem_id": 40, "library": "Scipy", "test_case_cnt": 1, "perturbation_type": "Surface", "perturbation_origin_id": 38 }
import numpy as np import itertools import copy import scipy.spatial.distance def generate_test_case(test_case_id): def define_test_input(test_case_id): if test_case_id == 1: example_array = np.array( [ [0, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0], ...