id int64 0 7.95k | code_block stringlengths 1 52.9k | too_long stringclasses 2
values | marks int64 1 5 | graph_vertex_id float64 1 88 | graph_vertex_class stringclasses 12
values | graph_vertex_subclass stringclasses 70
values | kernel_id float64 25.8k 14.7M ⌀ | sqale_rating float64 1 4 | maintainability_rating stringclasses 4
values | code_smells int64 0 36 | complexity float64 0 15 ⌀ | cognitive_complexity int64 0 33 | bugs int64 0 7 | sqale_index int64 0 125 | ncloc float64 0 101 ⌀ | mlscent_analysis_status stringclasses 3
values | mlscent_smell_count int64 0 31 | mlscent_unique_smell_count int64 0 12 | mlscent_findings_json stringlengths 2 7.76k | mlscent_ml_rating stringclasses 5
values | mlscent_ml_rating_basis stringclasses 52
values | mlscent_ml_findings_json stringclasses 50
values | mlscent_ignored_findings_json stringclasses 199
values | context_line_count int64 0 33 | combined_rating stringclasses 5
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5,894 | from sklearn.preprocessing import OneHotEncoder
# transforms given dataset to OHE representation
def one_hot(dataset):
ohe = OneHotEncoder(sparse=True, dtype=np.float32, handle_unknown='ignore')
return ohe.fit_transform(dataset.values) | Yes | 5 | 20 | Data_Transform | categorify | 3,402,586 | 1 | A | 0 | 1 | 0 | 0 | 0 | 4 | ok | 6 | 6 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Pipeline Checker", "fix": "Use Pipelines for all scikit-learn estimators.", "benefits": "Prevents data leakage and ensures correct model evaluation.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross V... | D | Cross Validation Checker=low, Data Leakage Checker=high, Pipeline Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Data Leakage Checker", "severity": "high"}, {"type": "Pipeline Checker", "severity": "low"}] | ["Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 8 | D |
5,895 | new_train, new_test = transform_dataset(
train[col4train], test[col4train],
one_hot)
print(new_train.shape, new_test.shape) | No | 3 | 12 | Data_Transform | create_dataframe | 3,402,586 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 3 | 3 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Unit Testing... | A | no applicable ML-specific findings | [] | ["Column Selection Checker", "Exception Handling Checker", "Unit Testing Checker"] | 8 | A |
5,896 | from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
def extract_col_interaction(dataset, col1, col2, tfidf = True):
data = dataset.groupby([col1])[col2].agg(lambda x: " ".join(list([str(y) for y in x])))
if tfidf:
vectorizer = Tfid... | Yes | 3 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 0 | null |
5,897 | new_train, new_test = transform_dataset(
train[col4train], test[col4train],
get_col_interactions_svd
)
print(new_train.shape, new_test.shape)
new_train.head(5) | Yes | 3 | 41 | Debug | show_table | 3,402,586 | 1 | A | 0 | 0 | 0 | 0 | 0 | 6 | ok | 5 | 5 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Valida... | B | Cross Validation Checker=low, No random seed setting detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "No random seed setting detected", "severity": "low"}] | ["Column Selection Checker", "Exception Handling Checker", "Unit Testing Checker"] | 8 | B |
5,898 | def get_freq_encoding(dataset):
new_dataset = pd.DataFrame()
for c in dataset.columns:
data = dataset.groupby([c]).size().reset_index()
new_dataset[c+"_freq"] = dataset[[c]].merge(data, on = c, how = "left")[0]
return new_dataset | No | 3 | 12 | Data_Transform | create_dataframe | 3,402,586 | 1 | A | 0 | 2 | 1 | 0 | 0 | 6 | ok | 1 | 1 | [{"detector": "general_ml", "framework": "General ML", "name": "Missing docstring for function: get_freq_encoding. Consider adding documentation for parameters and return values.", "fix": "Not specified", "benefits": "Not specified", "location": "Line 9"}] | A | no applicable ML-specific findings | [] | ["Missing function docstring"] | 8 | A |
5,899 | new_train, new_test = transform_dataset(
train[col4train], test[col4train],
get_freq_encoding
)
print(new_train.shape, new_test.shape)
new_train.head(5) | Yes | 3 | 41 | Debug | show_table | 3,402,586 | 1 | A | 0 | 0 | 0 | 0 | 0 | 6 | ok | 5 | 5 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Valida... | B | Cross Validation Checker=low, No random seed setting detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "No random seed setting detected", "severity": "low"}] | ["Column Selection Checker", "Exception Handling Checker", "Unit Testing Checker"] | 8 | B |
5,900 | new_train1, new_test1 = transform_dataset(
train[col4train], test[col4train], get_freq_encoding
)
new_train2, new_test2 = transform_dataset(
train[col4train], test[col4train], get_col_interactions_svd
)
new_train3, new_test3 = transform_dataset(
train[col4train], test[col4train],
assign_rnd_integer, {"... | Yes | 4 | 11 | Data_Transform | concatenate | 3,402,586 | 1 | A | 0 | 0 | 0 | 0 | 0 | 13 | ok | 7 | 5 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Unit Testing... | B | No random seed setting detected=low | [{"type": "No random seed setting detected", "severity": "low"}] | ["Column Selection Checker", "Exception Handling Checker", "No error handling detected in data processing. Consider adding try-except blocks or validation checks for robustness.", "Unit Testing Checker"] | 8 | B |
5,901 | model = get_model()
model.fit(new_train.values, y)
predictions = model.predict_proba(new_test)[:,1]
submit = pd.DataFrame()
submit["Id"] = test["id"]
submit["ACTION"] = predictions
submit.to_csv("submission.csv", index = False) | Yes | 4 | 25 | Data_Export | save_to_csv | 3,402,586 | 1 | A | 0 | 0 | 0 | 0 | 0 | 7 | ok | 10 | 9 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Valida... | B | Cross Validation Checker=low, Cross-validation not detected=low, No random seed setting detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Cross-validation not detected", "severity": "low"}, {"type": "No random seed setting detected", "severity": "low"}] | ["Column Selection Checker", "Dependent Threshold Checker", "Exception Handling Checker", "No error handling detected in data processing. Consider adding try-except blocks or validation checks for robustness.", "Unit Testing Checker", "Verbose Mode Checker"] | 8 | B |
5,902 | # Assuring you have the most recent CatBoost release
!pip install catboost -U | No | 5 | 87 | Environment | install_modules | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,903 | # Getting useful tabular processing and generator functions
!git clone https://github.com/lmassaron/deep_learning_for_tabular_data.git | No | 2 | 23 | Environment | set_options | 6,220,615 | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 23 | null |
5,904 | # Importing core libraries
import numpy as np
import pandas as pd
from time import time
import pprint
import joblib
# Suppressing warnings because of skopt verbosity
import warnings
warnings.filterwarnings("ignore")
# Classifiers
from catboost import CatBoostClassifier, Pool
# Model selection
from sklearn.model_sele... | No | 5 | 23 | Environment | set_options | 6,220,615 | 1 | A | 0 | 0 | 0 | 0 | 0 | 11 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Threshold Checker", "fix": "Use threshold-independent metrics alongside threshold-dependent ones.", "benefits": "Provides a comprehensive evaluation of model performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker"] | 23 | A |
5,905 | # Loading data directly from CatBoost
from catboost.datasets import amazon
X, Xt = amazon()
y = X["ACTION"].apply(lambda x: 1 if x == 1 else 0).values
X.drop(["ACTION"], axis=1, inplace=True) | Yes | 4 | 21 | Data_Transform | prepare_x_and_y | 6,220,615 | 1 | A | 0 | 1 | 1 | 0 | 0 | 4 | ok | 3 | 3 | [{"detector": "framework_specific", "framework": "Pandas", "name": "InPlace Checker", "fix": "Assign operations to a new DataFrame variable.", "benefits": "Prevents data loss and improves code clarity.", "location": "Line 30"}, {"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker"... | A | no applicable ML-specific findings | [] | ["Column Selection Checker", "Dependent Threshold Checker", "InPlace Checker"] | 23 | A |
5,906 | # Transforming all the labels of all variables
from sklearn.preprocessing import LabelEncoder
label_encoders = [LabelEncoder() for _ in range(X.shape[1])]
for col, column in enumerate(X.columns):
label_encoders[col].fit(X[column].append(Xt[column]))
X[column] = label_encoders[col].transform(X[column])
Xt[... | Yes | 5 | 20 | Data_Transform | categorify | 6,220,615 | 1 | A | 0 | 1 | 1 | 0 | 0 | 6 | ok | 12 | 10 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Pipeline Che... | D | Cross Validation Checker=low, Data Leakage Checker=high, No random seed setting detected=low, Pipeline Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Data Leakage Checker", "severity": "high"}, {"type": "No random seed setting detected", "severity": "low"}, {"type": "Pipeline Checker", "severity": "low"}] | ["Column Selection Checker", "Dependent Threshold Checker", "Exception Handling Checker", "No error handling detected in data processing. Consider adding try-except blocks or validation checks for robustness.", "Unit Testing Checker", "Verbose Mode Checker"] | 23 | D |
5,907 | # Enconding frequencies instead of labels (so we have some numeric variables)
def frequency_encoding(column, df, df_test=None):
frequencies = df[column].value_counts().reset_index()
df_values = df[[column]].merge(frequencies, how='left',
left_on=column, right_on='index').ilo... | No | 5 | 20 | Data_Transform | categorify | null | 1 | A | 0 | 3 | 3 | 0 | 0 | 14 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,908 | # Pointing out which variables are categorical and which are numeric
categorical_variables = [col for col in X.columns if '_counts' not in col]
numeric_variables = [col for col in X.columns if '_counts' in col] | No | 3 | 77 | Other | define_variables | 6,220,615 | 1 | A | 0 | 2 | 0 | 0 | 0 | 2 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Threshold Checker", "fix": "Use threshold-independent metrics alongside threshold-dependent ones.", "benefits": "Provides a comprehensive evaluation of model performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker"] | 23 | A |
5,909 | X.head() | No | 5 | 41 | Debug | show_table | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,910 | Xt.head() | No | 5 | 41 | Debug | show_table | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,911 | # Counting unique values of categorical variables
X[categorical_variables].nunique() | No | 5 | 54 | EDA | count_unique_values | 6,220,615 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 2 | 2 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Th... | A | no applicable ML-specific findings | [] | ["Column Selection Checker", "Dependent Threshold Checker"] | 23 | A |
5,912 | # Describing numeric variables
X[numeric_variables].describe() | No | 5 | 40 | Debug | show_table_attributes | 6,220,615 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 2 | 2 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Th... | A | no applicable ML-specific findings | [] | ["Column Selection Checker", "Dependent Threshold Checker"] | 23 | A |
5,913 | # Initializing a CatBoostClassifier with best parameters
best_params = {'bagging_temperature': 0.6,
'border_count': 200,
'depth': 8,
'iterations': 350,
'l2_leaf_reg': 30,
'learning_rate': 0.30,
'random_strength': 0.01,
... | No | 4 | 4 | Model_Train | choose_model_class | 6,220,615 | 1 | A | 0 | 0 | 0 | 0 | 0 | 14 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Threshold Checker", "fix": "Use threshold-independent metrics alongside threshold-dependent ones.", "benefits": "Provides a comprehensive evaluation of model performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker"] | 23 | A |
5,914 | # CV interations
roc_auc = list()
average_precision = list()
oof = np.zeros(len(X))
best_iteration = list()
for train_idx, test_idx in skf.split(X, y):
X_train, y_train = X.iloc[train_idx, :], y[train_idx]
X_test, y_test = X.iloc[test_idx, :], y[test_idx]
train = Pool(data=X_train,
labe... | Yes | 2 | 7 | Model_Train | train_model | 6,220,615 | 1 | A | 4 | 1 | 1 | 0 | 20 | 26 | ok | 12 | 11 | [{"detector": "framework_specific", "framework": "NumPy", "name": "Array Creation Efficiency", "fix": "Specify dtype when creating arrays.", "benefits": "Improves memory efficiency and avoids unnecessary conversions.", "location": "Line 28"}, {"detector": "framework_specific", "framework": "Pandas", "name": "Column Sel... | B | Cross Validation Checker=low, Cross-validation not detected=low, No random seed setting detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Cross-validation not detected", "severity": "low"}, {"type": "No random seed setting detected", "severity": "low"}] | ["Array Creation Efficiency", "Column Selection Checker", "Dependent Threshold Checker", "Exception Handling Checker", "Memory Release Checker", "No error handling detected in data processing. Consider adding try-except blocks or validation checks for robustness.", "Unit Testing Checker", "Verbose Mode Checker"] | 23 | B |
5,915 | # Using catboost on all the data for predictions
best_params = {'bagging_temperature': 0.6,
'border_count': 200,
'depth': 8,
'iterations': int(np.median(best_iteration) * 1.3),
'l2_leaf_reg': 30,
'learning_rate': 0.30,
'random_st... | Yes | 3 | 7 | Model_Train | train_model | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,916 | import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam, Nadam
from tensorflow.keras.layers import Input, Embedding, Reshape, GlobalAveragePooling1D
from tensorflow.keras.layer... | No | 5 | 22 | Environment | import_modules | 6,220,615 | 1 | A | 0 | 0 | 0 | 0 | 0 | 17 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Threshold Checker", "fix": "Use threshold-independent metrics alongside threshold-dependent ones.", "benefits": "Provides a comprehensive evaluation of model performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker"] | 23 | A |
5,917 | # Registering custom activations suitable for tabular problems
from tensorflow.keras.utils import get_custom_objects
from tensorflow.keras.layers import Activation, LeakyReLU
from deep_learning_for_tabular_data.tabular import gelu, Mish, mish
# Add gelu so we can use it as a string
get_custom_objects().update({'gelu'... | Yes | 5 | 22 | Environment | import_modules | 6,220,615 | 1 | A | 0 | 0 | 0 | 0 | 0 | 6 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Threshold Checker", "fix": "Use threshold-independent metrics alongside threshold-dependent ones.", "benefits": "Provides a comprehensive evaluation of model performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker"] | 23 | A |
5,918 | # Parametric architecture
def tabular_dnn(numeric_variables, categorical_variables, categorical_counts,
feature_selection_dropout=0.2, categorical_dropout=0.1,
first_dense = 256, second_dense = 256, dense_dropout = 0.2,
activation_type=gelu):
numerical_inputs =... | No | 4 | 4 | Model_Train | choose_model_class | 6,220,615 | 1 | A | 0 | 2 | 1 | 0 | 0 | 26 | ok | 4 | 4 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Th... | B | Randomness Control Checker=low | [{"type": "Randomness Control Checker", "severity": "low"}] | ["Column Selection Checker", "Dependent Threshold Checker", "Missing function docstring"] | 23 | B |
5,919 | # Useful functions
from tensorflow.keras.metrics import AUC
def mAP(y_true, y_pred):
return tf.py_func(average_precision_score, (y_true, y_pred), tf.double)
def compile_model(model, loss, metrics, optimizer):
model.compile(loss=loss, metrics=metrics, optimizer=optimizer)
return model
def plot_keras_hist... | Yes | 5 | 35 | Visualization | learning_history | null | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 0 | null |
5,920 | # Global training settings
SEED = 42
FOLDS = 5
BATCH_SIZE = 512 | No | 5 | 77 | Other | define_variables | 6,220,615 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 3 | 2 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Threshold Checker", "fix": "Use threshold-independent metrics alongside threshold-dependent ones.", "benefits": "Provides a comprehensive evaluation of model performance.", "location": ""}, {"detector": "general_ml", "framework": "Genera... | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker", "Magic number"] | 23 | A |
5,921 | from deep_learning_for_tabular_data.tabular import TabularTransformer, DataGenerator
# Setting the CV strategy
skf = StratifiedKFold(n_splits=FOLDS,
shuffle=True,
random_state=SEED)
# CV Iteration
roc_auc = list()
average_precision = list()
oof = np.zeros(len(X))
best_ite... | Yes | 2 | 48 | Model_Evaluation | predict_on_test | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,922 | # We train on all the examples, using a rule of thumb for the number of iterations
tb = TabularTransformer(numeric = numeric_variables,
ordinal = [],
lowcat = [],
highcat = categorical_variables)
tb.fit(X)
sizes = tb.shape(X)
categorical_levels ... | Yes | 2 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,923 | # Predicting and submission
preds = model.predict(tb.transform(Xt[X.columns]),
verbose=1,
batch_size=1024).flatten()
submission = pd.DataFrame(Xt.id)
submission['Action'] = preds
submission.to_csv("tabular_dnn_submission.csv", index=False)
tabular_dnn_submission = submissio... | Yes | 5 | 25 | Data_Export | save_to_csv | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,924 | from scipy.stats import rankdata
# We use normalized ranks because probabilities emissions from the two models may differ
dnn_rank = rankdata(tabular_dnn_submission.Action, method='dense') / len(Xt)
cat_rank = rankdata(cat_boost_submission.Action, method='dense') / len(Xt)
submission = pd.DataFrame(Xt.id)
submission[... | Yes | 5 | 25 | Data_Export | save_to_csv | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,925 | import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings("ignore") | No | 5 | 23 | Environment | set_options | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 6 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 0 | A |
5,926 | data = pd.read_csv('../input/amazon-employee-access-challenge/train.csv')
print(data.shape)
data.head() | Yes | 4 | 45 | Data_Extraction | load_from_csv | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 1 | 1 | [{"detector": "general_ml", "framework": "General ML", "name": "Hardcoded file path detected: ../input/amazon-employee-access-challenge/train.csv. Consider using configuration files or environment variables.", "fix": "Not specified", "benefits": "Not specified", "location": "Line 13"}] | A | no applicable ML-specific findings | [] | ["Hardcoded file path"] | 12 | A |
5,927 | data_explore = data.copy() | No | 4 | 12 | Data_Transform | create_dataframe | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,928 | data_explore.info() | No | 5 | 40 | Debug | show_table_attributes | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,929 | sns.countplot(x='ACTION', data=data_explore) | No | 5 | 33 | Visualization | distribution | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,930 | data_explore_role_dept = data_explore[['ROLE_DEPTNAME', "ACTION"]].groupby(by='ROLE_DEPTNAME').count()
data_explore_role_dept.sort_values('ACTION', ascending=False).head(n=15).transpose()' | No | 2 | 40 | Debug | show_table_attributes | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,931 | data_explore_role_codes = data_explore[['ROLE_CODE', "ACTION"]].groupby(by='ROLE_CODE').count()
data_explore_role_codes.sort_values('ACTION', ascending=False).head(n=15).transpose()' | Yes | 3 | 12 | Data_Transform | create_dataframe | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,932 | data_explore_role_family = data_explore[['ROLE_FAMILY', "ACTION"]].groupby(by='ROLE_FAMILY').count()
data_explore_role_family.sort_values('ACTION', ascending=False).head(n=15).transpose()' | Yes | 3 | 12 | Data_Transform | create_dataframe | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,933 | plt.figure(figsize=(12, 7))
corr_matrix = data_explore.corr()
sns.heatmap(corr_matrix, mask=np.zeros_like(corr_matrix, dtype=np.bool), square=True, annot=True, cbar=False)
plt.tight_layout() | No | 5 | 80 | Visualization | heatmap | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,934 | corr_matrix['ACTION'].sort_values(ascending=False) | No | 2 | 40 | Debug | show_table_attributes | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Column Selection Checker"] | 12 | A |
5,935 | from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer | No | 5 | 22 | Environment | import_modules | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,936 | X = data.drop(columns=['ACTION'], axis=1).copy()
y = data['ACTION'].copy()
X.shape, y.shape | No | 3 | 21 | Data_Transform | prepare_x_and_y | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Column Selection Checker"] | 12 | A |
5,937 | from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(X, y):
strat_train_set = data.iloc[train_index]
strat_test_set = data.iloc[test_index]
X_train = strat_train_set.drop('ACTION', axis... | Yes | 4 | 13 | Data_Transform | split | 12,295,627 | 1 | A | 0 | 1 | 1 | 0 | 0 | 10 | ok | 3 | 3 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Valida... | B | Cross Validation Checker=low, Cross-validation not detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Cross-validation not detected", "severity": "low"}] | ["Column Selection Checker"] | 12 | B |
5,938 | from sklearn.model_selection import KFold, cross_val_score
kf = KFold(n_splits=5, shuffle=True, random_state=42) | Yes | 5 | 84 | Other | not_enough_vertices | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,939 | from sklearn.metrics import matthews_corrcoef, make_scorer, roc_auc_score, roc_curve
Matthew = make_scorer(matthews_corrcoef)
results = []
def plot_custom_roc_curve(clf_name, y_true, y_scores):
auc_score = np.round(roc_auc_score(y_true, y_scores), 3)
fpr, tpr, thresholds = roc_curve(y_true, y_scores)
plt.... | Yes | 5 | 84 | Other | not_enough_vertices | null | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 0 | null |
5,940 | def plot_feature_importance(feature_columns, importance_values, top_n_features=10):
feature_imp = [ col for col in zip(feature_columns, importance_values)]
feature_imp.sort(key=lambda x:x[1], reverse=True)
if top_n_features:
imp = pd.DataFrame(feature_imp[0:top_n_features], columns=['feature', ... | No | 5 | 79 | Visualization | model_coefficients | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,941 | from sklearn.linear_model import LogisticRegression
logistic_reg = LogisticRegression(solver='liblinear', C=1, penalty='l2', max_iter=1000, random_state=42, n_jobs=-1)
logistic_reg.fit(X_train_transformed, y_train) | Yes | 5 | 7 | Model_Train | train_model | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 5 | 5 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Scaler Missing Checker", "fix": "Apply scaling before scaling-sensitive operations.", "benefits": "Improves model performance and accuracy.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Validation... | C | Cross Validation Checker=low, Scaler Missing Checker=medium | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Scaler Missing Checker", "severity": "medium"}] | ["Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 12 | C |
5,942 | plot_feature_importance(feature_columns, logistic_reg.coef_[0], top_n_features=15) | No | 5 | 79 | Visualization | model_coefficients | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,943 | performance_measures(logistic_reg) | No | 4 | 35 | Visualization | learning_history | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,944 | from sklearn.ensemble import RandomForestClassifier
forest_clf = RandomForestClassifier(n_estimators=300, max_depth=16, random_state=42,n_jobs=-1)
forest_clf.fit(X_train_transformed, y_train) | Yes | 5 | 7 | Model_Train | train_model | 12,295,627 | 2 | B | 1 | 0 | 0 | 0 | 5 | 3 | ok | 5 | 4 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Validation Checker", "fix": "Implement cross-validation techniques for robust model evaluation.", "benefits": "Enhances model performance and reduces overfitting.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLear... | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | ["Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 12 | B |
5,945 | plot_feature_importance(feature_columns, forest_clf.feature_importances_, top_n_features=15) | No | 5 | 79 | Visualization | model_coefficients | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,946 | performance_measures(forest_clf) | No | 4 | 35 | Visualization | learning_history | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,947 | from xgboost import XGBClassifier
xgb_clf = XGBClassifier(n_estimators=300, max_depth=16, learning_rate=0.1, random_state=42, n_jobs=-1)
xgb_clf.fit(X_train_transformed, y_train) | Yes | 5 | 7 | Model_Train | train_model | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 4 | 4 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Validation Checker", "fix": "Implement cross-validation techniques for robust model evaluation.", "benefits": "Enhances model performance and reduces overfitting.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLear... | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | ["Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 12 | B |
5,948 | plot_feature_importance(feature_columns, xgb_clf.feature_importances_, top_n_features=15) | No | 5 | 79 | Visualization | model_coefficients | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,949 | performance_measures(xgb_clf) | No | 4 | 35 | Visualization | learning_history | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,950 | from catboost import CatBoostClassifier
catboost_clf = CatBoostClassifier(loss_function='Logloss', iterations=500, depth=6, l2_leaf_reg=1,
cat_features=list(range(X_cb_train_transformed.shape[1])),
eval_metric='AUC', random_state=42, verbose=0)
catb... | Yes | 5 | 7 | Model_Train | train_model | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 5 | ok | 4 | 4 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Validation Checker", "fix": "Implement cross-validation techniques for robust model evaluation.", "benefits": "Enhances model performance and reduces overfitting.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLear... | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | ["Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 12 | B |
5,951 | performance_measures(catboost_clf, X_tr=X_cb_train_transformed, X_ts=X_cb_test_transformed) | No | 5 | 53 | Other | something_strange | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,952 | plot_feature_importance(feature_columns, catboost_clf.feature_importances_, top_n_features=15) | No | 5 | 79 | Visualization | model_coefficients | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,953 | from sklearn.ensemble import VotingClassifier
voting_reg = VotingClassifier(estimators=named_estimators, voting='soft', n_jobs=-1)
voting_reg.fit(X_train, y_train) | Yes | 5 | 7 | Model_Train | train_model | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 4 | 4 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Validation Checker", "fix": "Implement cross-validation techniques for robust model evaluation.", "benefits": "Enhances model performance and reduces overfitting.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLear... | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | ["Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 12 | B |
5,954 | performance_measures(voting_reg, X_tr=X_train, X_ts=X_test) | No | 4 | 35 | Visualization | learning_history | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,955 | result_df = pd.DataFrame(results, columns=['Model', 'CV Train AUC Score', 'CV Test AUC Score', 'CV Train MCC', 'CV Test MCC'])
result_df | No | 5 | 12 | Data_Transform | create_dataframe | 12,295,627 | 1 | A | 0 | 0 | 0 | 1 | 0 | 2 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 12 | A |
5,956 | plt.figure(figsize=(8, 5))
plot_custom_roc_curve('Logistic Regression', y_test, logistic_reg.decision_function(X_test_transformed))
plot_custom_roc_curve('Random Forest', y_test, forest_clf.predict_proba(X_test_transformed)[:,1])
plot_custom_roc_curve('XGBoost', y_test, xgb_clf.predict_proba(X_test_transformed)[:,1])
p... | No | 5 | 53 | Other | something_strange | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 7 | ok | 7 | 4 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Unit Testing Checker", "fix": "Write unit tests for data processing and model components.", "benefits": "Ensures code reliability and prevents bugs.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Excepti... | B | No random seed setting detected=low | [{"type": "No random seed setting detected", "severity": "low"}] | ["Exception Handling Checker", "No error handling detected in data processing. Consider adding try-except blocks or validation checks for robustness.", "Unit Testing Checker"] | 12 | B |
5,957 | final_model = Pipeline([('pre_process', cat_boost_pre_process),
('catboost', catboost_clf)])
final_model.fit(X_train, y_train) | Yes | 5 | 7 | Model_Train | train_model | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 4 | 4 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Validation Checker", "fix": "Implement cross-validation techniques for robust model evaluation.", "benefits": "Enhances model performance and reduces overfitting.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLear... | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | ["Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 12 | B |
5,958 | test_data = pd.read_csv('../input/amazon-employee-access-challenge/test.csv')
test_data.head() | No | 4 | 45 | Data_Extraction | load_from_csv | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 1 | 1 | [{"detector": "general_ml", "framework": "General ML", "name": "Hardcoded file path detected: ../input/amazon-employee-access-challenge/test.csv. Consider using configuration files or environment variables.", "fix": "Not specified", "benefits": "Not specified", "location": "Line 13"}] | A | no applicable ML-specific findings | [] | ["Hardcoded file path"] | 12 | A |
5,959 | output = pd.DataFrame(test_data['id'])
test_data = test_data.drop('id', axis=1) | Yes | 4 | 12 | Data_Transform | create_dataframe | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Column Selection Checker"] | 12 | A |
5,960 | predictions = final_model.predict(test_data) | No | 5 | 48 | Model_Evaluation | predict_on_test | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,961 | output['ACTION'] = predictions.copy() | No | 3 | 12 | Data_Transform | create_dataframe | 12,295,627 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 3 | 3 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Unit Testing... | A | no applicable ML-specific findings | [] | ["Column Selection Checker", "Exception Handling Checker", "Unit Testing Checker"] | 12 | A |
5,962 | output.to_csv("./submission.csv", index=False) | No | 5 | 25 | Data_Export | save_to_csv | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,963 | MAX_WEIGHT = 50.0
toys = {
"horse": { "sample": lambda: max(0, np.random.normal(5,2,1)[0]), "sample_type": "normal(5,2)" },
"ball": { "sample": lambda: max(0, 1 + np.random.normal(1,0.3,1)[0]), "sample_type": "normal(1,0.3)" },
"bike": { "sample": lambda: max(0, np.random.normal(20,10,1)[0]), "sample_... | Yes | 3 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,964 | X_test['Store'].nunique(), X_test['Dept'].nunique(), X_test['Date'].nunique() | No | 5 | 54 | EDA | count_unique_values | 6,457,885 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Column Selection Checker"] | 17 | A |
5,965 | X_test.shape, X_train.shape | No | 5 | 58 | Debug | show_shape | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,966 | X_train['Year'] = pd.DatetimeIndex(X_train['Date']).year
X_train['Month'] = pd.DatetimeIndex(X_train['Date']).month
X_train['woy'] = pd.DatetimeIndex(X_train['Date']).weekofyear
X_train['quarter'] = pd.DatetimeIndex(X_train['Date']).quarter
X_test['Year'] = pd.DatetimeIndex(X_test['Date']).year
X_test['Month'] = pd.Da... | No | 5 | 8 | Data_Transform | feature_engineering | 6,457,885 | 1 | A | 0 | 0 | 0 | 0 | 0 | 8 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Column Selection Checker"] | 17 | A |
5,967 | X_all['Store'].unique() | No | 5 | 57 | Debug | show_unique_values | 6,457,885 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Column Selection Checker"] | 17 | A |
5,970 | cols_num = [col for col in X_train.columns if X_train[col].dtype in [float, int]]
ncols = len(cols_num) // 4
fig, axes = plt.subplots(ncols=ncols, nrows=5, figsize=(30,16))
i = 1
for j, col in enumerate(cols_num):
sns.distplot(X_train[col], bins=10, ax=axes[i-1][j % ncols])
if j % ncols == (ncols - 1):
... | No | 5 | 33 | Visualization | distribution | 6,457,885 | 1 | A | 0 | 3 | 3 | 0 | 0 | 9 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Column Selection Checker"] | 17 | A |
5,972 | X_train_tf['Date2'] = pd.to_datetime(X_train_tf['Date'], utc = True)
X_test['Date2'] = pd.to_datetime(X_test['Date'], utc = True)
X_train_tf['Weekly_Sales_tf_Lag_52_Weeks'] = X_train_tf.merge(X_all,
left_on=['Store', 'Dept', 'Date2'],
... | No | 3 | 32 | Data_Transform | merge | 6,457,885 | 1 | A | 0 | 0 | 0 | 0 | 0 | 13 | ok | 8 | 7 | [{"detector": "framework_specific", "framework": "Pandas", "name": "InPlace Checker", "fix": "Assign operations to a new DataFrame variable.", "benefits": "Prevents data loss and improves code clarity.", "location": "Line 30"}, {"detector": "framework_specific", "framework": "Pandas", "name": "InPlace Checker", "fix": ... | B | Cross Validation Checker=low, Cross-validation not detected=low, No random seed setting detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Cross-validation not detected", "severity": "low"}, {"type": "No random seed setting detected", "severity": "low"}] | ["Column Selection Checker", "Data Augmentation Checker", "InPlace Checker", "Logging Checker"] | 17 | B |
5,973 | b"fig, axes = plt.subplots(ncols=5, figsize=(20,8))\nsns.distplot(X_train['Weekly_Sales'], bins=10, ax=axes[0]).set_title('Weekly Sales')\nsns.distplot(X_train['Weekly_Sales_Log'], bins=10, ax=axes[1]).set_title('Log(1+Weekly Sales)')\nsns.distplot(X_train_tf['Weekly_Sales_Log'], bins=10, ax=axes[2]).set_title('Log(1+W... | No | 5 | 33 | Visualization | distribution | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,974 | print(X_train_tf.shape)
X_train_tf.head() | No | 4 | 41 | Debug | show_table | 6,457,885 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 3 | 3 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Validation Checker", "fix": "Implement cross-validation techniques for robust model evaluation.", "benefits": "Enhances model performance and reduces overfitting.", "location": ""}, {"detector": "framework_specific", "framework": "TensorFlow... | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | ["Data Augmentation Checker", "Logging Checker"] | 17 | B |
5,975 | b"print(X_train_tf['Type'].value_counts(), '\\n', X_test['Type'].value_counts())\nprint(X_train_tf['IsHoliday'].value_counts(), '\\n', X_test['IsHoliday'].value_counts())" | No | 5 | 72 | EDA | count_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,976 | lbl_encoder = LabelEncoder()
X_train_tf['IsHoliday'] = X_train_tf['IsHoliday'].replace(True, 5).replace(False, 1).values # go off the custom weighted-mae function
X_train_tf['Type'] = lbl_encoder.fit_transform(X_train_tf['Type'])
X_test['IsHoliday'] = X_test['IsHoliday'].replace(True, 5).replace(False, 1).values # go... | No | 5 | 20 | Data_Transform | categorify | 6,457,885 | 1 | A | 0 | 0 | 0 | 0 | 0 | 5 | ok | 13 | 12 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Pipeline Che... | D | Cross Validation Checker=low, Cross-validation not detected=low, Data Leakage Checker=high, No random seed setting detected=low, Pipeline Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Cross-validation not detected", "severity": "low"}, {"type": "Data Leakage Checker", "severity": "high"}, {"type": "No random seed setting detected", "severity": "low"}, {"type": "Pipeline Checker", "severity": "low"}] | ["Column Selection Checker", "Data Augmentation Checker", "Exception Handling Checker", "Logging Checker", "No error handling detected in data processing. Consider adding try-except blocks or validation checks for robustness.", "Unit Testing Checker", "Verbose Mode Checker"] | 17 | D |
5,977 | X_train_tf.head() | No | 5 | 41 | Debug | show_table | 6,457,885 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 3 | 3 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Validation Checker", "fix": "Implement cross-validation techniques for robust model evaluation.", "benefits": "Enhances model performance and reduces overfitting.", "location": ""}, {"detector": "framework_specific", "framework": "TensorFlow... | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | ["Data Augmentation Checker", "Logging Checker"] | 17 | B |
5,978 | def weighted_mae_custom(y_true, y_pred):
'''
Custom weighting function as specified in the evaluation section.
'''
weights = X_train_tf['IsHoliday']
sample_weights = pd.Series(weights.loc[y_true.index.values].values.reshape(-1)).dropna()
return (1.0 / np.sum(sample_weights)) * np.sum(sample_weig... | No | 5 | 84 | Other | not_enough_vertices | 6,457,885 | 1 | A | 0 | 1 | 0 | 0 | 0 | 5 | ok | 7 | 4 | [{"detector": "framework_specific", "framework": "NumPy", "name": "Missing Axis Specification", "fix": "Specify axis in array operations.", "benefits": "Improves performance and avoids unexpected behaviour.", "location": "Line 24"}, {"detector": "framework_specific", "framework": "NumPy", "name": "Missing Axis Specific... | C | Missing Axis Specification=medium | [{"type": "Missing Axis Specification", "severity": "medium"}] | ["Column Selection Checker", "DataFrame Conversion Checker", "Unit Testing Checker"] | 17 | C |
5,979 | X_train_tf.dtypes | No | 5 | 70 | Debug | show_data_types | 6,457,885 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 17 | A |
5,984 | X_test.drop('Date', axis=1).isna().sum() | No | 5 | 39 | EDA | count_missing_values | 6,457,885 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 17 | A |
5,985 | ## QuantileTransformer ##
X_test['Weekly_Sales'] = qt.inverse_transform(best_models[2].predict(X_test.drop('Date', axis=1)).reshape(-1, 1)) + 1
X_test.head() | No | 3 | 8 | Data_Transform | feature_engineering | 6,457,885 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 8 | 6 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Unit Testing... | B | No random seed setting detected=low | [{"type": "No random seed setting detected", "severity": "low"}] | ["Column Selection Checker", "Exception Handling Checker", "Memory Release Checker", "No error handling detected in data processing. Consider adding try-except blocks or validation checks for robustness.", "Unit Testing Checker"] | 17 | B |
5,986 | import pandas as pd
import os
import numpy as np
from sklearn.preprocessing import LabelEncoder
print(os.listdir('../input'))
file = ['train_users.csv', 'age_gender_bkts.csv', 'sessions.csv', 'countries.csv', 'test_users.csv']
data = {}
for f in file:
data[f.replace('.csv','')]=pd.read_csv('../input/'+f)
train... | No | 3 | 22 | Environment | import_modules | 26,455 | 1 | A | 1 | 1 | 1 | 0 | 5 | 16 | ok | 4 | 3 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Valida... | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | ["Column Selection Checker", "Hardcoded file path"] | 3 | B |
5,987 | # temp = pd.DataFrame(train.apply(lambda row: isinstance(row['date_first_booking'], float), axis = 1))
# temp['destination'] = (target == 'NDF')
# temp['comparison'] = temp.apply(lambda x: x[0] != x['destination'], axis = 1)
# temp.apply(sum) | No | 4 | 8 | Data_Transform | feature_engineering | 26,455 | 1 | A | 1 | 0 | 0 | 0 | 5 | 0 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
5,988 | # Imports
# pandas
import pandas as pd
from pandas import Series,DataFrame
# numpy, matplotlib, seaborn
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# machine learning
from sklearn.linear_model import LogisticRegression, RandomizedLasso
from sklearn.ensemble import Grad... | No | 5 | 23 | Environment | set_options | 27,393 | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 0 | null |
5,989 | plot_params = {
"font.size":14.0,
"figure.figsize": (6, 4),
"axes.labelsize": "large",
"figure.autolayout": True,
"patch.edgecolor":"white",
"axes.facecolor": "#f0f0f0",
"patch.edgecolor": "#f0f0f0",
"figure.facecolor": "#f0f0f0",
"grid.linestyle": "-",
"grid.linewidth": 1.0,
"grid.color"... | No | 5 | 23 | Environment | set_options | 27,393 | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,990 | # get airbnb & test csv files as a DataFrame
airbnb_df = pd.read_csv('../input/train_users.csv')
test_df = pd.read_csv('../input/test_users.csv')
# preview the data
airbnb_df.head() | No | 4 | 45 | Data_Extraction | load_from_csv | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,991 | # drop unnecessary columns, these columns won't be useful in analysis and prediction
airbnb_df = airbnb_df.drop(['date_account_created','timestamp_first_active'], axis=1)
test_df = test_df.drop(['date_account_created','timestamp_first_active'], axis=1) | No | 5 | 10 | Data_Transform | drop_column | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,992 | airbnb_df['booked'] = (airbnb_df['country_destination'] != 'NDF').astype(int)
gp = airbnb_df[['id','country_destination']].groupby('country_destination').count()
ax = gp.sort('id').plot(kind='barh', color=['#0059b3'])
ax.set_xlabel('# of bookings')
ax.set_ylabel('country destination')
ax.legend_.remove() | No | 5 | 81 | Visualization | relationship | 27,393 | 1 | A | 0 | 0 | 0 | 0 | 0 | 6 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,993 | # date_first_booking
def get_year(date):
if date == date:
return int(str(date)[:4])
return date
def get_month(date):
if date == date:
return int(str(date)[5:7])
return date
# Create Year and Month columns
airbnb_df['Year'] = airbnb_df['date_first_booking'].apply(get_year)
airbnb_df... | No | 3 | 8 | Data_Transform | feature_engineering | 27,393 | 1 | A | 0 | 4 | 2 | 2 | 0 | 18 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,994 | # age<br><br># assign all age values > 100 to NaN, these NaN values will be replaced with real ages below<br>airbnb_df["age"][airbnb_df["age"] > 100] = np.NaN<br>test_df["age"][test_df["age"] > 100] = np.NaN<br><br># get average, std, and number of NaN values in airbnb_df<br>average_age_airbnb = airbnb_df["age"].... | No | 3 | 17 | Data_Transform | correct_missing_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,995 | # signup_method<br>airbnb_df["signup_method"] = (airbnb_df["signup_method"] == "basic").astype(int)<br>test_df["signup_method"] = (test_df["signup_method"] == "basic").astype(int)<br><br># signup_flow<br>airbnb_df["signup_flow"] = (airbnb_df["signup_flow"] == 3).astype(int)<br>test_df["signup_flow"] = (test_df["sig... | No | 5 | 16 | Data_Transform | data_type_conversions | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,996 | for f in airbnb_df.columns:<br> if f == "country_destination" or f == "id": continue<br> if airbnb_df[f].dtype == \'object\':<br> lbl = LabelEncoder()<br> lbl.fit(np.unique(list(airbnb_df[f].values) + list(test_df[f].values)))<br> airbnb_df[f] = lbl.transform(list(airbnb_df[f].values))<br> ... | No | 5 | 20 | Data_Transform | categorify | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,997 | X = airbnb_df.drop(["country_destination", "id", \'booked\'],axis=1)<br>y = airbnb_df["country_destination"]<br>test = test_df.drop("id",axis=1).copy() | No | 4 | 21 | Data_Transform | prepare_x_and_y | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,998 | # modify country_destination to numerical values
country_num_dic = {'NDF': 0, 'US': 1, 'other': 2, 'FR': 3, 'IT': 4, 'GB': 5, 'ES': 6, 'CA': 7, 'DE': 8, 'NL': 9, 'AU': 10, 'PT': 11}
num_country_dic = {y:x for x,y in country_num_dic.items()}
y = y.map(country_num_dic) | No | 5 | 20 | Data_Transform | categorify | 27,393 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
5,999 | # convert type to integer
ypred = ypred.astype(int)
# change values back to original country symbols
ypred = Series(ypred).map(num_country_dic) | No | 4 | 16 | Data_Transform | data_type_conversions | 27,393 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
6,000 | <br># Create submission<br><br>country_df = pd.DataFrame({<br> "id": test_df["id"],<br> "country": ypred<br> })<br><br>submission = DataFrame(columns=["id", "country"])<br><br># sort countries according to most probable destination country <br>for key in country_df[\'country\'].value_counts().index:<br... | No | 5 | 25 | Data_Export | save_to_csv | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.