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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,785 | b"# \nparams = {'objective': 'reg:linear',\n 'eta': 0.01,\n 'max_depth': 11,\n 'subsample': 0.5,\n 'colsample_bytree': 0.5,\n 'silent': 1,\n 'seed': 1\n }\nnum_trees = 10000" | No | 5 | 59 | Model_Train | init_hyperparams | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,786 | b"# \nfrom sklearn.model_selection import train_test_split\n\nX_train, X_test = train_test_split(train, test_size=0.2, random_state=2)\n\ndtrain = xgb.DMatrix(X_train[features], np.log1p(X_train.Sales))\ndvalid = xgb.DMatrix(X_test[features], np.log1p(X_test.Sales))\ndtest = xgb.DMatrix(test[features])\n\nwatchlist = [... | No | 2 | 7 | Model_Train | train_model | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,787 | #
test_probs = gbm.predict(xgb.DMatrix(test[features]), ntree_limit=gbm.best_ntree_limit)
indices = test_probs < 0
test_probs[indices] = 0
submission = pd.DataFrame({"Id": test["Id"], "Sales": np.expm1(test_probs)})
submission.to_csv("xgboost.csv", index=False)' | 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 |
2,788 | from fastai.tabular import *
from isoweek import Week
#import tarfile
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename))
# path to external datasets
tar = tarfile.open('/kaggle/input/external-datasets/rossmann.tgz', "r:gz")' | No | 4 | 88 | Debug | list_files | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,789 | # place holders
path = "/kaggle/input/rossmann-store-sales/"
base_path="../output" | No | 3 | 44 | Data_Extraction | load_from_disk | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,790 | # paths to kaggle data sets
train = "/kaggle/input/rossmann-store-sales/train.csv"
test = "/kaggle/input/rossmann-store-sales/test.csv"
store = "/kaggle/input/rossmann-store-sales/store.csv"
# paths to external tar file datasets
store_states = tar.extractfile('store_states.csv')
state_names = tar.extractfile('state_na... | No | 4 | 45 | Data_Extraction | load_from_csv | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,791 | # read in kaggle and external datasets as dataframes
table_names = [train, store, store_states, state_names, googletrend, weather, test]
tables = [pd.read_csv(fpath, low_memory=False) for fpath in table_names]
train, store, store_states, state_names, googletrend, weather, test = tables
len(train),len(test) | No | 4 | 45 | Data_Extraction | load_from_csv | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,792 | print(train.shape)
train.head() | No | 4 | 58 | Debug | show_shape | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,793 | print(test.shape)
test.head() | No | 4 | 58 | Debug | show_shape | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,794 | print(store.shape)
store.head() | No | 4 | 58 | Debug | show_shape | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,795 | print(store_states.shape)
store_states.head() | No | 4 | 58 | Debug | show_shape | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,796 | print(googletrend.shape)
googletrend.head() | No | 4 | 58 | Debug | show_shape | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,797 | print(weather.shape)
weather.head() | No | 4 | 58 | Debug | show_shape | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,798 | print(train.StateHoliday.unique())
print(test.StateHoliday.unique()) | No | 5 | 57 | Debug | show_unique_values | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,799 | train.StateHoliday = train.StateHoliday!='0'
test.StateHoliday = test.StateHoliday!='0' | No | 5 | 14 | Data_Transform | filter | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,800 | def join_df(left, right, left_on, right_on=None, suffix='_y'):
if right_on is None: right_on = left_on
return left.merge(right, how='left', left_on=left_on, right_on=right_on,
suffixes=("",suffix))' | No | 5 | 32 | Data_Transform | merge | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,801 | weather = join_df(weather, state_names, "file", "StateName")
weather.head(3) | No | 4 | 32 | Data_Transform | merge | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,802 | googletrend['Date'] = googletrend.week.str.split(' - ', expand=True)[0]
googletrend['State'] = googletrend.file.str.split('_', expand=True)[2]
googletrend.loc[googletrend.State=='NI', "State"] = 'HB,NI'' | No | 4 | 78 | Data_Transform | string_transform | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,803 | googletrend.head(3) | No | 5 | 41 | Debug | show_table | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,804 | def add_datepart(df, fldname, drop=True, time=False):
"Helper function that adds columns relevant to a date."
fld = df[fldname]
fld_dtype = fld.dtype
if isinstance(fld_dtype, pd.core.dtypes.dtypes.DatetimeTZDtype):
fld_dtype = np.datetime64
if not np.issubdtype(fld_dtype, np.datetime64):
... | No | 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 |
2,805 | add_datepart(googletrend,"Date", drop=False)
googletrend.head(3) | No | 2 | 16 | Data_Transform | data_type_conversions | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,806 | # continue with all other tables
add_datepart(weather, "Date", drop=False)
add_datepart(train, "Date", drop=False)
add_datepart(test, "Date", drop=False) | No | 3 | 16 | Data_Transform | data_type_conversions | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,807 | trend_de = googletrend[googletrend.file == 'Rossmann_DE']
trend_de.head(3) | No | 4 | 14 | Data_Transform | filter | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,808 | store = join_df(store, store_states, "Store")
len(store[store.State.isnull()]) | No | 4 | 32 | Data_Transform | merge | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,809 | joined = join_df(train, store, "Store")
joined_test = join_df(test, store, "Store")
len(joined[joined.StoreType.isnull()]), len(joined_test[joined_test.StoreType.isnull()]) | No | 4 | 32 | Data_Transform | merge | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,810 | # join the joined df with googletrend with ["State","Year","Week"] as the index
# this way the non matching day dates do not create issues.
joined = join_df(joined, googletrend, ["State","Year", "Week"])
joined_test = join_df(joined_test, googletrend, ["State","Year", "Week"])
len(joined[joined.trend.isnull()]),len(joi... | No | 4 | 32 | Data_Transform | merge | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,811 | # now join the overal germany trend
joined = joined.merge(trend_de, 'left', ["Year", "Week"], suffixes=('', '_DE'))
joined_test = joined_test.merge(trend_de, 'left', ["Year", "Week"], suffixes=('', '_DE'))
len(joined[joined.trend_DE.isnull()]),len(joined_test[joined_test.trend_DE.isnull()])' | No | 4 | 32 | Data_Transform | merge | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,812 | # finally join the weather data
joined = join_df(joined, weather, ["State","Date"])
joined_test = join_df(joined_test, weather, ["State","Date"])
len(joined[joined.Mean_TemperatureC.isnull()]),len(joined_test[joined_test.Mean_TemperatureC.isnull()]) | No | 4 | 32 | Data_Transform | merge | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,813 | # now we can drop duplicated columns
for df in (joined, joined_test):
for c in df.columns:
if c.endswith('_y'):
if c in df.columns: df.drop(c, inplace=True, axis=1) | No | 5 | 10 | Data_Transform | drop_column | 10,295,596 | 1 | A | 1 | 4 | 10 | 0 | 5 | 4 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,814 | for df in (joined,joined_test):
df['CompetitionOpenSinceYear'] = df.CompetitionOpenSinceYear.fillna(1900).astype(np.int32)
df['CompetitionOpenSinceMonth'] = df.CompetitionOpenSinceMonth.fillna(1).astype(np.int32)
df['Promo2SinceYear'] = df.Promo2SinceYear.fillna(1900).astype(np.int32)
df['Promo2SinceWee... | No | 5 | 16 | Data_Transform | data_type_conversions | null | 1 | A | 0 | 1 | 1 | 0 | 0 | 5 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,815 | for df in (joined, joined_test):
df['CompetitionOpenSince'] = pd.to_datetime(dict(year=df.CompetitionOpenSinceYear,
month=df.CompetitionOpenSinceMonth,
day=15))
df['CompetitionDaysOpen'] = df.Date.subtract... | No | 4 | 16 | Data_Transform | data_type_conversions | 10,295,596 | 1 | A | 1 | 1 | 1 | 0 | 5 | 5 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,816 | for df in (joined, joined_test):
df.loc[df.CompetitionDaysOpen<0, "CompetitionDaysOpen"] = 0
df.loc[df.CompetitionOpenSinceYear<1990, "CompetitionDaysOpen"] = 0 | No | 4 | 20 | Data_Transform | categorify | null | 1 | A | 0 | 1 | 1 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,817 | for df in (joined,joined_test):
df["CompetitionMonthsOpen"] = df["CompetitionDaysOpen"]//30
df.loc[df.CompetitionMonthsOpen>24, "CompetitionMonthsOpen"] = 24
joined.CompetitionMonthsOpen.unique() | No | 4 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | 1 | 1 | 0 | 0 | 4 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,818 | for df in (joined, joined_test):
df["Promo2Since"] = pd.to_datetime(df.apply(
lambda x: Week(x.Promo2SinceYear, x.Promo2SinceWeek).monday(), axis=1))
df["Promo2Days"] = df.Date.subtract(df['Promo2Since']).dt.days' | No | 4 | 16 | Data_Transform | data_type_conversions | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,819 | for df in (joined,joined_test):
df.loc[df.Promo2Days<0, "Promo2Days"] = 0
df.loc[df.Promo2SinceYear<1990, "Promo2Days"] = 0
df["Promo2Weeks"] = df["Promo2Days"]//7
df.loc[df.Promo2Weeks<0, "Promo2Weeks"] = 0
df.loc[df.Promo2Weeks>25, "Promo2Weeks"] = 25
df.Promo2Weeks.unique() | No | 4 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | 1 | 1 | 0 | 0 | 7 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,821 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename)) | No | 5 | 88 | Debug | list_files | null | 1 | A | 0 | 2 | 3 | 0 | 0 | 7 | ok | 1 | 1 | [{"detector": "general_ml", "framework": "General ML", "name": "Hardcoded file path detected: /kaggle/input. Consider using configuration files or environment variables.", "fix": "Not specified", "benefits": "Not specified", "location": "Line 6"}] | A | no applicable ML-specific findings | [] | ["Hardcoded file path"] | 0 | A |
2,822 | b"# This decoratore shows some info about function perormance\n# etc time,shpe changes,nan values\n\ndef info(function):\n import datetime\n def wrapper(data,*args,**kargs):\n tic = datetime.datetime.now()\n result = function(data,*args,**kargs)\n toc = datetime.datetime.now()\n ... | No | 5 | 53 | Other | something_strange | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,823 | # let`s load datasets as usually
train = pd.read_csv('/kaggle/input/rossmann-store-sales/train.csv')
test = pd.read_csv('/kaggle/input/rossmann-store-sales/test.csv')
stores = pd.read_csv('/kaggle/input/rossmann-store-sales/store.csv')
sample = pd.read_csv('/kaggle/input/rossmann-store-sales/sample_submission.csv') | No | 5 | 45 | Data_Extraction | load_from_csv | 11,013,798 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 6 | 3 | [{"detector": "general_ml", "framework": "General ML", "name": "Data loading detected without size checks or batch processing. Consider using generators or batch processing for large datasets.", "fix": "Not specified", "benefits": "Not specified", "location": ""}, {"detector": "general_ml", "framework": "General ML", "... | A | no applicable ML-specific findings | [] | ["Data loading detected without size checks or batch processing. Consider using generators or batch processing for large datasets.", "Hardcoded file path", "No error handling detected in data processing. Consider adding try-except blocks or validation checks for robustness."] | 7 | A |
2,824 | # Thank to notebooks we can definve evaluation metric
def ToWeight(y):
w = np.zeros(y.shape, dtype=float)
ind = y != 0
w[ind] = 1./(y[ind]**2)
return w
def rmspe(yhat, y):
w = ToWeight(y)
rmspe = np.sqrt(np.mean( w * (y - yhat)**2 ))
return rmspe | No | 5 | 84 | Other | not_enough_vertices | 11,013,798 | 1 | A | 1 | 2 | 0 | 0 | 10 | 9 | ok | 4 | 3 | [{"detector": "framework_specific", "framework": "NumPy", "name": "Missing Axis Specification", "fix": "Specify axis in array operations.", "benefits": "Improves performance and avoids unexpected behaviour.", "location": "Line 19"}, {"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Che... | C | Missing Axis Specification=medium | [{"type": "Missing Axis Specification", "severity": "medium"}] | ["Column Selection Checker", "Missing function docstring"] | 7 | C |
2,825 | import seaborn as sns
fig,ax =plt.subplots(1,2,figsize = (20,10))
ins1 = ax[0].inset_axes([0.5,0.5,0.4,0.4])
ins2 = ax[1].inset_axes([0.7,0.7,0.2,0.2])
sns.distplot(train[train.Sales != 0].Sales,ax=ax[0],bins=100)
sns.distplot(np.log1p(train[train.Sales != 0].Sales),ax=ins1,bins=100,color = 'red')
sns.boxplot(trai... | No | 5 | 33 | Visualization | distribution | 11,013,798 | 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"] | 7 | A |
2,826 | @info
def log_transf(df):
# log transformation function to remove skeew
df.Sales = np.log1p(df.Sales)
df.Customers = np.log1p(df.Customers)
return df
@info
def remove_outliers(df,column='Sales'):
# interquntile approach to remove outliers
q1 = df[column].quantile(0.2)
q3 = df[column].... | No | 3 | 8 | Data_Transform | feature_engineering | 11,013,798 | 1 | A | 0 | 2 | 0 | 0 | 0 | 14 | ok | 3 | 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": "general_ml", "framework": "General ML", "name": "Missing docstring for... | A | no applicable ML-specific findings | [] | ["Column Selection Checker", "Missing function docstring"] | 7 | A |
2,827 | @info
def timeseries_features(df):
# move to datetime format
df.Date = pd.to_datetime(df.Date)
df = df.sort_values('Date').reset_index(drop = True)
# derive regular for ml task time series features
df['month'] = df.Date.dt.month
df['dayofmonth'] = df.Date.dt.day
df['dayofye... | No | 2 | 8 | Data_Transform | feature_engineering | 11,013,798 | 1 | A | 0 | 6 | 2 | 0 | 0 | 50 | ok | 8 | 6 | [{"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 47"}, {"detector": "framework_specific", "framework": "Pandas", "name": "InPlace Checker", "fix": ... | 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", "InPlace Checker", "Magic number", "Missing function docstring"] | 7 | B |
2,828 | # Here I would like to know what is rmspe score with th emost dumb approach
# we devide data on train and test
test_bs = data_prep[data_prep.year == 2015]
train_bs = data_prep[data_prep.year < 2015]
# I am going to use mean Sales grouped by store-month-day among previous years as predicted values for 2015
predict_b... | Yes | 3 | 33 | Visualization | distribution | 11,013,798 | 1 | A | 0 | 1 | 1 | 0 | 0 | 16 | ok | 9 | 7 | [{"detector": "framework_specific", "framework": "NumPy", "name": "Randomness Control Checker", "fix": "Use np.random.seed() for reproducibility.", "benefits": "Enables reproducible results and debugging.", "location": ""}, {"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "f... | B | Cross Validation Checker=low, No random seed setting detected=low, Randomness Control Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "No random seed setting detected", "severity": "low"}, {"type": "Randomness Control Checker", "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"] | 7 | B |
2,829 | # There are two few reasons to use mean (aka target) encoding
# We have 1115 stores, definetly there is correlation between store and sales
# We could perform leave stores as it is ----> not good for known reasons
# We could perform OneHotEncoding ----> not goodm becaouse we will have 1115 new columns, mainly sp... | No | 1 | 16 | Data_Transform | data_type_conversions | 11,013,798 | 1 | A | 0 | 1 | 0 | 0 | 0 | 11 | ok | 1 | 1 | [{"detector": "general_ml", "framework": "General ML", "name": "Missing docstring for function: mean_encoding. Consider adding documentation for parameters and return values.", "fix": "Not specified", "benefits": "Not specified", "location": "Line 16"}] | A | no applicable ML-specific findings | [] | ["Missing function docstring"] | 7 | A |
2,830 | b"# also it is good to statistic\n\nfrom statsmodels.tsa.seasonal import seasonal_decompose\nfrom statsmodels.graphics.tsaplots import plot_acf,plot_pacf\nfrom statsmodels.tsa.stattools import adfuller\n\n\n# first lets check our data for stationarity\n\ncounter = 0\nfor store in data_prep.Store.unique():\n df_store... | Yes | 2 | 22 | Environment | import_modules | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,831 | # lets check few random stores
rnd_store = np.random.randint(min(data_prep.Store),max(data_prep.Store),3)
fig,ax = plt.subplots(3,2,figsize = (15,10))
for idx,store in enumerate(rnd_store):
df_store = data_prep.copy().loc[data_prep.Store == store,['Date','Sales']].set_index('Date')
df_store = df_store.resam... | No | 3 | 33 | Visualization | distribution | 11,013,798 | 1 | A | 0 | 1 | 1 | 0 | 0 | 10 | ok | 2 | 2 | [{"detector": "framework_specific", "framework": "NumPy", "name": "Randomness Control Checker", "fix": "Use np.random.seed() for reproducibility.", "benefits": "Enables reproducible results and debugging.", "location": ""}, {"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "f... | B | Randomness Control Checker=low | [{"type": "Randomness Control Checker", "severity": "low"}] | ["Column Selection Checker"] | 7 | B |
2,832 | b"# finally lets check on nan and dublicated values\n \nprint('NaN summary\\n\\n',data_prep.isna().sum()/len(data_prep)*100,'\\n')\nprint('Number of absoulute dublicates:',data_prep.duplicated().sum())\nprint('Number of Store - Date dublicates:',data_prep.duplicated(subset = ['Date','Store']).sum())" | No | 3 | 39 | EDA | count_missing_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,833 | from pandas.plotting import scatter_matrix
import seaborn
corr = data_prep.corr()
plt.figure(figsize=(15,15))
seaborn.heatmap(corr) | No | 5 | 80 | Visualization | heatmap | 11,013,798 | 1 | A | 0 | 0 | 0 | 0 | 0 | 5 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 7 | A |
2,834 | stores = np.random.randint(train.Store.min(),train.Store.max(),2)
plt.figure(figsize=(15,10))
for store in stores:
plt.plot(data_prep.loc[(data_prep.Store == store) & (data_prep.year == 2013),'Date'],data_prep.loc[(data_prep.Store == store) & (data_prep.year == 2013),'Sales'],label = store)
plt.legend() | No | 5 | 75 | Visualization | time_series | 11,013,798 | 1 | A | 0 | 1 | 1 | 0 | 0 | 5 | ok | 3 | 3 | [{"detector": "framework_specific", "framework": "NumPy", "name": "Randomness Control Checker", "fix": "Use np.random.seed() for reproducibility.", "benefits": "Enables reproducible results and debugging.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Validation Checker... | B | Cross Validation Checker=low, No random seed setting detected=low, Randomness Control Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "No random seed setting detected", "severity": "low"}, {"type": "Randomness Control Checker", "severity": "low"}] | [] | 7 | B |
2,835 | ohe_col = data_prep.select_dtypes('object').columns.tolist()+['Store','DayOfWeek','month']
num_col = data_prep.select_dtypes('float').columns.tolist() | No | 2 | 8 | Data_Transform | feature_engineering | 11,013,798 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 7 | A |
2,836 | X = data_prep.drop(['Date','Sales','Customers','Store'],axis = 1)
y = data_prep.Sales
X_train,X_val = X.loc[X.year < 2015,:],X.loc[X.year == 2015,:]
y_train,y_val = y[:X_train.index[-1]+1], y[X_train.index[-1]+1:] | No | 3 | 13 | Data_Transform | split | 11,013,798 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | 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"] | 7 | A |
2,837 | from sklearn.preprocessing import StandardScaler,MinMaxScaler
from sklearn.preprocessing import OneHotEncoder,LabelEncoder,OrdinalEncoder
from sklearn.compose import make_column_transformer
from sklearn.pipeline import make_pipeline
transformer = make_column_transformer(
(StandardScaler(),['CompetitionDistance', '... | No | 3 | 7 | Model_Train | train_model | 11,013,798 | 1 | A | 1 | 0 | 0 | 0 | 5 | 18 | ok | 11 | 8 | [{"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, 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"}] | ["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"] | 7 | D |
2,838 | # We need to apply same transformation on test set as we did we train set
test_prep = (test
.copy()
.pipe(timeseries_features)
.drop(['Open','Date'],axis=1)
)
test_prep = pd.merge(test_prep,store_prep,how='left',on='Store')
test_prep['is_promo'] = test_prep.apply... | No | 4 | 32 | Data_Transform | merge | 11,013,798 | 1 | A | 0 | 1 | 1 | 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"] | 7 | A |
2,839 | test_id = test_prep.Id
test_prep.drop('Id',axis=1,inplace = True)
predict = np.expm1(pipeline.predict(test_prep)) # Remember to make inverse transformation | No | 5 | 48 | Model_Evaluation | predict_on_test | 11,013,798 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | 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 9"}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Unit Testing Checker"... | A | no applicable ML-specific findings | [] | ["Exception Handling Checker", "InPlace Checker", "Unit Testing Checker"] | 7 | A |
2,840 | sub = pd.DataFrame({'Id':test_id,'Sales':predict}).sort_values('Id').reset_index(drop=True)
sub.to_csv('submission.csv',index=False) | No | 5 | 25 | Data_Export | save_to_csv | 11,013,798 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 5 | 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"] | 7 | B |
2,841 | columns = ["Date", "Store", "Promo", "StateHoliday", "SchoolHoliday"] | No | 4 | 21 | Data_Transform | prepare_x_and_y | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,842 | df = train[columns].append(test[columns])
df.head(3) | No | 4 | 21 | Data_Transform | prepare_x_and_y | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,843 | fld = 'SchoolHoliday'
df = df.sort_values(['Store', 'Date'])
get_elapsed(fld, 'After')
df = df.sort_values(['Store', 'Date'], ascending=[True, False])
get_elapsed(fld, 'Before') | No | 4 | 9 | Data_Transform | sort_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 5 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,844 | fld = 'StateHoliday'
df = df.sort_values(['Store', 'Date'])
get_elapsed(fld, 'After')
df = df.sort_values(['Store', 'Date'], ascending=[True, False])
get_elapsed(fld, 'Before') | No | 4 | 9 | Data_Transform | sort_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 5 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,845 | fld = 'Promo'
df = df.sort_values(['Store', 'Date'])
get_elapsed(fld, 'After')
df = df.sort_values(['Store', 'Date'], ascending=[True, False])
get_elapsed(fld, 'Before') | No | 4 | 9 | Data_Transform | sort_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 5 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,846 | df = df.set_index('Date') | No | 5 | 53 | Other | something_strange | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,847 | columns = ['SchoolHoliday', 'StateHoliday', 'Promo'] | No | 4 | 17 | Data_Transform | correct_missing_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,848 | for o in ['Before', 'After']:
for p in columns:
a = o+p
df[a] = df[a].fillna(0).astype(int) | No | 3 | 17 | Data_Transform | correct_missing_values | null | 1 | A | 0 | 2 | 3 | 0 | 0 | 4 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,849 | bwd = df[['Store']+columns].sort_index().groupby("Store").rolling(7, min_periods=1).sum()' | No | 4 | 60 | Data_Transform | groupby | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,850 | fwd = df[['Store']+columns].sort_index(ascending=False
).groupby("Store").rolling(7, min_periods=1).sum()' | No | 4 | 60 | Data_Transform | groupby | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,851 | bwd.drop('Store',1,inplace=True)
bwd.reset_index(inplace=True) | 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 |
2,852 | fwd.drop('Store',1,inplace=True)
fwd.reset_index(inplace=True) | 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 |
2,853 | df.reset_index(inplace=True) | No | 4 | 84 | Other | not_enough_vertices | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,854 | df = df.merge(bwd, 'left', ['Date', 'Store'], suffixes=['', '_bw'])
df = df.merge(fwd, 'left', ['Date', 'Store'], suffixes=['', '_fw']) | No | 5 | 32 | Data_Transform | merge | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,855 | df.drop(columns,1,inplace=True) | No | 5 | 10 | Data_Transform | drop_column | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,857 | df["Date"] = pd.to_datetime(df.Date) | No | 5 | 16 | Data_Transform | data_type_conversions | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,859 | joined = join_df(joined, df, ['Store', 'Date']) | No | 5 | 32 | Data_Transform | merge | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,860 | joined_test = join_df(joined_test, df, ['Store', 'Date']) | No | 5 | 32 | Data_Transform | merge | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,861 | joined = joined[joined.Sales!=0] | No | 5 | 14 | Data_Transform | filter | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,862 | joined.reset_index(inplace=True)
joined_test.reset_index(inplace=True) | No | 5 | 84 | Other | not_enough_vertices | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,864 | pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None) | No | 5 | 23 | Environment | set_options | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,865 | train_df = joined
test_df = joined_test | No | 5 | 77 | Other | define_variables | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,866 | train_df.head().T | 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 |
2,867 | print(test_df.shape)
test_df.head() | No | 3 | 41 | Debug | show_table | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,868 | n = len(train_df); n | No | 5 | 77 | Other | define_variables | null | 1 | A | 0 | 0 | 0 | 1 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,869 | idx = np.random.permutation(range(n))[:2000]
idx.sort()
small_train_df = train_df.iloc[idx[:1000]]
small_test_df = train_df.iloc[idx[1000:]]
small_cont_vars = ['CompetitionDistance','Mean_Humidity']
small_cat_vars = ['Store','DayOfWeek','PromoInterval']
small_train_df = small_train_df[small_cat_vars + small_cont_vars +... | No | 4 | 14 | Data_Transform | filter | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 8 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,870 | small_train_df.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 |
2,871 | small_test_df.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 |
2,872 | categorify = Categorify(small_cat_vars, small_cont_vars)
categorify(small_train_df)
categorify(small_test_df, test=True) | No | 5 | 20 | Data_Transform | categorify | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,873 | small_train_df.PromoInterval.cat.categories | No | 5 | 57 | Debug | show_unique_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,874 | # we convert to categories then add 1 to -1 (NaNs) to turn it to zero because you can not look up 1 in an embedding matrix
small_train_df['PromoInterval'].cat.codes[:5] | No | 5 | 41 | Debug | show_table | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,875 | fill_missing = FillMissing(small_cat_vars, small_cont_vars)
fill_missing(small_train_df)
fill_missing(small_test_df, test=True) | No | 5 | 17 | Data_Transform | correct_missing_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,876 | # find any missing values, create a column called "_na" and set it to True any time it is missing
# then replace the empty value with the median of CompetitionDistance because it needs to be a continues varaiable
small_train_df[small_train_df['CompetitionDistance_na'] == True]' | No | 5 | 14 | Data_Transform | filter | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,877 | len(train_df),len(test_df) | No | 5 | 58 | Debug | show_shape | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,878 | # as seen above, create pre processers fill missing, categorify
# and normalize (normalize: for any continous var subtract the mean and divide by std)
procs=[FillMissing, Categorify, Normalize] | No | 5 | 77 | Other | define_variables | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,879 | # name your category variables, keep some continues variables like "day" as cat because
# as a cat var it will create an embedding matrix and the different days of the month will create different behavors
cat_vars = ['Store', 'DayOfWeek', 'Year', 'Month', 'Day', 'StateHoliday', 'CompetitionMonthsOpen',
'Promo2Weeks... | No | 4 | 14 | Data_Transform | filter | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,880 | # dependant var
dep_var = 'Sales'
# the final df to pass in will be the cat_vars, cont_vars, dep_var, and date, date will be used to create the validation set,
#it will be the same number of records at the end of the time period as the test set from kaggle
df = train_df[cat_vars + cont_vars + [dep_var,'Date']].copy() | No | 3 | 14 | Data_Transform | filter | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,881 | test_df['Date'].min(), test_df['Date'].max() | No | 5 | 40 | Debug | show_table_attributes | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,882 | cut = train_df['Date'][(train_df['Date'] == train_df['Date'][len(test_df)])].index.max()
cut | No | 5 | 14 | Data_Transform | filter | 10,295,596 | 1 | A | 0 | 0 | 0 | 1 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,883 | valid_idx = range(cut) | No | 4 | 13 | Data_Transform | split | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,884 | # finally, lets look
df[dep_var].head() | No | 5 | 41 | Debug | show_table | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,885 | # create databunch
data = (TabularList.from_df(df, path='.', cat_names=cat_vars, cont_names=cont_vars, procs=procs,)
.split_by_idx(valid_idx)
.label_from_df(cols=dep_var, label_cls=FloatList, log=True)
.add_test(TabularList.from_df(test_df, path=path, cat_names=cat_vars, ... | No | 5 | 12 | Data_Transform | create_dataframe | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 5 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,886 | max_log_y = np.log(np.max(train_df['Sales'])*1.2)
y_range = torch.tensor([0, max_log_y], device=defaults.device) | No | 4 | 21 | Data_Transform | prepare_x_and_y | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,887 | # Learner
learn = tabular_learner(data, layers=[1000,500], ps=[0.001,0.01], emb_drop=0.04,
y_range=y_range, metrics=exp_rmspe) | No | 4 | 7 | Model_Train | train_model | 10,295,596 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
2,888 | learn.model | No | 3 | 4 | Model_Train | choose_model_class | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | 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.