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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,848 | df_out.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 |
1,849 | df_out.to_csv('out5.csv') | No | 5 | 25 | Data_Export | save_to_csv | 242,408 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 9 | A |
1,850 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline | No | 5 | 23 | Environment | set_options | null | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 0 | null |
1,851 | df_store = pd.read_csv('../input/store.csv', index_col='Store') | No | 5 | 45 | Data_Extraction | load_from_csv | 243,149 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 2 | 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", "Hardcoded file path"] | 6 | A |
1,852 | df_store.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 |
1,853 | df_store.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 |
1,854 | categorial_features = ['StoreType', 'Assortment', 'PromoInterval'] | No | 1 | 23 | Environment | set_options | 243,149 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | 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"] | 6 | A |
1,855 | plt.figure(figsize=(20,16))
for i,country in enumerate(list_countries):
Fatal_diff=Fatal_pivot[(Fatal_pivot[country]>0)][country].diff().fillna(0)
Fatal_diff=Fatal_diff[Fatal_diff>0]
plt.subplot(3,4,i+1)
Fatal_diff.plot(color=colors[i],label=country.upper(),lw=5)
plt.xticks(rotation=60)
plt.titl... | No | 5 | 33 | Visualization | distribution | 8,604,602 | 1 | A | 0 | 1 | 1 | 0 | 0 | 10 | 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"] | 5 | A |
1,856 | from sklearn.preprocessing import OneHotEncoder, LabelEncoder
for p in categorial_features:
X_int = LabelEncoder().fit_transform(df_store[p].values.astype(str)).reshape(-1,1)
ohe_feat = OneHotEncoder(sparse=False).fit_transform(X_int)
tmp = pd.DataFrame(ohe_feat, columns=['{0}='.format(p) + str(i) for i in... | No | 4 | 8 | Data_Transform | feature_engineering | 243,149 | 1 | A | 0 | 1 | 1 | 0 | 0 | 9 | ok | 14 | 10 | [{"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, 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"}] | ["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"] | 6 | D |
1,857 | for p in ['CompetitionDistance', 'CompetitionOpenSinceMonth', 'CompetitionOpenSinceYear']:
df_store.loc[:, p] = (df_store[p] - df_store[p].mean()) / df_store[p].std() | No | 4 | 18 | Data_Transform | normalization | 243,149 | 1 | A | 0 | 1 | 1 | 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"] | 6 | A |
1,858 | # Understanding New cases confirmation variations on daily basis
plt.figure(figsize=(20,16))
for i,country in enumerate(list_countries):
plt.subplot(4,3,i+1)
train_df[(train_df['Country_Region']==country)&(train_df['ConfirmedCases']!=0)].groupby('Date')['ConfirmedCases'].sum().diff().diff().plot(color=colors[i]... | No | 5 | 33 | Visualization | distribution | 8,604,602 | 1 | A | 0 | 1 | 1 | 0 | 0 | 7 | 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": "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"] | 5 | B |
1,859 | plt.figure(figsize=(16,8))
plt.title('Confirmed Cases trend from first day of incidence')
for i,country in enumerate(list_countries):
confirm_group=train_df[(train_df['Country_Region']==country)&train_df['ConfirmedCases']!=0].groupby('Date').agg({'ConfirmedCases':['sum']})
confirm_value=[j for j in confirm_grou... | No | 5 | 33 | Visualization | distribution | 8,604,602 | 1 | A | 1 | 1 | 1 | 0 | 5 | 8 | 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": "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"] | 5 | B |
1,860 | from sklearn.manifold import TSNE
model = TSNE()
arr = model.fit_transform(df_store.fillna(0))
plt.scatter(arr[:, 0], arr[:, 1]) | No | 3 | 33 | Visualization | distribution | 243,149 | 1 | A | 1 | 0 | 0 | 0 | 5 | 4 | ok | 6 | 6 | [{"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... | D | Cross Validation Checker=low, Data Leakage Checker=high | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Data Leakage Checker", "severity": "high"}] | ["Dependent Threshold Checker", "Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 6 | D |
1,861 | plt.figure(figsize=(16,10))
plt.title('Fatalities trend from first day of incidence')
for i,country in enumerate(list_countries):
fatal_group=train_df[(train_df['Country_Region']==country)&train_df['ConfirmedCases']!=0].groupby('Date').agg({'Fatalities':['sum']})
fatal_value=[j for j in fatal_group.Fatalities['... | No | 5 | 33 | Visualization | distribution | 8,604,602 | 1 | A | 1 | 1 | 1 | 0 | 5 | 8 | 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": "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"] | 5 | B |
1,862 | from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score
scores = []
ns = list(range(2, 10)) + list(range(10, 30, 5))
for n in ns:
agc = AgglomerativeClustering(n_clusters=n)
store_cluster = agc.fit_predict(df_store.fillna(0)).reshape(-1,1)
scores.append(silhouette_s... | No | 2 | 6 | Hyperparam_Tuning | train_on_grid | 243,149 | 1 | A | 1 | 1 | 1 | 0 | 5 | 9 | ok | 10 | 8 | [{"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, 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"}] | ["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"] | 6 | B |
1,863 | agc = AgglomerativeClustering(n_clusters=9)
store_cluster = agc.fit_predict(df_store.fillna(1))
store_cluster.shape | No | 3 | 7 | Model_Train | train_model | 243,149 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 5 | 5 | [{"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"}] | ["Dependent Threshold Checker", "Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 6 | B |
1,864 | from sklearn.manifold import TSNE
model = TSNE()
arr = model.fit_transform(df_store.fillna(1))
plt.scatter(arr[:, 0], arr[:, 1], c=store_cluster) | No | 3 | 56 | Visualization | plot_predictions | 243,149 | 1 | A | 1 | 0 | 0 | 0 | 5 | 4 | ok | 6 | 6 | [{"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... | D | Cross Validation Checker=low, Data Leakage Checker=high | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Data Leakage Checker", "severity": "high"}] | ["Dependent Threshold Checker", "Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 6 | D |
1,865 | print(df_train.shape)
df_train.head() | No | 3 | 45 | Data_Extraction | load_from_csv | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,866 | df_train.StateHoliday.unique() | 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 |
1,867 | df_train.replace({'StateHoliday': {0: '0'}}, inplace=True)
df_train.StateHoliday.unique() | No | 5 | 57 | Debug | show_unique_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,868 | SH_int = LabelEncoder().fit_transform(df_train.StateHoliday.values.astype(str)).reshape(-1,1)
ohe_feat = OneHotEncoder(sparse=False).fit_transform(SH_int)
tmp = pd.DataFrame(ohe_feat, columns=['SH='+ str(i) for i in df_train.StateHoliday.unique()],
index=df_train.index,
dtype=int)... | No | 2 | 8 | Data_Transform | feature_engineering | 243,149 | 1 | A | 0 | 0 | 0 | 0 | 0 | 7 | ok | 14 | 10 | [{"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, 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"}] | ["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"] | 6 | D |
1,869 | ohe_feat = OneHotEncoder(sparse=False).fit_transform(df_train.DayOfWeek.values.reshape(-1,1))
tmp = pd.DataFrame(ohe_feat, columns=['DayOfWeek=' + str(i) for i in df_train.DayOfWeek.unique()],
index=df_train.index,
dtype=int)
df_train = df_train.drop('DayOfWeek', axis=1)
df_train ... | No | 3 | 8 | Data_Transform | feature_engineering | 243,149 | 1 | A | 0 | 0 | 0 | 0 | 0 | 6 | ok | 9 | 9 | [{"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, 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"}] | ["Dependent Threshold Checker", "Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 6 | D |
1,870 | print(df_train.shape, df_train.columns) | No | 3 | 8 | Data_Transform | feature_engineering | 243,149 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | 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"] | 6 | A |
1,871 | df_train['label'] = pd.Series([store_cluster[ind - 1] for ind in df_train.index],
index=df_train.index)
y_train = df_train[df_train.Open != 0].Sales.values
X_train = df_train[df_train.Open != 0].drop(['Date', 'Sales', 'Customers'], axis=1).values | No | 2 | 58 | Debug | show_shape | 243,149 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 2 | 2 | [{"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"}] | ["Dependent Threshold Checker"] | 6 | B |
1,872 | from sklearn.linear_model import Ridge
from sklearn.metrics import accuracy_score
rlnrs = {}
for i, c in enumerate(np.unique(store_cluster)):
df_c = df_train[df_train.label == c]
if df_c.shape[0] == 0:
continue
X_c = df_c.drop(['Date', 'Sales', 'Customers'], axis=1).values
y_c = df_c.Sales.valu... | No | 3 | 21 | Data_Transform | prepare_x_and_y | 243,149 | 1 | A | 0 | 2 | 3 | 0 | 0 | 13 | ok | 6 | 6 | [{"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, Cross-validation not detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Cross-validation not detected", "severity": "low"}] | ["Dependent Threshold Checker", "Exception Handling Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 6 | B |
1,873 | df_test = pd.read_csv('../input/test.csv', index_col='Id') | No | 2 | 7 | Model_Train | train_model | 243,149 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 2 | 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", "Hardcoded file path"] | 6 | A |
1,874 | print(df_test.Open.unique()) | No | 5 | 57 | Debug | show_unique_values | 243,149 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | 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"] | 6 | A |
1,875 | df_test.loc[df_test.Open == 0, 'Sales'] = 0
df_test.Open = df_test.loc[:, 'Open'].fillna(1) | No | 5 | 17 | Data_Transform | correct_missing_values | 243,149 | 1 | A | 0 | 0 | 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"] | 6 | A |
1,876 | df_test.replace({'StateHoliday': {0: '0'}}, inplace=True)
SH_int = LabelEncoder().fit_transform(df_test.StateHoliday.values.astype(str)).reshape(-1,1)
ohe_feat = OneHotEncoder(sparse=False).fit_transform(SH_int)
tmp = pd.DataFrame(ohe_feat, columns=['SH='+ str(i) for i in df_test.StateHoliday.unique()],
... | No | 3 | 57 | Debug | show_unique_values | 243,149 | 1 | A | 0 | 0 | 0 | 0 | 0 | 20 | ok | 16 | 10 | [{"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, 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"}] | ["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"] | 6 | D |
1,877 | plt.figure(figsize=(16,8))
plt.subplot(1,2,1)
train_df.groupby('Date')['ConfirmedCases'].sum().plot(color='blue')
plt.ylabel('Number of Confirmed Cases')
plt.title('Confirmed Cases worldwide trend')
plt.subplot(1,2,2)
train_df.groupby('Date')['Fatalities'].sum().plot(color='r')
plt.ylabel('Number of Fatalities')
plt.t... | No | 5 | 33 | Visualization | distribution | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,878 | # Confirmed Cases and Fatalities without China's data
plt.figure(figsize=(16,8))
plt.subplot(1,2,1)
train_df[(train_df['Country_Region']!='China')&(train_df['ConfirmedCases']!=0)].groupby('Date')['ConfirmedCases'].sum().plot(color='blue')
plt.ylabel('Number of Confirmed Cases')
plt.title('Confirmed Cases worldwide tren... | No | 5 | 33 | Visualization | distribution | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,879 | countries=train_df['Country_Region'].unique() | No | 5 | 57 | Debug | show_unique_values | 8,604,602 | 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": "Cross Valida... | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | ["Column Selection Checker"] | 5 | B |
1,880 | country_list=[]
confirmation_list=[]
list_fatality=[]
for country in countries:
country_list.append(country)
confirm_country=train_df[train_df.Country_Region==country].groupby('Date')['ConfirmedCases'].sum().max()
confirmation_list.append(confirm_country)
fatal_country=train_df[train_df.Country_Region==... | Yes | 2 | 8 | Data_Transform | feature_engineering | 8,604,602 | 1 | A | 0 | 1 | 1 | 0 | 0 | 11 | 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": "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"] | 5 | B |
1,881 | map_df | No | 5 | 41 | Debug | show_table | 8,604,602 | 1 | A | 0 | 0 | 0 | 1 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 5 | A |
1,882 | code_df=pd.read_csv('../input/countrycodes/country-codes.csv') | No | 5 | 45 | Data_Extraction | load_from_csv | 8,604,602 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 1 | 1 | [{"detector": "general_ml", "framework": "General ML", "name": "Hardcoded file path detected: ../input/countrycodes/country-codes.csv. 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"] | 5 | A |
1,883 | code_df=code_df[['ISO3166-1-Alpha-3','CLDR display name']] | No | 5 | 10 | Data_Transform | drop_column | 8,604,602 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 5 | A |
1,884 | map_df=map_df.merge(code_df,left_on='Country',right_on='CLDR display name') | No | 5 | 32 | Data_Transform | merge | 8,604,602 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 5 | A |
1,885 | map_df.drop('CLDR display name',axis=1,inplace=True) | No | 5 | 10 | Data_Transform | drop_column | 8,604,602 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 1 | 1 | [{"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 6"}] | A | no applicable ML-specific findings | [] | ["InPlace Checker"] | 5 | A |
1,886 | map_df.rename(columns={'ISO3166-1-Alpha-3':'Country Code'},inplace=True) | No | 5 | 61 | Data_Transform | rename_columns | 8,604,602 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 1 | 1 | [{"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 6"}] | A | no applicable ML-specific findings | [] | ["InPlace Checker"] | 5 | A |
1,887 |
from plotly.offline import download_plotlyjs,init_notebook_mode,plot,iplot
init_notebook_mode(connected=True)
data=go.Choropleth(
locations=map_df['Country Code'], # Spatial coordinates
z = map_df['ConfirmedCases'], # Data to be color-coded,
colorscale = 'Reds',
text=map_df['Country'],
colorbar_ti... | No | 5 | 33 | Visualization | distribution | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,888 | test_df['Date']=pd.to_datetime(test_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 |
1,889 | test_df['Province_State']=test_df.drop('Province_State',axis=1) | No | 5 | 10 | Data_Transform | drop_column | 8,604,602 | 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"] | 5 | A |
1,890 | train_df=train_df.reset_index() | No | 2 | 10 | Data_Transform | drop_column | 8,604,602 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 1 | 1 | [{"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": ""}] | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | [] | 5 | B |
1,891 | def error_metrics(model, predictions, y_test):
print("Model: ", model)
# The mean squared error
print("--Mean squared error: %.2f" % mean_squared_error(y_test, predictions))
# RMS
print('--Root Mean Squared Error: %.2f' % np.sqrt(metrics.mean_squared_error(y_test, predictions)))
# Explained vari... | No | 5 | 84 | Other | not_enough_vertices | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,892 | # Take a look at some of the results
def inspect_df(predictions, y_test):
true_vs_pred = np.vstack((predictions, y_test))
true_df = pd.DataFrame(true_vs_pred)
true_df = true_df.transpose()
true_df.columns = ["Predicted", "Actual"]
return true_df | No | 5 | 12 | Data_Transform | create_dataframe | 8,658,083 | 1 | A | 0 | 1 | 0 | 0 | 0 | 6 | ok | 1 | 1 | [{"detector": "general_ml", "framework": "General ML", "name": "Missing docstring for function: inspect_df. Consider adding documentation for parameters and return values.", "fix": "Not specified", "benefits": "Not specified", "location": "Line 5"}] | A | no applicable ML-specific findings | [] | ["Missing function docstring"] | 3 | A |
1,893 | from IPython.display import display_html
def display_side_by_side(*args):
html_str=''
for df in args:
html_str+=df.to_html()
display_html(html_str.replace('table','table style="display:inline"'),raw=True)' | No | 5 | 53 | Other | something_strange | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,894 | ridge_pred, y_test = linear_models(x, y, "ridge")
lasso_pred, y_test = linear_models(x, y, "lasso")
xgb_pred, y_test = linear_models(x, y, "xgb")
lgb_pred, y_test = linear_models(x, y, "catboost") | No | 5 | 53 | Other | something_strange | 8,658,083 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
1,895 | error_metrics("Ridge", ridge_pred, y_test)
error_metrics("Lasso", lasso_pred, y_test)
error_metrics("xgboost regression", xgb_pred, y_test)
error_metrics("catboost regression", lgb_pred, y_test) | No | 5 | 49 | Model_Evaluation | compute_test_metric | 8,658,083 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
1,896 | X_train, X_test, y_train, y_test = train_test_split(x, y, random_state = 42)
model = CatBoostRegressor(random_state = 42)
"""grid = {'learning_rate': [0.03, 0.1],
'depth': [4, 6, 10],
'l2_leaf_reg': [1, 3, 5, 7, 9],
#'num_leaves' : [5, 15, 31, 60],
'bagging_temperature' : [0, 1, 5, 10]... | No | 3 | 13 | Data_Transform | split | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,897 | model = CatBoostRegressor(num_leaves = 31, bagging_temperature= 0, depth = 6, l2_leaf_reg = 1, learning_rate = 0.03).fit(X_train, y_train)
predictions = model.predict(X_test)
error_metrics("Catboost regression", predictions, y_test) | No | 3 | 7 | Model_Train | train_model | 8,658,083 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 8 | 7 | [{"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, 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"}] | ["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"] | 3 | B |
1,898 | print(model.get_feature_importance(prettified = True)) | No | 3 | 79 | Visualization | model_coefficients | 8,658,083 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
1,899 | test.columns | No | 5 | 71 | Debug | show_columns | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,900 | submit = pd.DataFrame()
submit['ForecastId'] = test['ForecastId']
test.drop(["ForecastId"], axis = 1, inplace = True)' | No | 4 | 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 |
1,901 | submit | No | 5 | 41 | Debug | show_table | null | 1 | A | 0 | 0 | 0 | 1 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,902 | fatilities = model.predict(test) | No | 5 | 48 | Model_Evaluation | predict_on_test | 8,658,083 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 2 | 2 | [{"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... | A | no applicable ML-specific findings | [] | ["Exception Handling Checker", "Unit Testing Checker"] | 3 | A |
1,903 | model = CatBoostRegressor(num_leaves = 31, bagging_temperature= 0, depth = 4, l2_leaf_reg = 5, learning_rate = 0.1).fit(X_train, y_train)
predictions = model.predict(X_test)
error_metrics("Catboost regression", predictions, y_test) | No | 4 | 79 | Visualization | model_coefficients | 8,658,083 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 8 | 7 | [{"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, 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"}] | ["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"] | 3 | B |
1,904 | confirmedCases = model.predict(test) | Yes | 5 | 48 | Model_Evaluation | predict_on_test | 8,658,083 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 2 | 2 | [{"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... | A | no applicable ML-specific findings | [] | ["Exception Handling Checker", "Unit Testing Checker"] | 3 | A |
1,905 | submit['ConfirmedCases'] = confirmedCases
submit['Fatalities'] = fatilities | No | 5 | 55 | Data_Export | prepare_output | 8,658,083 | 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"] | 3 | A |
1,906 | submit.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 |
1,907 | import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression | No | 5 | 22 | Environment | import_modules | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 0 | A |
1,908 | test = pd.read_csv("../input/test.csv",parse_dates=[3],index_col="Id",dtype={"StateHoliday":np.str})
train = pd.read_csv("../input/train.csv",parse_dates=[2],dtype={"StateHoliday":np.str})
print(test.dtypes) # Kaggle doesn't seem to support Python 2.7. Oh well.
print(train.dtypes)' | 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 |
1,909 | set(test.Store.values).issubset(train.Store.values)
# if true, I can predict sales per store, not the whole model with store info joined | No | 5 | 53 | Other | something_strange | 244,547 | 1 | A | 0 | 0 | 0 | 1 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
1,910 | train = train.loc[train.Sales > 0]
# Any day and store with 0 sales is ignored in scoring => no reason to predict them, either | No | 5 | 14 | Data_Transform | filter | 244,547 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
1,911 | def prepare(df):
# transform the date into something human-meaningful
df['Year'] = pd.DatetimeIndex(df.Date).year
df['Month'] = pd.DatetimeIndex(df.Date).month
df['Day'] = pd.DatetimeIndex(df.Date).day
# encode StateHolidays into numbers
# Since there are only 'a' state holidays in test set, I c... | No | 5 | 21 | Data_Transform | prepare_x_and_y | 244,547 | 1 | A | 0 | 1 | 0 | 0 | 0 | 7 | 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": "general_ml", "framework": "General ML", "name": "Missing docstring for... | A | no applicable ML-specific findings | [] | ["Column Selection Checker", "Missing function docstring"] | 3 | A |
1,912 | train = prepare(train);
test = prepare(test);
print(train.dtypes)
print(test.dtypes) | No | 4 | 70 | Debug | show_data_types | 244,547 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
1,913 | # Curses! NA! Foiled again!
test.iloc[pd.isnull(test).any(1).nonzero()] | No | 5 | 14 | Data_Transform | filter | 244,547 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
1,914 | test_nona = test.dropna().copy()
stores = set(test_nona.Store.values)
test_nona['Sales'] = 0 # create a column to be filled | No | 5 | 17 | Data_Transform | correct_missing_values | 244,547 | 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"] | 3 | A |
1,915 | columns = ['DayOfWeek','Open','Promo','SchoolHoliday','Year','Month','Day','StateHoliday']
# Customers are not present in test, not worth using
for store in stores: # takes *FOREVER* to run
# pandas throws "IndexingError: Unalignable boolean Series key provided" if I index df directly
# well, it must think it's... | No | 2 | 27 | Model_Train | predict_on_train | null | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 0 | null |
1,916 | test['Sales'] = test_nona.Sales
test = test.fillna(0) # we didn't predict some stores with NAs, tell Kaggle to ignore them | No | 5 | 17 | Data_Transform | correct_missing_values | 244,547 | 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"] | 3 | A |
1,917 | test[['Sales']].to_csv("submission.csv")' | 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 |
1,918 | # This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in
import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O... | No | 5 | 88 | Debug | list_files | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 1 | 1 | [{"detector": "general_ml", "framework": "General ML", "name": "Hardcoded file path detected: ../input. Consider using configuration files or environment variables.", "fix": "Not specified", "benefits": "Not specified", "location": "Line 12"}] | A | no applicable ML-specific findings | [] | ["Hardcoded file path"] | 0 | A |
1,919 | import sklearn.cross_validation as cv
import sklearn.preprocessing as preprocessing
import sklearn.feature_extraction as fe
import sklearn.ensemble as es | No | 5 | 22 | Environment | import_modules | 244,742 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 6 | A |
1,920 | b"store = pd.read_csv('../input/store.csv')\ntrain = pd.read_csv('../input/train.csv',low_memory=False) # low_memory\ntest = pd.read_csv('../input/test.csv')" | No | 5 | 45 | Data_Extraction | load_from_csv | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,921 | test.fillna(1, inplace=True)
train = train[train["Open"] != 0] | No | 4 | 17 | Data_Transform | correct_missing_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,922 | train = pd.merge(train,store,on='Store')
test = pd.merge(test,store,on='Store') | 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 |
1,923 | sale_means = train.groupby('Store').mean().Sales
sale_means.name = 'Sales=_Means'
train = train.join(sale_means,on='Store')
test = test.join(sale_means,on='Store') | No | 2 | 32 | Data_Transform | merge | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,924 | y = train.Sales.tolist()
train_ = train.drop(['Date','Sales','Store','Customers'],axis=1).fillna(0)
train_dic = train_.fillna(0).to_dict('records')
test_dic = test.drop(["Date","Store","Id"],axis=1).fillna(0).to_dict('records')' | No | 3 | 10 | Data_Transform | drop_column | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,925 | dv = fe.DictVectorizer()
X = dv.fit_transform(train_dic)
Xo = dv.transform(test_dic) | No | 5 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,926 | maxmin = preprocessing.MinMaxScaler()
X = maxmin.fit_transform(X.toarray())
Xo = maxmin.transform(Xo.toarray()) | No | 5 | 18 | Data_Transform | normalization | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,927 | clf = es.RandomForestRegressor(n_estimators=25)
clf.verbose = True
clf.n_jobs = 8
clf | No | 5 | 4 | Model_Train | choose_model_class | 244,742 | 1 | A | 0 | 0 | 0 | 1 | 0 | 4 | ok | 3 | 3 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Randomness Control Checker", "fix": "Set random_state in estimators for reproducibility.", "benefits": "Ensures reproducible results and consistent model behaviour.", "location": "Line 7"}, {"detector": "framework_specific", "framework": "ScikitLe... | B | Randomness Control Checker=low | [{"type": "Randomness Control Checker", "severity": "low"}] | ["Magic number", "Verbose Mode Checker"] | 6 | B |
1,928 | clf.fit(Xtrain,Ytrain)
print ("Training Score :" + str(clf.score(Xtrain,Ytrain)))
print ("Test Score : " + str(clf.score(Xtest,Ytest)) ) | No | 3 | 7 | Model_Train | train_model | 244,742 | 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"] | 6 | B |
1,929 | Yresult = clf.predict(Xtest)
Yresult = np.array(Yresult)
Ytest = np.array(Ytest) | No | 5 | 48 | Model_Evaluation | predict_on_test | 244,742 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 4 | 3 | [{"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 8"}, {"detector": "framework_specific", "framework": "NumPy", "name": "Array Creati... | A | no applicable ML-specific findings | [] | ["Array Creation Efficiency", "Exception Handling Checker", "Unit Testing Checker"] | 6 | A |
1,930 | result = clf.predict(Xo)
output = pd.DataFrame(test.Id).join(pd.DataFrame(result,columns=['Sales']))
output.to_csv('output.csv',index=False) | No | 4 | 25 | Data_Export | save_to_csv | 244,742 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 2 | 2 | [{"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... | A | no applicable ML-specific findings | [] | ["Exception Handling Checker", "Unit Testing Checker"] | 6 | A |
1,931 | import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style('whitegrid')
%matplotlib inline
#
df_train = pd.read_csv("../input/train.csv")
df_store = pd.read_csv("../input/store.csv")
df_test = pd.read_csv("../input/test.csv")
#
df_train['Year'] = df_train['Date']... | No | 3 | 22 | Environment | import_modules | null | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 0 | null |
1,932 | cust_sales = pd.DataFrame()
cust_sales['Customers'] = df_train['Customers']
cust_sales['Sales'] = df_train['Sales']
correlation_matrix = cust_sales.corr().abs()
plt.subplots(figsize=(13, 9))
sns.heatmap(correlation_matrix,annot=True) | No | 3 | 33 | Visualization | distribution | 244,890 | 1 | A | 0 | 0 | 0 | 0 | 0 | 6 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 4 | A |
1,933 | df_train["HolidayBin"] = df_train['StateHoliday'].map({"0": 0, "a": 1, "b": 1, "c": 1})
sns.factorplot(x ="Year", y ="Sales", hue ="Promo", data = df_train,
size = 4, kind ="box", palette ="muted")
sns.factorplot(x ="Year", y ="Sales", hue ="SchoolHoliday", data = df_train,
size =... | No | 5 | 33 | Visualization | distribution | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,934 | #
df_train['StateHoliday'] = df_train['StateHoliday'].replace(0, '0')
df_train["HolidayBin"] = df_train['StateHoliday'].map({"0": 0, "a": 1, "b": 1, "c": 1})
sns.factorplot(x ="Year", y ="Sales", hue ="StateHoliday", data = df_train,
size = 6, kind ="bar", palette ="muted")' | Yes | 3 | 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 |
1,935 | import spacy
nlp = spacy.blank("en")
def get_token_num_by_offset(s, offset):
s_pre = s[:offset]
return len(spacy_tok.tokenizer(s_pre))
# note that 'xxunk' is not special in this sense
special_tokens = ['xxbos','xxfld','xxpad', 'xxmaj','xxup','xxrep','xxwrep']
def adjust_token_num(processed, token_num):
"""
... | 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 |
1,936 | def dataframe_to_tensors(df, max_len=512):
# offsets are: pron_tok_offset, a_tok_offset, a_tok_right_offset, b_tok_offset, b_tok_right_offset
offsets = list()
labels = np.zeros((len(df),), dtype=np.int64)
processed = list()
for i, row in tqdm(df.iterrows()):
try:
text = row["Text"]
a_offset = ... | No | 4 | 12 | Data_Transform | create_dataframe | 3,065,122 | 1 | A | 3 | 3 | 7 | 0 | 15 | 42 | ok | 2 | 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", "Missing function docstring"] | 1 | A |
1,937 | train_ds = TensorDataset(*dataframe_to_tensors(test))
valid_ds = TensorDataset(*dataframe_to_tensors(val))
test_ds = TensorDataset(*dataframe_to_tensors(train)) | No | 4 | 13 | Data_Transform | split | 3,065,122 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | 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"] | 1 | A |
1,938 | train_dl = DataLoader(train_ds, batch_size=64, shuffle=True)
valid_dl = DataLoader(valid_ds, batch_size=32, shuffle=False)
test_dl = DataLoader(test_ds, batch_size=32, shuffle=False) | No | 3 | 45 | Data_Extraction | load_from_csv | 3,065,122 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | 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"] | 1 | A |
1,939 | lm.freeze() | No | 2 | 23 | Environment | set_options | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
1,940 | encoder_hidden_sz = 400
device = torch.device("cuda")
class CorefResolver(nn.Module):
def __init__(self, encoder, dropout_p=0.3):
super(CorefResolver, self).__init__()
self.encoder = encoder
self.dropout = nn.Dropout(dropout_p)
self.hidden2hidden = nn.Linear(encoder_hidden_sz * 2 + 1, 25)
self.h... | Yes | 3 | 23 | Environment | set_options | 3,065,122 | 1 | A | 2 | 4 | 3 | 0 | 10 | 32 | ok | 4 | 4 | [{"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", "Missing class docstring", "Missing function docstring"] | 1 | A |
1,941 | enc = lm.model[0] | 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 |
1,943 | resolver = CorefResolver(enc) | No | 2 | 53 | Other | something_strange | 3,065,122 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | 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"] | 1 | A |
1,944 | resolver.to(device) | No | 3 | 23 | Environment | set_options | 3,065,122 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | 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"] | 1 | A |
1,945 | for param in resolver.encoder.parameters():
param.requires_grad = False | No | 4 | 23 | Environment | set_options | 3,065,122 | 1 | A | 0 | 1 | 1 | 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"] | 1 | A |
1,946 | lr = 0.001
loss_fn = nn.NLLLoss()
optimizer = torch.optim.Adam(resolver.parameters(), lr=lr) | No | 4 | 4 | Model_Train | choose_model_class | 3,065,122 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 2 | 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"] | 1 | A |
1,947 | from sklearn.metrics import classification_report | No | 5 | 22 | Environment | import_modules | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | 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"] | 0 | A |
1,948 | def train_epoch(model, optimizer, train_dl, report_every=10):
model.train()
step = 0
total_loss = 0
for texts, offsets, labels in train_dl:
texts, offsets, labels = texts.to(device), offsets.to(device), labels.to(device)
step += 1
optimizer.zero_grad()
_, loss = model(texts, offsets, labels)
... | Yes | 4 | 2 | Hyperparam_Tuning | find_best_params | 3,065,122 | 1 | A | 5 | 6 | 5 | 1 | 25 | 34 | ok | 7 | 6 | [{"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, No random seed setting detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "No random seed setting detected", "severity": "low"}] | ["Dependent Threshold Checker", "Exception Handling Checker", "Missing function docstring", "Unit Testing Checker"] | 1 | B |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.