kernel_id int64 24.2k 23.3M | prompt stringlengths 8 1.85M | completetion stringlengths 1 182k | comp_name stringlengths 5 57 |
|---|---|---|---|
9,034,271 | ts = time.time()
matrix = target_encoding(matrix, ['date_block_num'], 'item_cnt_month', 'date_avg_item_cnt', [1])
matrix = target_encoding(matrix, ['date_block_num', 'item_id'], 'item_cnt_month', 'date_item_avg_item_cnt', [1,2,3,6,12])
matrix = target_encoding(matrix, ['date_block_num', 'shop_id'], 'item_cnt_month', ... | def make_random_forest(X_train, y_train):
randomforest = RandomForestClassifier(n_estimators=100,random_state=0)
gridsearch = GridSearchCV(randomforest,param_grid={'n_estimators':[60], 'max_depth':[2,3,7], \
'max_leaf_nodes':[100,300,500],'random_state':[0]}, cv=10,return_train_score=True, iid=True)\
.fit(X_train, y_... | Titanic - Machine Learning from Disaster |
9,034,271 | ts = time.time()
group = train.groupby(['item_id'] ).agg({'item_price': ['mean']})
group.columns = ['item_avg_item_price']
group.reset_index(inplace=True)
matrix = pd.merge(matrix, group, on=['item_id'], how='left')
matrix['item_avg_item_price'] = matrix['item_avg_item_price'].astype(np.float16)
group = train.group... | randomforest, gridsearch = make_random_forest(X_train_standardized, y_train)
pd.DataFrame(gridsearch.cv_results_)\
.loc[:,['params','mean_test_score','mean_train_score','rank_test_score']]\
.sort_values(by='rank_test_score' ).head(3)
print('Setting randomforest to {}'.format(gridsearch.best_params_)) | Titanic - Machine Learning from Disaster |
9,034,271 | ts = time.time()
group = train.groupby(['date_block_num','shop_id'] ).agg({'revenue': ['sum']})
group.columns = ['date_shop_revenue']
group.reset_index(inplace=True)
matrix = pd.merge(matrix, group, on=['date_block_num','shop_id'], how='left')
matrix['date_shop_revenue'] = matrix['date_shop_revenue'].astype(np.float... | randomforest_index_class1 = np.where(randomforest.classes_==1)[0][0]
randomforest_predictions = randomforest.predict(X_test_standardized)
randomforest_probas = randomforest.predict_proba(X_test_standardized)[:,probas_index_class1]
randomforest_accuracy = randomforest.score(X_test_standardized,y_test)
randomforest_cro... | Titanic - Machine Learning from Disaster |
9,034,271 | matrix['month'] = matrix['date_block_num'] % 12
matrix['year'] =(matrix['date_block_num'] / 12 ).astype(np.int8 )<create_dataframe> | write_model_results('RandomForest', randomforest_accuracy, randomforest_crossvalscores, randomforest_predictions,
y_test ) | Titanic - Machine Learning from Disaster |
9,034,271 | ts = time.time()
last_sale = pd.DataFrame()
for month in range(1,35):
last_month = matrix.loc[(matrix['date_block_num']<month)&(matrix['item_cnt_month']>0)].groupby(['item_id','shop_id'])['date_block_num'].max()
df = pd.DataFrame({'date_block_num':np.ones([last_month.shape[0],])*month,
'item_id': last_month.index.get_l... | def make_deep_model(num_features):
num_input_features = num_features
num_hidden_neurons = 13
deep_model = tf.keras.models.Sequential([
tf.keras.layers.Dense(num_input_features, activation='relu'),
tf.keras.layers.Dense(num_hidden_neurons, activation='sigmoid'),
tf.keras.layers.Dropout(rate=0.2, seed=0),
tf.keras.layers... | Titanic - Machine Learning from Disaster |
9,034,271 | ts = time.time()
last_sale = pd.DataFrame()
for month in range(1,35):
last_month = matrix.loc[(matrix['date_block_num']<month)&(matrix['item_cnt_month']>0)].groupby('item_id')['date_block_num'].max()
df = pd.DataFrame({'date_block_num':np.ones([last_month.shape[0],])*month,
'item_id': last_month.index.values,
'item_las... | deep_model = make_deep_model(num_features=X_train_standardized.shape[1] ) | Titanic - Machine Learning from Disaster |
9,034,271 | ts = time.time()
matrix['item_shop_first_sale'] = matrix['date_block_num'] - matrix.groupby(['item_id','shop_id'])['date_block_num'].transform('min')
matrix['item_first_sale'] = matrix['date_block_num'] - matrix.groupby('item_id')['date_block_num'].transform('min')
time.time() - ts<load_pretrained> | deep_model_history = deep_model.fit(x=X_train_standardized, y=y_train, epochs=40, verbose=0, validation_split=.1 ) | Titanic - Machine Learning from Disaster |
9,034,271 | matrix.to_pickle('data.pkl')
del matrix
del group
del items
del shops
del cats
del train
gc.collect() ;<load_pretrained> | deep_probas = deep_model.predict(X_test_standardized)[:, 1]
deep_predictions = deep_probas.copy()
deep_predictions[deep_predictions<.5] = 0
deep_predictions[deep_predictions>=.5] = 1
deep_predictions=deep_predictions.astype('int')
deep_accuracy = deep_model.evaluate(x=X_test_standardized, y=y_test, verbose=0)[1]
deep_... | Titanic - Machine Learning from Disaster |
9,034,271 | data = pd.read_pickle('./data.pkl')
data.head()<create_dataframe> | write_model_results('DeepModel', deep_accuracy, deep_crossvalscores, deep_predictions, y_test ) | Titanic - Machine Learning from Disaster |
9,034,271 | data = data[[
'date_block_num',
'shop_id',
'item_cnt_month',
'city_code',
'item_category_id',
'type_code','subtype_code',
'item_cnt_month_lag_1','item_cnt_month_lag_2','item_cnt_month_lag_3','item_cnt_month_lag_6','item_cnt_month_lag_12',
'item_avg_sale_last_6', 'item_std_sale_last_6',
'item_avg_sale_last_12', 'item_st... | train['PctLived'] = train_copy.PctLived
X_train, y_train = train.loc[:, train.columns!='Survived'], train.loc[:,'Survived']
feature_importances = drop_column_feature_importances(X_train, y_train ) | Titanic - Machine Learning from Disaster |
9,034,271 | X_train = data[data.date_block_num < 33].drop(['item_cnt_month'], axis=1)
Y_train = data[data.date_block_num < 33]['item_cnt_month']
X_valid = data[data.date_block_num == 33].drop(['item_cnt_month'], axis=1)
Y_valid = data[data.date_block_num == 33]['item_cnt_month']
X_test = data[data.date_block_num == 34].drop(['it... | allmodels_predictions = [adaboost_predictions, logit_predictions, randomforest_predictions, deep_predictions]
ada_rf_deep_predictions = [adaboost_predictions, randomforest_predictions, deep_predictions]
all_no_deep_predictions = [adaboost_predictions, logit_predictions, randomforest_predictions]
voted_allmodels_predict... | Titanic - Machine Learning from Disaster |
9,034,271 | sys.version_info<train_model> | voted_allmodels_accuracy = len(np.where(voted_allmodels_predictions==y_test)[0])/y_test.size
voted_ada_rf_deep_accuracy = len(np.where(voted_ada_rf_deep_predictions==y_test)[0])/y_test.size
voted_all_no_deep_accuracy = len(np.where(voted_all_no_deep_predictions==y_test)[0])/y_test.size | Titanic - Machine Learning from Disaster |
9,034,271 | ts = time.time()
model = LGBMRegressor(
max_depth = 8,
n_estimators = 500,
colsample_bytree=0.7,
min_child_weight = 300,
reg_alpha = 0.1,
reg_lambda = 1,
random_state = 42,
)
model.fit(
X_train,
Y_train,
eval_metric="rmse",
eval_set=[(X_train, Y_train),(X_valid, Y_valid)],
verbose=10,
early_stopping_rounds = 40,
ca... | write_model_results('Voted_AllModels', voted_allmodels_accuracy, np.array(0), voted_allmodels_predictions, y_test)
write_model_results('Voted_Ada_Rf_Deep', voted_ada_rf_deep_accuracy, np.array(0), voted_ada_rf_deep_predictions, y_test)
write_model_results('Voted_All_No_Deep', voted_all_no_deep_accuracy, np.array(0), ... | Titanic - Machine Learning from Disaster |
9,034,271 | Y_pred = model.predict(X_valid ).clip(0, 20)
Y_test = model.predict(X_test ).clip(0, 20)
X_train_level2 = pd.DataFrame({
"ID": np.arange(Y_pred.shape[0]),
"item_cnt_month": Y_pred
})
X_train_level2.to_csv('lgb_valid.csv', index=False)
submission = pd.DataFrame({
"ID": np.arange(Y_test.shape[0]),
"item_cnt_month": Y... | del model_results
model_successes = np.zeros(len(X_full))
model_results_initial_features_no_pct_lived = cross_validate_entire_process(k=10)
model_results_initial_features_no_pct_lived | Titanic - Machine Learning from Disaster |
9,034,271 | np.random.seed(233333 )<load_pretrained> | del model_results
model_successes = np.zeros(len(X_full))
model_results_initial_features_with_pct_lived = cross_validate_entire_process(k=10,ticket_survival_feature=True)
model_results_initial_features_with_pct_lived | Titanic - Machine Learning from Disaster |
9,034,271 | data = pd.read_pickle('data.pkl')
data = data[[
'date_block_num',
'item_cnt_month',
'item_cnt_month_lag_1','item_cnt_month_lag_2','item_cnt_month_lag_3','item_cnt_month_lag_6','item_cnt_month_lag_12',
'item_avg_sale_last_6', 'item_std_sale_last_6',
'item_avg_sale_last_12', 'item_std_sale_last_12',
'shop_avg_sale_last_... | train_survived, test_survived = get_ticket_survival_arrays()
train_copy['PctLived'] = train_survived
train_copy['model_successes'] = model_successes
train_copy.loc[:, 'model_successes'] = train_copy.loc[:, 'model_successes'].astype('int' ) | Titanic - Machine Learning from Disaster |
9,034,271 | def Sales_prediction_model(input_shape):
in_layer = Input(input_shape)
x = Dense(16,kernel_initializer='RandomUniform', kernel_regularizer=l2(0.02), activation = "relu" )(in_layer)
x = Dense(8, kernel_initializer='RandomUniform', kernel_regularizer=l2(0.02), activation = "relu" )(x)
x = Dense(1, kernel_initializer='... | test['CabinLetter'] = test['Cabin'].fillna('X' ).apply(lambda x:x[0] ) | Titanic - Machine Learning from Disaster |
9,034,271 | Y_pred = model.predict(X_valid ).clip(0, 20)[:,0]
Y_test = model.predict(X_test ).clip(0, 20)[:,0]
X_train_level2 = pd.DataFrame({
"ID": np.arange(Y_pred.shape[0]),
"item_cnt_month": Y_pred
})
X_train_level2.to_csv('nn_valid.csv', index=False)
submission = pd.DataFrame({
"ID": np.arange(Y_test.shape[0]),
"item_cnt_mo... | test['Title']=test['Name'].str.extract(r'^.+,\s (.{0,12}\.) ',expand=False)
test.loc[test.Title.isin(['Mlle.','Ms.']),'Title'] = 'Miss.'
test.loc[test.Title.isin(['Capt.','Col.','Jonkheer.','Major.']),'Title'] = 'Officer.'
test.loc[test.Title.isin(['Lady.','Sir.','the Countess.']),'Title'] = 'Aristocrat.'
test.loc[tes... | Titanic - Machine Learning from Disaster |
9,034,271 | sys.version_info<train_model> | for title in test['Title'].unique() :
nans = test.loc[(test['Title']==title)&(test['Age'].isna())]
non_nan_sample = train_ages.loc[train_ages['Title']==title,'Age'].dropna().sample(n=len(nans), \
replace=False, \
random_state=0 ).values
test.loc[nans.index,'Age'] = non_nan_sample | Titanic - Machine Learning from Disaster |
9,034,271 | ts = time.time()
model = XGBRegressor(
max_depth=7,
n_estimators=1000,
min_child_weight=300,
colsample_bytree=0.8,
subsample=0.8,
gamma = 0.005,
eta=0.1,
seed=42)
model.fit(
X_train,
Y_train,
eval_metric="rmse",
eval_set=[(X_train, Y_train),(X_valid, Y_valid)],
verbose=10,
early_stopping_rounds = 40,
)
time.time()... | test.loc[:, 'AgeGroup'] = test.loc[:, 'Age'].transform(code_age_group ) | Titanic - Machine Learning from Disaster |
9,034,271 | Y_pred = model.predict(X_valid ).clip(0, 20)
Y_test = model.predict(X_test ).clip(0, 20)
X_train_level2 = pd.DataFrame({
"ID": np.arange(Y_pred.shape[0]),
"item_cnt_month": Y_pred
})
X_train_level2.to_csv('xgb_valid.csv', index=False)
submission = pd.DataFrame({
"ID": np.arange(Y_test.shape[0]),
"item_cnt_month": Y... | test['Fare']=test['Fare'].fillna(0 ) | Titanic - Machine Learning from Disaster |
9,034,271 | import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import Ridge, LinearRegression
import gc<prepare_x_and_y> | test['Embarked']=test['Embarked'].fillna('S' ) | Titanic - Machine Learning from Disaster |
9,034,271 | data = pd.read_pickle('data.pkl')
Y_train_level2 = data[data.date_block_num == 33]['item_cnt_month']
del data
gc.collect()<load_from_csv> | test['TicketStub']=test['Ticket'].str.extract(r'([A-Za-z///.]+)',expand=False)
test['TicketStub']=test['TicketStub'].fillna('numeric:'+ test['Ticket'].str.len().astype('str'))
test['TicketStub']=test['TicketStub'].str.replace('.','' ).str.upper()
test.loc[test.groupby('TicketStub')['PassengerId'].transform(len)<=5,'Ti... | Titanic - Machine Learning from Disaster |
9,034,271 | X_train_level2 = pd.DataFrame()
df = pd.read_csv('./lgb_valid.csv')
X_train_level2['lgb'] = df['item_cnt_month']
df = pd.read_csv('./xgb_valid.csv')
X_train_level2['xgb'] = df['item_cnt_month']
df = pd.read_csv('./nn_valid.csv')
X_train_level2['nn'] = df['item_cnt_month']
X_test_level2 = pd.DataFrame()
df = pd.read_... | test['FamilySize'] = test['SibSp'].add(test['Parch'])+1
test.loc[:,'TicketSize'] = test.loc[:,'Ticket'].map(passengers_per_ticket)
test.loc[:,'FamilySize'] = test.loc[:,['FamilySize','TicketSize']].max(axis=1)
test['FamilySize_Code'] = test['FamilySize'].apply(encode_family_size ) | Titanic - Machine Learning from Disaster |
9,034,271 | best_alpha = 1;
best_rmse = 100;
for alpha in np.arange(0,1,0.02):
Y_pred_level2 = alpha*X_train_level2['lgb'] +(1-alpha)*X_train_level2['xgb']
rmse = np.sqrt(mean_squared_error(Y_train_level2, Y_pred_level2))
if(rmse<best_rmse):
best_rmse = rmse
best_alpha = alpha
Y_test_level2 = best_alpha*X_test_level2['lgb'] +(1-be... | train_survival, test_survival = get_ticket_survival_arrays()
test.loc[:,'PctLived'] = test_survival
train_with_dummies.loc[:,'PctLived'] = train_survival | Titanic - Machine Learning from Disaster |
9,034,271 | import numpy as np
import pandas as pd
import scipy
import sklearn
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OrdinalEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_squared_error
from itertool... | test_passenger_ids = test.PassengerId | Titanic - Machine Learning from Disaster |
9,034,271 | dpath = '.. /input/competitive-data-science-predict-future-sales/'
adpath ='.. /input/predict-future-sales/'<load_from_csv> | use_columns = ['Pclass','Sex','Title','CabinLetter','Age','TicketStub','FamilySize_Code','Fare','Embarked','PctLived','Survived']
drop_columns = set(test.columns)- set(use_columns)
test.drop(drop_columns, axis=1,inplace=True)
test.columns | Titanic - Machine Learning from Disaster |
9,034,271 | df_train = pd.read_csv(dpath + 'sales_train.csv')
df_test = pd.read_csv(dpath + 'test.csv', index_col='ID')
df_shops = pd.read_csv(dpath + 'shops.csv', index_col='shop_id')
df_items = pd.read_csv(dpath + 'items.csv', index_col='item_id')
df_itemcat = pd.read_csv(dpath + 'item_categories.csv', index_col='item_catego... | non_convertible_columns = \
test.columns[(test.dtypes == 'float64')|(test.dtypes == 'category')|(test.columns=='Survived')]
convertible_columns = set(test.columns)- set(non_convertible_columns)
for column in convertible_columns:
test[column] = pd.Categorical(test[column] ) | Titanic - Machine Learning from Disaster |
9,034,271 | calendar = pd.read_csv(adpath + 'calendar.csv', dtype='int16' )<categorify> | test_with_dummies=pd.get_dummies(test,drop_first=True ) | Titanic - Machine Learning from Disaster |
9,034,271 | def shop_name2city(sn):
sn = sn.split() [0]
if sn == 'Цифровой' or sn == 'Интернет-магазин': sn = 'Internet'
if sn[0] == '!': sn = sn[1:]
return sn
df_shops['city'] = df_shops['shop_name'].apply(shop_name2city)
df_shops['city_enc'] = LabelEncoder().fit_transform(df_shops['city'] ).astype('int8')
city_info = pd.read_p... | missing_cols = set(train_with_dummies.columns)- set(test_with_dummies.columns)
for c in missing_cols:
test_with_dummies[c] = 0
test_with_dummies = test_with_dummies[train_with_dummies.columns] | Titanic - Machine Learning from Disaster |
9,034,271 | class Items() :
def __init__(self, df_items, df_itemcat):
self.df_items = df_items
self.df_itemcat = df_itemcat
self.set_hl_cat()
self.make_items_ext()
self.item_features = ['item_category_id', 'hl_cat_id']
def set_hl_cat(self):
self.df_itemcat['hl_cat_id'] = self.df_itemcat['item_category_name'].str.split(n=1, expand=... | X_full = np.array(train_with_dummies.loc[:,(train_with_dummies.columns !='Survived')])
test_array = np.array(test_with_dummies.loc[:,(test_with_dummies.columns !='Survived')] ) | Titanic - Machine Learning from Disaster |
9,034,271 | items = Items(df_items, df_itemcat )<prepare_output> | full_scaler = preprocessing.StandardScaler().fit(X_full)
X_full_standardized = full_scaler.transform(X_full)
test_array = full_scaler.transform(test_array ) | Titanic - Machine Learning from Disaster |
9,034,271 | class TT_Extended() :
def __init__(self, df_train, df_test, items, df_shops, calendar, cmode, verbose=True):
self.info = verbose
self.df_train = df_train.copy()
self.df_test = df_test.copy()
self.df_shops = df_shops.copy()
self.calendar = self.set_calender(calendar.copy())
self.idx_columns = ['date_block_num', 'shop_i... | _=logitmodel.fit(X_full_standardized, y_full)
logit_predictions = logitmodel.predict(test_array)
_=adaboost.fit(X_full_standardized, y_full)
adaboost_predictions = adaboost.predict(test_array)
_=randomforest.fit(X_full_standardized, y_full)
randomforest_predictions = randomforest.predict(test_array)
deep_model = ... | Titanic - Machine Learning from Disaster |
9,034,271 | %%time
pfs = TT_Extended(df_train, df_test, items, df_shops, calendar, cmode='total' )<set_options> | potential_submissions = dict([('LogisticRegression',logit_predictions),\
('AdaBoost',adaboost_predictions),\
('RandomForest',randomforest_predictions),\
('DeepModel',deep_predictions),\
('Voted_AllModels',voted_allmodels_predictions),\
('Voted_Ada_Rf_Deep',voted_ada_rf_deep_predictions),\
('Voted_All_No_Deep',vot... | Titanic - Machine Learning from Disaster |
9,034,271 | <drop_column><EOS> | timestamp = datetime.today().strftime('%y%m%d_%H%M')
submission_df = pd.DataFrame()
submission_df['PassengerId'] = test_passenger_ids
for i in range(5):
model = model_results_initial_features_with_pct_lived.data.index[i]
submission_df['Survived'] = potential_submissions[model]
file_name = model + '_' + timestamp + '.c... | Titanic - Machine Learning from Disaster |
7,770,915 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<prepare_x_and_y> | print("pandas version: {}".format(pd.__version__))
print("NumPy version: {}".format(np.__version__))
print("matplotlib version: {}".format(matplotlib.__version__))
print("seaborn version: {}".format(sns.__version__))
print("scikit-learn version: {}".format(sklearn.__version__))
print("statsmodels version: {}".format(st... | Titanic - Machine Learning from Disaster |
7,770,915 | X_train = df_work[df_work.date_block_num < 33].drop(['item_cnt_month'], axis=1)
y_train = df_work[df_work.date_block_num < 33]['item_cnt_month']
X_valid = df_work[df_work.date_block_num == 33].drop(['item_cnt_month'], axis=1)
y_valid = df_work[df_work.date_block_num == 33]['item_cnt_month']
X_test = df_work[df_work.d... | from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn import feature_selection
from sklearn import model_selection
from sklearn import metrics
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import seaborn as sns | Titanic - Machine Learning from Disaster |
7,770,915 | del df_work<init_hyperparams> | data = pd.read_csv(".. /input/titanic/train.csv")
data_val = pd.read_csv(".. /input/titanic/test.csv")
data1 = data.copy(deep = True)
data_cleaner = [data1, data_val] | Titanic - Machine Learning from Disaster |
7,770,915 | %%time
feature_names = X_train.columns.tolist()
params = {
'objective': 'mse',
'metric': 'rmse',
'num_leaves': 255,
'learning_rate': 0.005,
'feature_fraction': 0.75,
'bagging_fraction': 0.75,
'bagging_freq': 5,
'seed': 1,
'verbose': 1,
'force_row_wise' : True
}
categorical_feature_names = [
'item_category_id',
'hl_cat_... | print(data1.isnull().sum())
print("-"*10)
print(data_val.isnull().sum() ) | Titanic - Machine Learning from Disaster |
7,770,915 | sample_submission['item_cnt_month'] = gbm.predict(X_test[feature_names] ).clip(0, 20)
sample_submission.to_csv('submission_k_l3_1.csv' )<set_options> | for dataset in data_cleaner:
dataset['Age'].fillna(dataset['Age'].median() , inplace = True)
dataset['Embarked'].fillna(dataset['Embarked'].mode() [0], inplace = True)
dataset['Fare'].fillna(dataset['Fare'].median() , inplace = True)
dataset.drop('Cabin', axis=1, inplace=True ) | Titanic - Machine Learning from Disaster |
7,770,915 | le = LabelEncoder()
pd.set_option('display.max_rows', 400)
pd.set_option('display.max_columns', 160)
pd.set_option('display.max_colwidth', 40)
warnings.filterwarnings("ignore" )<load_from_csv> | print(data1.isnull().sum())
print("-"*10)
print(data_val.isnull().sum() ) | Titanic - Machine Learning from Disaster |
7,770,915 | test = pd.read_csv('.. /input/competitive-data-science-predict-future-sales/test.csv')
test.head()<load_from_csv> | varlist = ['Sex']
def binary_map(x):
return x.map({'male': 1, "female": 0})
for dataset in data_cleaner:
dataset[varlist] = dataset[varlist].apply(binary_map ) | Titanic - Machine Learning from Disaster |
7,770,915 | categories = pd.read_csv('.. /input/predict-future-sales-eng-translation/categories.csv')
pd.DataFrame(categories.category_name.values.reshape(-1, 4))<categorify> | dummy1 = pd.get_dummies(data1['Embarked'], prefix='Embarked', drop_first=True)
data1 = pd.concat([data1, dummy1], axis=1 ) | Titanic - Machine Learning from Disaster |
7,770,915 | categories['group_name'] = categories['category_name'].str.extract(r'(^[\w\s]*)')
categories['group_name'] = categories['group_name'].str.strip()
categories['group_id'] = le.fit_transform(categories.group_name.values)
categories.sample(5 )<load_from_csv> | dummy1 = pd.get_dummies(data_val['Embarked'], prefix='Embarked', drop_first=True)
data_val = pd.concat([data_val, dummy1], axis=1 ) | Titanic - Machine Learning from Disaster |
7,770,915 | items = pd.read_csv('.. /input/predict-future-sales-eng-translation/items.csv')
items['item_name'] = items['item_name'].str.lower()
items['item_name'] = items['item_name'].str.replace('.', '')
for i in [r'[^\w\d\s\.]', r'\bthe\b', r'\bin\b', r'\bis\b',
r'\bfor\b', r'\bof\b', r'\bon\b', r'\band\b',
r'\bto\b', r'\bwith... | dummy1 = pd.get_dummies(data1['Pclass'], prefix='Pclass', drop_first=True)
data1 = pd.concat([data1, dummy1], axis=1 ) | Titanic - Machine Learning from Disaster |
7,770,915 | dupes = items[(items.duplicated(subset=['item_name','category_id'],keep=False)) ]
dupes['in_test'] = dupes.item_id.isin(test.item_id.unique())
dupes = dupes.groupby('item_name' ).agg({'item_id':['first','last'],'in_test':['first','last']})
dupes = dupes[(dupes[('in_test', 'first')]==False)|(dupes[('in_test', 'last')]... | dummy1 = pd.get_dummies(data_val['Pclass'], prefix='Pclass', drop_first=True)
data_val = pd.concat([data_val, dummy1], axis=1 ) | Titanic - Machine Learning from Disaster |
7,770,915 | sales = pd.read_csv('.. /input/competitive-data-science-predict-future-sales/sales_train.csv')
sales =(sales
.query('0 < item_price < 50000 and 0 < item_cnt_day < 1001')
.replace({
'shop_id':{0:57, 1:58, 11:10},
'item_id':item_map
})
)
sales = sales[sales['shop_id'].isin(test.shop_id.unique())]
sales['date'] = pd.to... | dummy1 = pd.get_dummies(data1['Sex'], prefix='Male', drop_first=True)
data1 = pd.concat([data1, dummy1], axis=1 ) | Titanic - Machine Learning from Disaster |
7,770,915 | temp = sales.groupby(['shop_id','weekday'] ).agg({'item_cnt_day':'sum'} ).reset_index()
temp = pd.merge(temp, sales.groupby(['shop_id'] ).agg({'item_cnt_day':'sum'} ).reset_index() , on='shop_id', how='left')
temp.columns = ['shop_id','weekday', 'shop_day_sales', 'shop_total_sales']
temp['day_quality'] = temp['shop_da... | dummy1 = pd.get_dummies(data_val['Sex'], prefix='Male', drop_first=True)
data_val = pd.concat([data_val, dummy1], axis=1 ) | Titanic - Machine Learning from Disaster |
7,770,915 | sales =(sales
.groupby(['date_block_num', 'shop_id', 'item_id'])
.agg({
'item_cnt_day':'sum',
'revenue':'sum',
'first_sale_day':'first'
})
.reset_index()
.rename(columns={'item_cnt_day':'item_cnt'})
)
sales.sample(5 )<drop_column> | data1['FamilySize'] = data1['SibSp'] + data1['Parch'] + 1
data1.head(2 ) | Titanic - Machine Learning from Disaster |
7,770,915 | test['date_block_num'] = 34
del test['ID']<concatenate> | data_val['FamilySize'] = data_val['SibSp'] + data_val['Parch'] + 1
data_val.head(2 ) | Titanic - Machine Learning from Disaster |
7,770,915 | df = pd.concat([df,test] ).fillna(0)
df = df.reset_index()
del df['index']<merge> | PassengerId = data_val.PassengerId | Titanic - Machine Learning from Disaster |
7,770,915 | df = pd.merge(df, sales, on=['shop_id', 'item_id', 'date_block_num'], how='left' ).fillna(0)
df = pd.merge(df, dates, on=['date_block_num','shop_id'], how='left')
df = pd.merge(df, items.drop(columns=['item_name','group_name','category_name']), on='item_id', how='left' )<feature_engineering> | data1= data1.rename(columns={ 'Male_1' : 'Male'})
data_val= data_val.rename(columns={ 'Male_1' : 'Male'} ) | Titanic - Machine Learning from Disaster |
7,770,915 | shops = pd.read_csv('.. /input/predict-future-sales-eng-translation/shops.csv')
shops_cats = pd.DataFrame(
np.array(list(product(*[df['shop_id'].unique() , df['category_id'].unique() ]))),
columns =['shop_id', 'category_id']
)
temp = df.groupby(['category_id', 'shop_id'] ).agg({'item_cnt':'sum'} ).reset_index()
tem... | drop_column = ['PassengerId', 'Pclass', 'Name', 'Sex', 'Ticket', 'Fare', 'Embarked']
data1.drop(drop_column, axis=1, inplace = True ) | Titanic - Machine Learning from Disaster |
7,770,915 | shops.dropna(inplace=True)
shops['shop_name'] = shops['shop_name'].str.lower()
shops['shop_name'] = shops['shop_name'].str.replace(r'[^\w\d\s]', ' ')
shops['shop_type'] = 'regular'
shops.loc[shops['shop_name'].str.contains(r'tc'), 'shop_type'] = 'tc'
shops.loc[shops['shop_name'].str.contains(r'mall|center|mega'), 'sh... | target = 'Survived'
y = data1[target]
x = data1.drop(columns = target)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.3, random_state = 42)
y = data1["Survived"]
features = ["Age", "Male","Pclass_2", "Pclass_3","FamilySize"]
X = pd.get_dummies(data1[features])
X_test = pd.get_dummies(x_test[fe... | Titanic - Machine Learning from Disaster |
7,770,915 | df = pd.merge(df, shops.drop(columns='shop_name'), on='shop_id', how='left')
df.head()<feature_engineering> | model = RandomForestClassifier(n_estimators=100, max_depth=3, random_state=1)
model.fit(X, y)
predictions = model.predict(X_test)
score = accuracy_score(y_test, predictions)
print("Score: ",score ) | Titanic - Machine Learning from Disaster |
7,770,915 | df['first_sale_day'] = df.groupby('item_id')['first_sale_day'].transform('max' ).astype('int16')
df.loc[df['first_sale_day']==0, 'first_sale_day'] = 1035
df['prev_days_on_sale'] = [max(idx)for idx in zip(df['first_day_of_month']-df['first_sale_day'],[0]*len(df)) ]
del df['first_day_of_month']<drop_column> | X_val = pd.get_dummies(data_val[features])
predictions_test = model.predict(X_val)
output = pd.DataFrame({'PassengerId': PassengerId, 'Survived': predictions_test})
output.to_csv('my_submission_RFC.csv', index=False)
print("Your submission was successfully saved!" ) | Titanic - Machine Learning from Disaster |
7,199,685 | del sales, categories, shops, shops_cats, temp, temp2, test, dupes, item_map,
df.head()<feature_engineering> | %matplotlib inline
sns.set()
| Titanic - Machine Learning from Disaster |
7,199,685 | df['item_cnt_unclipped'] = df['item_cnt']
df['item_cnt'] = df['item_cnt'].clip(0, 20 )<data_type_conversions> | gender_submission = pd.read_csv(".. /input/titanic/gender_submission.csv")
test = pd.read_csv(".. /input/titanic/test.csv")
train = pd.read_csv(".. /input/titanic/train.csv" ) | Titanic - Machine Learning from Disaster |
7,199,685 | def downcast(df):
float_cols = [c for c in df if df[c].dtype in ["float64"]]
int_cols = [c for c in df if df[c].dtype in ['int64']]
df[float_cols] = df[float_cols].astype('float32')
df[int_cols] = df[int_cols].astype('int16')
return df
df = downcast(df )<data_type_conversions> | train.isnull().sum() | Titanic - Machine Learning from Disaster |
7,199,685 | df['item_age'] =(df['date_block_num'] - df.groupby('item_id')['date_block_num'].transform('min')).astype('int8')
df['item_name_first4_age'] =(df['date_block_num'] - df.groupby('item_name_first4')['date_block_num'].transform('min')).astype('int8')
df['item_name_first6_age'] =(df['date_block_num'] - df.groupby('item_na... | train.isnull().sum() | Titanic - Machine Learning from Disaster |
7,199,685 | temp = df.query('item_cnt > 0' ).groupby(['item_id','shop_id'] ).agg({'date_block_num':'min'} ).reset_index()
temp.columns = ['item_id', 'shop_id', 'item_shop_first_sale']
df = pd.merge(df, temp, on=['item_id','shop_id'], how='left')
df['item_shop_first_sale'] = df['item_shop_first_sale'].fillna(50)
df['item_age_if_s... | test.isnull().sum() | Titanic - Machine Learning from Disaster |
7,199,685 | def agg_cnt_col(df, merging_cols, new_col,aggregation):
temp = df.groupby(merging_cols ).agg(aggregation ).reset_index()
temp.columns = merging_cols + [new_col]
df = pd.merge(df, temp, on=merging_cols, how='left')
return df
df = agg_cnt_col(df, ['date_block_num','item_id'],'item_cnt_all_shops',{'item_cnt':'mean'})
df... | test.isnull().sum() | Titanic - Machine Learning from Disaster |
7,199,685 | def new_item_sales(df, merging_cols, new_col):
temp =(
df
.query('item_age==0')
.groupby(merging_cols)['item_cnt']
.mean()
.reset_index()
.rename(columns={'item_cnt': new_col})
)
df = pd.merge(df, temp, on=merging_cols, how='left')
return df
df = new_item_sales(df, ['date_block_num','category_id','shop_id'], 'ne... | train_test_data= [train, test]
for dataset in train_test_data:
dataset['Title'] = dataset['Name'].str.extract('([A-Za-z]+)\.',expand = False ) | Titanic - Machine Learning from Disaster |
7,199,685 | def agg_price_col(df, merging_cols, new_col):
temp = df.groupby(merging_cols ).agg({'revenue':'sum','item_cnt_unclipped':'sum'} ).reset_index()
temp[new_col] = temp['revenue']/temp['item_cnt_unclipped']
temp = temp[merging_cols + [new_col]]
df = pd.merge(df, temp, on=merging_cols, how='left')
return df
df = agg_price_... | train['Title'].value_counts() | Titanic - Machine Learning from Disaster |
7,199,685 | df = downcast(df )<merge> | test['Title'].value_counts() | Titanic - Machine Learning from Disaster |
7,199,685 | def lag_feature(df, lag, col, merge_cols):
temp = df[merge_cols + [col]]
temp = temp.groupby(merge_cols ).agg({f'{col}':'first'} ).reset_index()
temp.columns = merge_cols + [f'{col}_lag{lag}']
temp['date_block_num'] += lag
df = pd.merge(df, temp, on=merge_cols, how='left')
df[f'{col}_lag{lag}'] = df[f'{col}_lag{lag}']... | title_mapping = {"Mr": 0, "Miss": 1, "Mrs": 2,
"Master": 3, "Dr": 3, "Rev": 3, "Col": 3, "Major": 3, "Mlle": 3,"Countess": 3,
"Ms": 3, "Lady": 3, "Jonkheer": 3, "Don": 3, "Dona" : 3, "Mme": 3,"Capt": 3,"Sir": 3 }
for dataset in train_test_data:
dataset['Title'] = dataset['Title'].map(title_mapping ) | Titanic - Machine Learning from Disaster |
7,199,685 | lag12_cols = {
'item_cnt':['date_block_num', 'shop_id', 'item_id'],
'item_cnt_all_shops':['date_block_num', 'item_id'],
'category_cnt':['date_block_num', 'shop_id', 'category_id'],
'category_cnt_all_shops':['date_block_num', 'category_id'],
'group_cnt':['date_block_num', 'shop_id', 'group_id'],
'group_cnt_all_shops':['... | train.drop('Name', axis=1, inplace = True)
test.drop('Name', axis=1, inplace = True ) | Titanic - Machine Learning from Disaster |
7,199,685 | lag2_cols = {
'item_cnt_unclipped':['date_block_num', 'shop_id', 'item_id'],
'item_cnt_all_shops_median':['date_block_num', 'item_id'],
'category_cnt_median':['date_block_num', 'shop_id', 'category_id'],
'category_cnt_all_shops_median':['date_block_num', 'category_id']
}
for col in lag2_cols:
df = lag_feature(df, 1, co... | sex_mapping = {"male":0, "female":1}
for dataset in train_test_data:
dataset["Sex"] = dataset["Sex"].map(sex_mapping ) | Titanic - Machine Learning from Disaster |
7,199,685 | df['item_cnt_diff'] = df['item_cnt_unclipped_lag1']/df['item_cnt_lag1to12']
df['item_cnt_all_shops_diff'] = df['item_cnt_all_shops_lag1']/df['item_cnt_all_shops_lag1to12']
df['category_cnt_diff'] = df['category_cnt_lag1']/df['category_cnt_lag1to12']
df['category_cnt_all_shops_diff'] = df['category_cnt_all_shops_lag1']/... | train["Age"].fillna(train.groupby("Title")["Age"].transform("median"), inplace=True)
test["Age"].fillna(test.groupby("Title")["Age"].transform("median"), inplace=True ) | Titanic - Machine Learning from Disaster |
7,199,685 | df = lag_feature(df, 1, 'category_price',['date_block_num', 'category_id'])
df = lag_feature(df, 1, 'block_price',['date_block_num'])
del df['category_price'], df['block_price']<feature_engineering> | for dataset in train_test_data:
dataset.loc[dataset['Age'] <= 16, 'Age'] = 0,
dataset.loc[(dataset['Age'] > 16)&(dataset['Age'] <= 26), 'Age'] = 1,
dataset.loc[(dataset['Age'] > 26)&(dataset['Age'] <= 36), 'Age'] = 2,
dataset.loc[(dataset['Age'] > 36)&(dataset['Age'] <= 62), 'Age'] = 3,
dataset.loc[dataset['Age'] > 62,... | Titanic - Machine Learning from Disaster |
7,199,685 | df.loc[(df['item_age']>0)&(df['item_cnt_lag1to12'].isna()), 'item_cnt_lag1to12'] = 0
df.loc[(df['category_age']>0)&(df['category_cnt_lag1to12'].isna()), 'category_cnt_lag1to12'] = 0
df.loc[(df['group_age']>0)&(df['group_cnt_lag1to12'].isna()), 'group_cnt_lag1to12'] = 0<feature_engineering> | Pclass1 = train[train['Pclass']==1]['Embarked'].value_counts()
Pclass2 = train[train['Pclass']==2]['Embarked'].value_counts()
Pclass3 = train[train['Pclass']==3]['Embarked'].value_counts()
df = pd.DataFrame([Pclass1, Pclass2, Pclass3])
df.index = ['1st class', '2nd index', '3rd class']
df.plot(kind='bar',stacked = Tru... | Titanic - Machine Learning from Disaster |
7,199,685 | df['item_cnt_lag1to12'] /= [min(idx)for idx in zip(df['item_age'],df['shop_age'],[12]*len(df)) ]
df['item_cnt_all_shops_lag1to12'] /= [min(idx)for idx in zip(df['item_age'],[12]*len(df)) ]
df['category_cnt_lag1to12'] /= [min(idx)for idx in zip(df['category_age'],df['shop_age'],[12]*len(df)) ]
df['category_cnt_all_shops... | for dataset in train_test_data:
dataset['Embarked'] = dataset['Embarked'].fillna('S' ) | Titanic - Machine Learning from Disaster |
7,199,685 | df = downcast(df )<merge> | embarked_mapping = {"S":0, "C":1, "Q":2}
for dataset in train_test_data:
dataset['Embarked'] = dataset['Embarked'].map(embarked_mapping ) | Titanic - Machine Learning from Disaster |
7,199,685 | def past_information(df, merging_cols, new_col, aggregation):
temp = []
for i in range(1,35):
block = df.query(f'date_block_num < {i}' ).groupby(merging_cols ).agg(aggregation ).reset_index()
block.columns = merging_cols + [new_col]
block['date_block_num'] = i
block = block[block[new_col]>0]
temp.append(block)
temp = ... | train["Fare"].fillna(train.groupby("Pclass")["Fare"].transform("median"), inplace=True)
test["Fare"].fillna(test.groupby("Pclass")["Fare"].transform("median"), inplace=True ) | Titanic - Machine Learning from Disaster |
7,199,685 | df['relative_price_item_block_lag1'] = df['last_item_price']/df['block_price_lag1']<data_type_conversions> | for dataset in train_test_data:
dataset.loc[dataset['Fare'] <= 17, 'Fare']=0,
dataset.loc[(dataset['Fare'] > 17)&(dataset['Fare'] <= 30), 'Fare']=1,
dataset.loc[(dataset['Fare'] > 30)&(dataset['Fare'] <= 100), 'Fare']=2,
dataset.loc[dataset['Fare'] >100, 'Fare']=3 | Titanic - Machine Learning from Disaster |
7,199,685 | df['item_cnt_per_day_alltime'] =(df['item_cnt_sum_alltime']/df['prev_days_on_sale'] ).fillna(0)
df['item_cnt_per_day_alltime_allshops'] =(df['item_cnt_sum_alltime_allshops']/df['prev_days_on_sale'] ).fillna(0 )<set_options> | train.Cabin.value_counts() | Titanic - Machine Learning from Disaster |
7,199,685 | gc.collect()
df = downcast(df )<groupby> | for dataset in train_test_data:
dataset['Cabin'] = dataset['Cabin'].str[:1] | Titanic - Machine Learning from Disaster |
7,199,685 | def matching_name_cat_age(df,n,all_shops):
temp_cols = [f'same_name{n}catage_cnt','date_block_num', f'item_name_first{n}','item_age','category_id']
if all_shops:
temp_cols[0] += '_all_shops'
else:
temp_cols += ['shop_id']
temp = []
for i in range(1,35):
block =(
df
.query(f'date_block_num < {i}')
.groupby(temp_cols[2... | cabin_mapping = {"A": 0, "B": 0.4, "C": 0.8, "D": 1.2, "E": 1.6, "F": 2, "G": 2.4, "T": 2.8}
for dataset in train_test_data:
dataset['Cabin'] = dataset['Cabin'].map(cabin_mapping ) | Titanic - Machine Learning from Disaster |
7,199,685 | df = downcast(df)
int8_cols = [
'item_cnt','month','group_id','shop_type',
'shop_city','shop_id','date_block_num','category_id',
'item_age',
]
int16_cols = [
'item_id','item_name_first4',
'item_name_first6','item_name_first11'
]
for col in int8_cols:
df[col] = df[col].astype('int8')
for col in int16_cols:
df[col] = d... | train["Cabin"].fillna(train.groupby("Pclass")["Cabin"].transform("median"), inplace=True)
test["Cabin"].fillna(test.groupby("Pclass")["Cabin"].transform("median"), inplace=True ) | Titanic - Machine Learning from Disaster |
7,199,685 | def nearby_item_data(df,col):
if col in ['item_cnt_unclipped_lag1','item_cnt_lag1to12']:
cols = ['date_block_num', 'shop_id', 'item_id']
temp = df[cols + [col]]
else:
cols = ['date_block_num', 'item_id']
temp = df.groupby(cols ).agg({col:'first'} ).reset_index() [cols + [col]]
temp.columns = cols + [f'below_{col}']
tem... | train['Familysize'] = train["SibSp"] + train["Parch"] + 1
test['Familysize'] = test["SibSp"] + test["Parch"] + 1 | Titanic - Machine Learning from Disaster |
7,199,685 | results = Counter()
items['item_name'].str.split().apply(results.update)
words = []
cnts = []
for key, value in results.items() :
words.append(key)
cnts.append(value)
counts = pd.DataFrame({'word':words,'count':cnts})
common_words = counts.query('count>200' ).word.to_list()
for word in common_words:
items[f'{word}_... | family_mapping = {1: 0, 2: 0.4, 3: 0.8, 4: 1.2, 5: 1.6, 6: 2, 7: 2.4, 8: 2.8, 9: 3.2, 10: 3.6, 11: 4}
for dataset in train_test_data:
dataset['Familysize'] = dataset['Familysize'].map(family_mapping ) | Titanic - Machine Learning from Disaster |
7,199,685 | df = df.join(items, on='item_id' )<categorify> | features_drop = ['Ticket', 'SibSp', 'Parch']
train = train.drop(features_drop, axis=1)
test = test.drop(features_drop, axis=1)
train = train.drop(['PassengerId'], axis=1 ) | Titanic - Machine Learning from Disaster |
7,199,685 | def binary_encode(df, letters, cols):
encoder = ce.BinaryEncoder(cols=[f'item_name_first{letters}'], return_df=True)
temp = encoder.fit_transform(df[f'item_name_first{letters}'])
df = pd.concat([df,temp], axis=1)
del df[f'item_name_first{letters}_0']
name_cols = [f'item_name_first{letters}_{x}' for x in range(1,cols... | X = train.drop('Survived', axis=1)
y = train['Survived']
X.shape, y.shape | Titanic - Machine Learning from Disaster |
7,199,685 | df.to_pickle('df_complete.pkl' )<set_options> | from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC | Titanic - Machine Learning from Disaster |
7,199,685 | %reset -f<set_options> | k_fold = KFold(n_splits=10, shuffle=True, random_state=0 ) | Titanic - Machine Learning from Disaster |
7,199,685 | pd.set_option('display.max_rows', 160)
pd.set_option('display.max_columns', 160)
pd.set_option('display.max_colwidth', 30)
warnings.filterwarnings("ignore" )<prepare_x_and_y> | knn = KNeighborsClassifier(n_neighbors=13)
scoring = 'accuracy'
score = cross_val_score(knn, X, y, cv=k_fold, n_jobs=1, scoring=scoring)
print(score ) | Titanic - Machine Learning from Disaster |
7,199,685 | df = pd.read_pickle('.. /input/files-top-scoring-notebook-output-exploration/df_complete.pkl')
X_train = df[~df.date_block_num.isin([0,1,33,34])]
y_train = X_train['item_cnt']
del X_train['item_cnt']
X_val = df[df['date_block_num']==33]
y_val = X_val['item_cnt']
del X_val['item_cnt']
X_test = df[df['date_block_num']==... | round(np.mean(score)*100, 2 ) | Titanic - Machine Learning from Disaster |
7,199,685 | def build_lgb_model(params, X_train, X_val, y_train, y_val, cat_features):
lgb_train = lgb.Dataset(X_train, y_train)
lgb_val = lgb.Dataset(X_val, y_val)
model = lgb.train(params=params, train_set=lgb_train, valid_sets=(lgb_train, lgb_val), verbose_eval=50,
categorical_feature=cat_features)
return model<train_model> | rf = RandomForestClassifier(n_estimators=13)
scoring = 'accuracy'
score = cross_val_score(rf, X, y, cv=k_fold, n_jobs=1, scoring=scoring)
print(score ) | Titanic - Machine Learning from Disaster |
7,199,685 | params = {
'objective': 'rmse',
'metric': 'rmse',
'num_leaves': 1023,
'min_data_in_leaf':10,
'feature_fraction':0.7,
'learning_rate': 0.01,
'num_rounds': 1000,
'early_stopping_rounds': 30,
'seed': 1
}
cat_features = ['category_id','month','shop_id','shop_city']
lgb_model = build_lgb_model(params, X_train, X_val, y_trai... | round(np.mean(score)*100, 2 ) | Titanic - Machine Learning from Disaster |
7,199,685 | submission = pd.read_csv('.. /input/competitive-data-science-predict-future-sales/sample_submission.csv')
submission['item_cnt_month'] = lgb_model.predict(X_test ).clip(0,20)
submission[['ID', 'item_cnt_month']].to_csv('initial_lgb_submission.csv', index=False )<load_from_csv> | nb = GaussianNB()
scoring = 'accuracy'
score = cross_val_score(nb, X, y, cv=k_fold, n_jobs=1, scoring=scoring)
print(score ) | Titanic - Machine Learning from Disaster |
7,199,685 | categories = pd.read_csv('.. /input/predict-future-sales-eng-translation/categories.csv')
categories['group_name'] = categories['category_name'].str.extract(r'(^[\w\s]*)')
categories['group_name'] = categories['group_name'].str.strip()
items = pd.read_csv('.. /input/predict-future-sales-eng-translation/items.csv')
i... | round(np.mean(score)*100, 2 ) | Titanic - Machine Learning from Disaster |
7,199,685 | X_train['lgb_pred'] = lgb_model.predict(X_train ).clip(0,20)
X_train['target'] = y_train
X_train['sq_err'] =(X_train['lgb_pred']-X_train['target'])**2
X_val['lgb_pred'] = lgb_model.predict(X_val ).clip(0,20)
X_val['target'] = y_val
X_val['sq_err'] =(X_val['lgb_pred']-X_val['target'])**2
X_test['lgb_pred'] = lgb_model... | svm = SVC()
scoring = 'accuracy'
score = cross_val_score(svm, X, y, cv=k_fold, n_jobs=1, scoring=scoring)
print(score ) | Titanic - Machine Learning from Disaster |
7,199,685 | data = X_train.groupby('date_block_num' ).agg({'lgb_pred':'mean','target':'mean','sq_err':'mean'} ).reset_index()
data['new_item_rmse'] = np.sqrt(X_train.query('item_age<=1' ).groupby('date_block_num' ).agg({'sq_err':'mean'} ).sq_err)
data['old_item_rmse'] = np.sqrt(X_train.query('item_age>1' ).groupby('date_block_num... | round(np.mean(score)*100, 2 ) | Titanic - Machine Learning from Disaster |
7,199,685 | df = pd.read_pickle('.. /input/files-top-scoring-notebook-output-exploration/df_complete.pkl')
(
df
[df['category_id'].isin(X_test.category_id.unique())]
.query('item_cnt>0')
.groupby('category_id')
.agg({
'category_age':'max',
'shop_id':['nunique','unique'],
'item_cnt':'sum'
})
.join(categories['category_name'])
.jo... | clf = SVC()
clf.fit(X, y)
test_data = test.drop("PassengerId", axis=1 ).copy()
prediction = clf.predict(test_data ) | Titanic - Machine Learning from Disaster |
7,199,685 | <merge><EOS> | submission = pd.DataFrame({
"PassengerId": test["PassengerId"],
"Survived": prediction
})
submission.to_csv('submission.csv', index=False ) | Titanic - Machine Learning from Disaster |
11,847,709 | <merge><EOS> | import pandas as pd | Titanic - Machine Learning from Disaster |
11,847,709 | <SOS> metric: categorizationaccuracy Kaggle data source: titanic-machine-learning-from-disaster<merge> | import pandas as pd | Titanic - Machine Learning from Disaster |
11,847,709 | CATEGORY = 20
(
items[items['item_id'].isin(X_test.item_id.unique())]
[['category_id','category_name','item_id','item_name']]
.join(
X_test
.groupby('item_id')
.agg({
'lgb_pred':'mean',
'same_name4catage_cnt_all_shops':'first',
'new_items_in_cat_all_shops_lag1to12':'first',
'item_cnt_all_shops_lag1':'first',
'cate... | pd.set_option('display.max_rows', 1000)
%pip install ppscore
seed =2055
plt.style.use('fivethirtyeight' ) | Titanic - Machine Learning from Disaster |
11,847,709 | M = pd.read_pickle('/kaggle/input/sales-data-prep/matrix.pkl')
M.columns<load_pretrained> | train = pd.read_csv('/kaggle/input/titanic/train.csv')
test = pd.read_csv('/kaggle/input/titanic/test.csv' ) | Titanic - Machine Learning from Disaster |
11,847,709 | M = pd.read_pickle('/kaggle/input/sales-data-prep/matrix.pkl')
M.drop(["new_item_cat_enc_lag_1", "new_item_cat_enc_lag_2", "new_item_cat_enc_lag_3"], axis=1, inplace=True)
M = M[M["date_block_num"] > 2]
M.fillna(0)
for col in M.columns:
print(col,M[col].nunique())
def reduce_mem_usage(df, use_float16=False):
star... | def basic_analysis(df1, df2):
b = pd.DataFrame()
b['First df_mean'] = round(df1.mean() ,2)
b['Second df_mean'] = round(df2.mean() ,2)
c =(b['First df_mean']/b['Second df_mean'])
if [c<=1]:
b['Variation, %'] = round(( 1-(( b['First df_mean']/b['Second df_mean'])))*100)
else:
b['Variation, %'] = round(((b['First df... | Titanic - Machine Learning from Disaster |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.