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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7,172 | adult['Sex'] = adult['Sex'].transform(lambda x: 1 if x=='Male' else 0 if x==x else x) | No | 5 | 8 | Data_Transform | feature_engineering | 1,554,855 | 3 | C | 1 | 2 | 3 | 1 | 5 | 1 | ok | 3 | 3 | [{"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": "framework_specific", "framework":... | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker", "Exception Handling Checker", "Unit Testing Checker"] | 3 | C |
7,173 | predictions = knn.predict(testAdult[["Age","Education-Num","Capital Gain", "Capital Loss", "Hours per week"]]) | No | 5 | 48 | Model_Evaluation | predict_on_test | 1,554,855 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 3 | 3 | [{"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": "framework_specific", "framework":... | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker", "Exception Handling Checker", "Unit Testing Checker"] | 3 | A |
7,174 | pretrained_model_1 = VGG16(include_top=False, input_shape=t_x.shape[1:]) | No | 5 | 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 |
7,175 | from keras import optimizers
base_model = pretrained_model_1 # Topless
add_model = Sequential()
add_model.add(Flatten(input_shape=base_model.output_shape[1:]))
add_model.add(Dense(256, activation='relu'))
add_model.add(Dense(num_classes, activation='softmax'))
model = Model(inputs=base_model.input, outputs=add_model(... | Yes | 4 | 4 | Model_Train | choose_model_class | 1,617,863 | 1 | A | 0 | 0 | 0 | 0 | 0 | 10 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 4 | A |
7,176 | X_test = pd.DataFrame() | No | 5 | 12 | Data_Transform | create_dataframe | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,177 | X_test['path'] = test_image_paths | No | 5 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,178 | result = np.vstack((testAdult.index.values, predictions)).T
x = ['Id','income']
resultado = pd.DataFrame(columns=x, data=result)
resultado.set_index('Id', inplace=True) | Yes | 3 | 11 | Data_Transform | concatenate | 1,554,855 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | 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"] | 3 | A |
7,179 | X_test['labels'] = X_test['path'].map(lambda x: os.path.splitext(os.path.basename(x))[0]) | No | 5 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,180 | resultado.to_csv('mypredictions.csv') | No | 5 | 25 | Data_Export | save_to_csv | 1,554,855 | 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"] | 3 | A |
7,181 | store = pd.read_csv("../input/store.csv")
train = pd.read_csv("../input/train.csv",parse_dates=[2])
test = pd.read_csv("../input/test.csv",parse_dates=[3]) | No | 5 | 45 | Data_Extraction | load_from_csv | 1,633,570 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 4 | 2 | [{"detector": "general_ml", "framework": "General ML", "name": "No error handling detected in data processing. Consider adding try-except blocks or validation checks for robustness.", "fix": "Not specified", "benefits": "Not specified", "location": ""}, {"detector": "general_ml", "framework": "General ML", "name": "Har... | A | no applicable ML-specific findings | [] | ["Hardcoded file path", "No error handling detected in data processing. Consider adding try-except blocks or validation checks for robustness."] | 3 | A |
7,182 | 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 |
7,183 | submission = pd.DataFrame() | No | 5 | 12 | Data_Transform | create_dataframe | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,184 | # check store nan rows
store.isnull().sum() | No | 5 | 39 | EDA | count_missing_values | 1,633,570 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
7,185 | store.PromoInterval.value_counts() | No | 5 | 72 | EDA | count_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,186 | submission.to_csv("predictions.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 |
7,187 | # fillna in store with 0 has better result than median()
store.fillna(0, inplace=True) | No | 5 | 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 |
7,188 | %matplotlib inline
import warnings
warnings.filterwarnings('ignore')
import os
import gc
import time
import pickle
import feather
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from tqdm._tqdm_notebook import tqdm_notebook as tqdm
tqdm.pandas()
# from tqdm import tqdm
# pd... | No | 4 | 88 | Debug | list_files | null | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 0 | null |
7,189 | train.head().append(train.tail()) | 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 |
7,190 | train.Open.value_counts() | No | 5 | 72 | EDA | count_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,191 | DATA_DIR = '../input/dogs-vs-cats-redux-kernels-edition/'
evals = pd.read_csv('../input/dvc-prepare-evalset/evals.csv')
evals.head() | Yes | 4 | 45 | Data_Extraction | load_from_csv | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,192 | H, W, C = 224, 224, 3 #at least 197
batch_size = 32
eval_batch_size = batch_size * 4 | No | 5 | 77 | Other | define_variables | 1,640,384 | 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"] | 2 | A |
7,193 | # draw store 1 and store 10 sales distribution plot<br>import matplotlib.pyplot as plt<br>store_1 = train.loc[(train["Store"]==1)&(train[\'Sales\']>0), [\'Date\',"Sales"]]<br>store_10 = train.loc[(train["Store"]==10)&(train[\'Sales\']>0), [\'Date\',"Sales"]]<br>f = plt.figure(figsize=(18,10))<br>ax1 = f.add_subplot(211... | No | 5 | 75 | Visualization | time_series | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,194 | import keras.backend as K
from keras.models import Model
from keras.callbacks import ModelCheckpoint, LearningRateScheduler, EarlyStopping
from keras import optimizers, losses, activations, models
from keras.layers import Conv2D, Dense, Input, Flatten, Concatenate, Dropout, Activation
from keras.layers import BatchNorm... | No | 5 | 22 | Environment | import_modules | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 7 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,195 | test.isnull().sum() | No | 5 | 39 | EDA | count_missing_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,196 | # check stores open distribution on days of week
import seaborn as sns
sns.countplot(x = 'DayOfWeek', hue = 'Open', data = test)
plt.title('Store Daily Open Countplot') | No | 5 | 75 | Visualization | time_series | 1,633,570 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
7,197 | # fill missing values in test with 1
test.fillna(value = 1, inplace = True) | No | 5 | 17 | Data_Transform | correct_missing_values | 1,633,570 | 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 5"}] | A | no applicable ML-specific findings | [] | ["InPlace Checker"] | 3 | A |
7,198 | import seaborn as sns
import matplotlib.pyplot as plt
# check distribution of sales in train set
fig = plt.figure(figsize=(12,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
g1 = sns.distplot(train['Sales'],hist = True,label='skewness:{:.2f}'.format(train['Sales'].skew()),ax = ax1)
g1.legend()
g1.set(xlabel ... | No | 5 | 33 | Visualization | distribution | 1,633,570 | 1 | A | 0 | 0 | 0 | 0 | 0 | 12 | 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"] | 3 | B |
7,199 | # process train and test<br>def process(data, isTest = False):<br> # label encode some features<br> mappings = {'0':0, 'a':1, 'b':2, 'c':3, 'd':4}<br> data.StoreType.replace(mappings, inplace=True)<br> data.Assortment.replace(mappings, inplace=True)<br> data.StateHoliday.replace(mappings, inplace=True)<b... | No | 5 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,200 | train_steps = int(np.ceil(train_flow.n / batch_size))
valid_steps = int(np.ceil(valid_flow.n / eval_batch_size))
test_steps = int(np.ceil(test_flow.n / eval_batch_size)) | No | 5 | 77 | Other | define_variables | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,201 | # try random forest
from sklearn.ensemble import RandomForestRegressor
clf = RandomForestRegressor(n_estimators = 15)
clf.fit(x_train, y_train)
# validation
y_pred = clf.predict(x_valid)
error = rmspe(np.expm1(y_valid), np.expm1(y_pred))
print('RMSPE: {:.4f}'.format(error)) | Yes | 3 | 4 | Model_Train | choose_model_class | 1,633,570 | 2 | B | 2 | 0 | 0 | 0 | 10 | 6 | 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, Randomness Control Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Cross-validation not detected", "severity": "low"}, {"type": "No random seed setting detected", "severity": "low"}, {"type": "Randomness Control 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"] | 3 | B |
7,202 | eval_res = pd.DataFrame(history.history)
eval_res.to_csv('eval_res_init.csv', index=False)
for c in ['acc', 'loss']:
eval_res[[c, f'val_{c}']].plot(figsize=[18, 4]);
plt.xlabel('Epoch'); plt.ylabel(c);
plt.title(c); plt.grid(); | Yes | 3 | 56 | Visualization | plot_predictions | 1,640,384 | 1 | A | 0 | 1 | 1 | 0 | 0 | 6 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Threshold Checker", "fix": "Use threshold-independent metrics alongside threshold-dependent ones.", "benefits": "Provides a comprehensive evaluation of model performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker"] | 2 | A |
7,203 | import xgboost as xgb<br><br>params = {"objective": "reg:linear", # for linear regression<br> "booster" : "gbtree", # use tree based models <br> "eta": 0.03, # learning rate<br> "max_depth": 10, # maximum depth of a tree<br> "subsample": 0.9, # Subsample ratio of the traini... | Yes | 4 | 59 | Model_Train | init_hyperparams | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,204 | # validation
y_pred = model.predict(xgb.DMatrix(x_valid))
error = rmspe(np.expm1(y_valid), np.expm1(y_pred))
print('RMSPE: {:.4f}'.format(error))
| Yes | 4 | 48 | Model_Evaluation | predict_on_test | 1,633,570 | 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"] | 3 | A |
7,205 | x_train_total.head().append(x_train_total.tail()) | No | 5 | 11 | Data_Transform | concatenate | 1,633,570 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 3 | 3 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Validation Checker", "fix": "Implement cross-validation techniques for robust model evaluation.", "benefits": "Enhances model performance and reduces overfitting.", "location": ""}, {"detector": "general_ml", "framework": "General ML", "name... | 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"}] | [] | 3 | B |
7,206 | print(x_train_total.shape)
print(y_train_total.shape) | No | 5 | 58 | Debug | show_shape | 1,633,570 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 3 | A |
7,207 | dtrain = xgb.DMatrix(x_train_total, y_train_total)
dtest = xgb.DMatrix(x_test)
# specify parameters via map
params = {"objective": "reg:linear", # for linear regression
"booster" : "gbtree", # use tree based models
"eta": 0.03, # learning rate
"max_depth": 10, # maximum depth of a ... | Yes | 4 | 59 | Model_Train | init_hyperparams | 1,633,570 | 1 | A | 0 | 0 | 0 | 0 | 0 | 14 | 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, 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", "Unit Testing Checker"] | 3 | B |
7,208 | model.load_weights('model.h5') | No | 5 | 30 | Model_Train | load_pretrained | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,209 | DATA_DIR = '../input/dogs-vs-cats-redux-kernels-edition/'
evals = pd.read_csv('../input/dvc-prepare-evalset/evals.csv')
evals['path'] = evals['path'].apply(lambda x: x.replace('../input/', DATA_DIR))
evals.head() | Yes | 4 | 45 | Data_Extraction | load_from_csv | 1,674,761 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 4 | 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"] | 3 | A |
7,210 | H, W, C = 150, 150, 3
batch_size = 32
eval_batch_size = batch_size * 4 | No | 5 | 77 | Other | define_variables | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,211 | import tensorflow as tf
import keras
from keras.preprocessing.image import ImageDataGenerator
train_gen = ImageDataGenerator(
rotation_range=20,
#width_shift_range=0.2,
#height_shift_range=0.2,
shear_range=0.2,
zoom_range=0.2,
#channel_shift_range=0.2,
horizontal_flip=True,
#vertical_fl... | Yes | 3 | 22 | Environment | import_modules | null | 2 | B | 4 | 0 | 0 | 0 | 20 | 13 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 0 | B |
7,212 | eval_res = pd.DataFrame(history.history)
eval_res.to_csv('eval_res_finetune.csv', index=False)
for c in ['acc', 'loss']:
eval_res[[c, f'val_{c}']].plot(figsize=[18, 4]);
plt.xlabel('Epoch'); plt.ylabel(c);
plt.title(c); plt.grid(); | No | 4 | 56 | Visualization | plot_predictions | 1,640,384 | 1 | A | 0 | 1 | 1 | 0 | 0 | 6 | ok | 1 | 1 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Threshold Checker", "fix": "Use threshold-independent metrics alongside threshold-dependent ones.", "benefits": "Provides a comprehensive evaluation of model performance.", "location": ""}] | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker"] | 2 | A |
7,213 | pred_val.shape, valid_flow.classes.shape | No | 5 | 58 | Debug | show_shape | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,214 | n_final_state = 32
def get_model(n_final_state, lr=1e-3, decay=1e-8):
input_shape = (H, W, C)
input_x = Input(shape=input_shape)
c1 = Conv2D(32, (3, 3))(input_x)
c1 = BatchNormalization()(c1)
c1 = Activation('relu')(c1)
c1 = MaxPooling2D((2, 2))(c1)
c2 = Conv2D(32, (3, 3))(c1... | No | 5 | 4 | Model_Train | choose_model_class | 1,674,761 | 1 | A | 1 | 1 | 0 | 0 | 5 | 34 | ok | 4 | 4 | [{"detector": "framework_specific", "framework": "TensorFlow", "name": "Memory Release Checker", "fix": "Clear session after model creation/training using tf.keras.backend.clear_session().", "benefits": "Prevents memory leaks and reduces resource usage.", "location": ""}, {"detector": "framework_specific", "framework":... | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker", "Magic number", "Memory Release Checker", "Missing function docstring"] | 3 | A |
7,215 | train_steps = int(np.ceil(train_flow.n / batch_size))
valid_steps = int(np.ceil(valid_flow.n / eval_batch_size))
test_steps = int(np.ceil(test_flow.n / eval_batch_size))
print(f'train {train_steps} steps')
print(f'valid {valid_steps} steps')
print(f'test {test_steps} steps') | No | 5 | 77 | Other | define_variables | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 6 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,216 | from sklearn.metrics import log_loss, accuracy_score<br>val_loss = log_loss(y_valid, pred_val)<br>val_acc = accuracy_score(y_valid, np.round(pred_val))<br>print(f'valid loss: {val_loss}\\t valid accuracy: {val_acc}') | No | 5 | 49 | Model_Evaluation | compute_test_metric | null | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 0 | null |
7,217 | evals.loc[evals['is_test']==1, 'img_id'].shape | No | 5 | 58 | Debug | show_shape | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,218 | eval_res = pd.DataFrame(history.history)
eval_res.to_csv('eval_res.csv', index=False)
for c in ['acc', 'loss']:
eval_res[[c, f'val_{c}']].plot(figsize=[18, 6]);
plt.xlabel('Epoch'); plt.ylabel(c);
plt.title(c); plt.grid(); | Yes | 3 | 25 | Data_Export | save_to_csv | null | 1 | A | 0 | 1 | 1 | 0 | 0 | 6 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,219 | subname = f'resnet50ft_{val_loss:.6f}.csv'
sub.to_csv(subname, index=False)
print(subname, 'saved') | No | 5 | 25 | Data_Export | save_to_csv | 1,640,384 | 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"] | 2 | A |
7,220 | def predict(model, modelpath, data_flow, steps, workers=4, verbose=1):
model.load_weights(modelpath)
pred = model.predict_generator(
generator=data_flow,
steps=steps,
use_multiprocessing=True if workers>1 else False,
workers=workers,
verbose=verbose
)
return p... | Yes | 3 | 30 | Model_Train | load_pretrained | 1,674,761 | 1 | A | 0 | 2 | 1 | 0 | 0 | 10 | ok | 6 | 5 | [{"detector": "framework_specific", "framework": "TensorFlow", "name": "Memory Release Checker", "fix": "Clear session after model creation/training using tf.keras.backend.clear_session().", "benefits": "Prevents memory leaks and reduces resource usage.", "location": ""}, {"detector": "framework_specific", "framework":... | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker", "Exception Handling Checker", "Memory Release Checker", "Missing function docstring", "Unit Testing Checker"] | 3 | A |
7,221 | train = pd.read_csv('../input/train.csv')
test = pd.read_csv('../input/test.csv') | No | 5 | 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 |
7,222 | from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures | No | 5 | 22 | Environment | import_modules | 1,683,385 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 8 | A |
7,223 | print(pred_val_best.shape, pred_val_best_tta.shape)
sns.distplot(pred_val_best)
sns.distplot(pred_val_best_tta)
plt.legend(['normal', 'fliplr']);
plt.grid(); | Yes | 4 | 33 | Visualization | distribution | 1,674,761 | 1 | A | 0 | 0 | 0 | 0 | 0 | 5 | 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"] | 3 | A |
7,224 | X_train = train[['LotFrontage','LotArea']].fillna(0)
X_test = test[['LotFrontage','LotArea']].fillna(0)
y_train = train['SalePrice'] | Yes | 4 | 17 | Data_Transform | correct_missing_values | 1,683,385 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | 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"}] | [] | 8 | B |
7,225 | from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_squared_error | No | 5 | 22 | Environment | import_modules | 1,683,385 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 8 | A |
7,226 | for i,(p, p_tta) in enumerate(zip(pred_val_li, pred_val_tta_li)):
print(i+2, 'th snapshot normal loss: {:.6f} acc: {:.6f}'.format(
log_loss(y_valid, p),
accuracy_score(y_valid, np.round(p))
))
print(i+2, 'th snapshot tta loss: {:.6f} acc: {:.6f}'.format(
log_loss(y_valid, p_tta),
... | No | 5 | 49 | Model_Evaluation | compute_test_metric | 1,674,761 | 1 | A | 0 | 1 | 1 | 0 | 0 | 9 | ok | 3 | 2 | [{"detector": "framework_specific", "framework": "TensorFlow", "name": "Dependent Threshold Checker", "fix": "Use threshold-independent metrics like AUC.", "benefits": "Provides more robust model evaluation.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Dependent Threshold C... | A | no applicable ML-specific findings | [] | ["Dependent Threshold Checker", "Unit Testing Checker"] | 3 | A |
7,227 | X_meta = pred_val_li + pred_val_tta_li
X_meta = np.hstack(X_meta)
X_meta.shape | Yes | 4 | 11 | Data_Transform | concatenate | 1,674,761 | 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"] | 3 | A |
7,228 | pipe.fit(X_train, y_train) | No | 5 | 7 | Model_Train | train_model | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,229 | preds = pipe.predict(X_test) | No | 5 | 48 | Model_Evaluation | predict_on_test | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,230 | sub = pd.DataFrame({'Id': test.Id, 'SalePrice': preds})
sub.to_csv('submission.csv', index=False) | No | 5 | 25 | Data_Export | save_to_csv | 1,683,385 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 8 | A |
7,231 | from sklearn.linear_model import LogisticRegressionCV
meta_model = LogisticRegressionCV(scoring='neg_log_loss')
meta_model.fit(X_meta, y_valid)
print(meta_model.coef_, meta_model.intercept_) | Yes | 3 | 7 | Model_Train | train_model | 1,674,761 | 1 | A | 1 | 0 | 0 | 0 | 5 | 4 | ok | 9 | 9 | [{"detector": "framework_specific", "framework": "TensorFlow", "name": "Memory Release Checker", "fix": "Clear session after model creation/training using tf.keras.backend.clear_session().", "benefits": "Prevents memory leaks and reduces resource usage.", "location": ""}, {"detector": "framework_specific", "framework":... | C | Cross Validation Checker=low, Scaler Missing Checker=medium | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Scaler Missing Checker", "severity": "medium"}] | ["Dependent Threshold Checker", "Exception Handling Checker", "Logging Checker", "Memory Release Checker", "Model Evaluation Checker", "Unit Testing Checker", "Verbose Mode Checker"] | 3 | C |
7,232 | train = pd.read_csv("../input/comp_train.csv")
test = pd.read_csv("../input/comp_test.csv")
print(train.shape) | Yes | 4 | 45 | Data_Extraction | load_from_csv | 1,699,161 | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 2 | 1 | [{"detector": "general_ml", "framework": "General ML", "name": "Hardcoded file path detected: ../input/comp_train.csv. Consider using configuration files or environment variables.", "fix": "Not specified", "benefits": "Not specified", "location": "Line 3"}, {"detector": "general_ml", "framework": "General ML", "name": ... | A | no applicable ML-specific findings | [] | ["Hardcoded file path"] | 2 | A |
7,233 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline
import cv2
import os | No | 5 | 23 | Environment | set_options | null | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 0 | null |
7,234 | # Fixed for our Cats & Dogs classes
NUM_CLASSES = 2
# Fixed for Cats & Dogs color images
CHANNELS = 3
IMAGE_RESIZE = 224
RESNET50_POOLING_AVERAGE = 'avg'
DENSE_LAYER_ACTIVATION = 'softmax'
OBJECTIVE_FUNCTION = 'categorical_crossentropy'
# Common accuracy metric for all outputs, but can use different metrics for diff... | No | 5 | 77 | Other | define_variables | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 14 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,235 | import matplotlib.pyplot as plt | No | 5 | 22 | Environment | import_modules | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,236 | from tensorflow.python.keras.applications import ResNet50
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense
###
### Below systax is available with TensorFlow 1.11 onwards but this upgrade is not available for Kaggle kernel yet
###
#import tensorflow as tf
#print(tf... | 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 |
7,237 | resnet_weights_path = '../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5' | No | 5 | 77 | Other | define_variables | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,238 | #Still not talking about our train/test data or any pre-processing.
model = Sequential()
# 1st layer as the lumpsum weights from resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5
# NOTE that this layer will be set below as NOT TRAINABLE, i.e., use it as is
model.add(ResNet50(include_top = False, pooling = RESNET50... | No | 5 | 4 | Model_Train | choose_model_class | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,239 | plt.scatter(train["OverallQual"],train["SalePrice"]) | No | 5 | 33 | Visualization | distribution | 1,699,161 | 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"] | 2 | A |
7,240 | plt.scatter(train["TotalBsmtSF"],train["SalePrice"]) | No | 5 | 33 | Visualization | distribution | 1,699,161 | 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"] | 2 | A |
7,241 | plt.scatter(train["YearBuilt"],train["SalePrice"]) | No | 5 | 33 | Visualization | distribution | 1,699,161 | 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"] | 2 | A |
7,242 | X_train = train["TotalBsmtSF"].values
y_train = train["SalePrice"].values
| No | 5 | 21 | Data_Transform | prepare_x_and_y | 1,699,161 | 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"] | 2 | A |
7,244 | fit_history = model.fit_generator(
train_generator,
steps_per_epoch=STEPS_PER_EPOCH_TRAINING,
epochs = NUM_EPOCHS,
validation_data=validation_generator,
validation_steps=STEPS_PER_EPOCH_VALIDATION,
callbacks=[cb_checkpointer, cb_early_stopper]
)
model.load_weights("../wor... | No | 4 | 30 | Model_Train | load_pretrained | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 9 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,245 | import numpy as np
m=train.shape[0]
#changing the shape to ,x1
one=np.ones((m,1))
X_train = X_train.reshape((m,1))
y_train = y_train.reshape((m,1))
X1=np.hstack((X_train,one))
| Yes | 3 | 11 | Data_Transform | concatenate | 1,699,161 | 1 | A | 0 | 0 | 0 | 0 | 0 | 6 | ok | 1 | 1 | [{"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 7"}] | A | no applicable ML-specific findings | [] | ["Array Creation Efficiency"] | 2 | A |
7,246 | plt.figure(1, figsize = (15,8))
plt.subplot(221)
plt.plot(fit_history.history['acc'])
plt.plot(fit_history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'valid'])
plt.subplot(222)
plt.plot(fit_history.history['loss'])
plt.plo... | No | 5 | 35 | Visualization | learning_history | null | 1 | A | 0 | null | 0 | 0 | 0 | null | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,247 | TRAIN_PATH = os.path.join("../input/ai-academy-intermediate-class-competition-1", "BBC News Train.csv")
#Load the data using pandas : Create a DataFrame named df, that contains the training data
df = pd.read_csv(TRAIN_PATH) | No | 5 | 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 |
7,248 | X_test=test.iloc[:,1:].values
m_test=X_test.shape[0]
one=np.ones((m_test,1))
X_test=np.hstack((X_test,one)) | Yes | 3 | 11 | Data_Transform | concatenate | 1,699,161 | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 1 | 1 | [{"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 5"}] | A | no applicable ML-specific findings | [] | ["Array Creation Efficiency"] | 2 | A |
7,249 | # List first 5 entries in dataframe to make sure it was loaded properly
# and review the various colums in the dataframe
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 |
7,250 | # Associate Category names with numerical index and save it in new column category_id
df['category_id'] = df['Category'].factorize()[0]
#View first 10 entries of category_id, as a sanity check
df['category_id'][0:10] | No | 5 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,251 | prediction=np.dot(X_test,theta)
prediction | No | 5 | 48 | Model_Evaluation | predict_on_test | 1,699,161 | 1 | A | 0 | 0 | 0 | 1 | 0 | 2 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 2 | A |
7,252 | # Create a new pandas dataframe "category_id_df", which only has unique Categories, also sorting this list in order of category_id values<br>category_id_df = df[[\'Category\', \'category_id\']].drop_duplicates().sort_values(\'category_id\') | No | 5 | 9 | Data_Transform | sort_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 0 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,253 | sub=pd.DataFrame()<br>sub[\'Id\'] = test[\'Id\']<br>sub[\'SalePrice\']=prediction<br>sub.to_csv("prediction.csv", index = False) | Yes | 4 | 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 |
7,254 | # Create a dictionary ( python datastructure - like a lookup table) that
# can easily convert category names into category_ids and vice-versa
category_to_id = dict(category_id_df.values)
id_to_category = dict(category_id_df[['category_id', 'Category']].values) | No | 5 | 77 | Other | define_variables | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,255 | print(prediction.shape) | No | 5 | 58 | Debug | show_shape | 1,699,161 | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | ok | 0 | 0 | [] | A | no applicable ML-specific findings | [] | [] | 2 | A |
7,256 | # Pick 5 random samples from the dataframe
df.sample(5, random_state=0) | 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 |
7,257 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
RANDOM_STATE = 31415 | Yes | 4 | 22 | Environment | import_modules | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 5 | ok | 1 | 1 | [{"detector": "general_ml", "framework": "General ML", "name": "Magic number detected: 31415", "fix": "Not specified", "benefits": "Not specified", "location": "Line 7"}] | A | no applicable ML-specific findings | [] | ["Magic number"] | 0 | A |
7,258 | # Group the dataframe by categories and count items ( number of news articles) in each category
df.groupby('Category').category_id.count()
| No | 5 | 72 | EDA | count_values | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,259 | #Plot the distribution of news articles by category
df.groupby('Category').category_id.count().plot.bar(ylim=0) | No | 5 | 33 | Visualization | distribution | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,260 | from sklearn.feature_extraction.text import TfidfVectorizer
tfidf = TfidfVectorizer(sublinear_tf=True, min_df=5, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english')
features = tfidf.fit_transform(df.Text).toarray() # Remaps the words in the 1490 articles in the text column of
... | No | 5 | 8 | Data_Transform | feature_engineering | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 4 | ok | 9 | 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... | D | Cross Validation Checker=low, Data Leakage Checker=high, No random seed setting detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Data Leakage Checker", "severity": "high"}, {"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"] | 0 | D |
7,261 | #Get a feel of the features identified by tfidf
features.shape # How many features are there ? | No | 5 | 58 | Debug | show_shape | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,262 | # metric to optimize
from sklearn.metrics import mean_squared_error
from sklearn.metrics import make_scorer
scorer = make_scorer(lambda y_test, predictions: np.sqrt(mean_squared_error(y_test, predictions))) | Yes | 4 | 49 | Model_Evaluation | compute_test_metric | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 3 | ok | 1 | 1 | [{"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": ""}] | A | no applicable ML-specific findings | [] | ["Unit Testing Checker"] | 0 | A |
7,263 | colors = [\'pink\', \'green\', \'midnightblue\', \'orange\', \'darkgrey\']<br><br># Find points belonging to each category and plot them<br>for category, category_id in sorted(category_to_id.items()):<br> points = projected_features[(labels[indices] == category_id).values]<br> plt.scatter(points[:, 0], points[:, ... | 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 |
7,264 | training_set = pd.read_csv('../input/train.csv')
training_set['datetime'] = training_set['datetime'].apply(lambda x: pd.to_datetime(x).timestamp()) | Yes | 4 | 45 | Data_Extraction | load_from_csv | 1,814,363 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | ok | 3 | 3 | [{"detector": "framework_specific", "framework": "Pandas", "name": "Column Selection Checker", "fix": "Select necessary columns after importing DataFrame.", "benefits": "Clarifies data usage and improves performance.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Cross Valida... | B | Cross Validation Checker=low | [{"type": "Cross Validation Checker", "severity": "low"}] | ["Column Selection Checker", "Hardcoded file path"] | 6 | B |
7,265 | features.shape | No | 5 | 58 | Debug | show_shape | null | 1 | A | 0 | 0 | 0 | 0 | 0 | 1 | no_ml_import | 0 | 0 | [] | null | no_ml_import | [] | [] | 0 | null |
7,266 | training_set.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 |
7,267 | from sklearn.model_selection import train_test_split
# Basic preprocessing which applies to all regression techniques (dependent variable: casual)
data = training_set.drop(columns = ['registered', 'count'])
X_train, X_test, y_train, y_test = train_test_split(data, data.casual, test_size=0.2, random_state = RANDOM_STA... | Yes | 3 | 13 | Data_Transform | split | 1,814,363 | 1 | A | 0 | 0 | 0 | 0 | 0 | 5 | 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": "general_ml", "framework": "General ML", "name... | B | Cross Validation Checker=low, Cross-validation not detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Cross-validation not detected", "severity": "low"}] | [] | 6 | B |
7,268 | from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV
?np.random.uniform | No | 5 | 84 | Other | not_enough_vertices | 1,814,363 | 1 | A | 0 | null | 0 | 0 | 0 | null | invalid_python | 0 | 0 | [] | null | invalid_python | [] | [] | 6 | null |
7,269 | casual_model.fit(X_train, y_train)
casual_model = casual_model.best_estimator_ | Yes | 4 | 7 | Model_Train | train_model | 1,814,363 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | 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 |
7,270 | # Same thing for the second variable
# Basic preprocessing which applies to all regression techniques (dependent variable: casual)
data = training_set.drop(columns = ['casual', 'count'])
X_train, X_test, y_train, y_test = train_test_split(data, data.registered, test_size=0.2, random_state = RANDOM_STATE)
X_train = X_t... | Yes | 3 | 13 | Data_Transform | split | 1,814,363 | 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": "general_ml", "framework": "General ML", "name... | B | Cross Validation Checker=low, Cross-validation not detected=low | [{"type": "Cross Validation Checker", "severity": "low"}, {"type": "Cross-validation not detected", "severity": "low"}] | [] | 6 | B |
7,271 | registered_model.fit(X_train, y_train)
registered_model = registered_model.best_estimator_ | Yes | 4 | 7 | Model_Train | train_model | 1,814,363 | 1 | A | 0 | 0 | 0 | 0 | 0 | 2 | 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 |
7,272 | from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import MultinomialNB
from sklearn.model_selection import cross_val_score
models = [
RandomForestClassifier(n_estimators=200, max_depth=3, random_state=0),
MultinomialNB(),
Logi... | Yes | 4 | 82 | Hyperparam_Tuning | define_search_model | null | 1 | A | 1 | 0 | 0 | 0 | 5 | 9 | ok | 2 | 2 | [{"detector": "framework_specific", "framework": "ScikitLearn", "name": "Scaler Missing Checker", "fix": "Apply scaling before scaling-sensitive operations.", "benefits": "Improves model performance and accuracy.", "location": ""}, {"detector": "framework_specific", "framework": "ScikitLearn", "name": "Verbose Mode Che... | C | Scaler Missing Checker=medium | [{"type": "Scaler Missing Checker", "severity": "medium"}] | ["Verbose Mode Checker"] | 0 | C |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.