Kaggle competition: Two Sigma Connect: Rental Listing Inquiries
<SOS> metric: MulticlassLoss Kaggle data source: two-sigma-connect:-rental-listing-inquiries<save_to_csv>
train_df=pd.read_json('.. /input/train.json')
 test_df=pd.read_json('.. /input/test.json' )
y_preds_LS =(np.argmax(W_LS.T @ X_test.T, axis=0)).astype(int)
 df_sample_sub.loc[:, 'Survived'] = y_preds_LS
df_sample_sub.to_csv('submission0.csv', index=False)
 display(df_sample_sub.head())
<compute_train_metric>
train_df["price_t"] =train_df["price"]/train_df["bedrooms"]
test_df["price_t"] = test_df["price"]/test_df["bedrooms"]
train_df["room_sum"] = train_df["bedrooms"]+train_df["bathrooms"]
test_df["room_sum"] = test_df["bedrooms"]+test_df["bathrooms"]
train_df["num_photos"] = train_df["photos"].apply(len)
 test_df["num_photos"] = test_df["photos"].apply(len)
 train_df["num_features"] = train_df["features"].apply(len)
 test_df["num_features"] = test_df["features"].apply(len)
 train_df["num_description_words"] = train_df["description"].apply(lambda x: len(x.split(" ")))
 test_df["num_description_words"] = test_df["description"].apply(lambda x: len(x.split(" ")))
 features_to_use=["bathrooms", "bedrooms", "latitude", "longitude", "price","price_t","num_photos", "num_features", "num_description_words","listing_id"]
def test_clfs(clfs):
for clf in clfs:
print('------------------------------------------')
 start = time()
clf = clf(random_state=42)
 scores = cross_val_score(clf, X, y, cv=5)
 print(str(clf), 'results:')
 print("Accuracy: %0.2f(+/- %0.2f)" %(scores.mean() , scores.std() * 2))
end = time()
print('Processing time', end-start,'s')
 models = [RandomForestClassifier, LogisticRegression,XGBClassifier]
test_clfs(models)
<train_model>
def runXGB(train_X, train_y, test_X, test_y=None, feature_names=None, seed_val=0, num_rounds=1000):
param = {}
param['objective'] = 'multi:softprob'
param['eta'] = 0.1
param['max_depth'] = 6
param['silent'] = 1
param['num_class'] = 3
param['eval_metric'] = "mlogloss"
param['min_child_weight'] = 1
param['subsample'] = 0.7
param['colsample_bytree'] = 0.7
param['seed'] = seed_val
num_rounds = num_rounds
plst = list(param.items())
 xgtrain = xgb.DMatrix(train_X, label=train_y)
 if test_y is not None:
xgtest = xgb.DMatrix(test_X, label=test_y)
 watchlist = [(xgtrain,'train'),(xgtest, 'test')]
model = xgb.train(plst, xgtrain, num_rounds, watchlist, early_stopping_rounds=20)
 else:
xgtest = xgb.DMatrix(test_X)
 model = xgb.train(plst, xgtrain, num_rounds)
 pred_test_y = model.predict(xgtest)
 return pred_test_y, model
from sklearn.model_selection import GridSearchCV 
<save_to_csv>
categorical = ["display_address", "manager_id", "building_id", "street_address"]
for f in categorical:
if train_df[f].dtype=='object':
lbl = preprocessing.LabelEncoder()
lbl.fit(list(train_df[f].values)+ list(test_df[f].values))
train_df[f] = lbl.transform(list(train_df[f].values))
test_df[f] = lbl.transform(list(test_df[f].values))
features_to_use.append(f )
clf1 = RandomForestClassifier(max_depth=9, min_samples_leaf=4, min_samples_split=2,
n_estimators=9, random_state=42, n_jobs=-1)
 clf1.fit(X, y)
 y_preds_RF = clf1.predict(X_test ).astype(int)
 df_sample_sub.loc[:, 'Survived'] = y_preds_RF
df_sample_sub.to_csv('submission1.csv', index=False)
 display(df_sample_sub.head())
<save_to_csv>
train_df['features'] = train_df["features"].apply(lambda x: " ".join(["_".join(i.split(" ")) for i in x]))
test_df['features'] = test_df["features"].apply(lambda x: " ".join(["_".join(i.split(" ")) for i in x]))
print(train_df["features"].head())
 tfidf = CountVectorizer(stop_words='english', max_features=200)
 tr_sparse = tfidf.fit_transform(train_df["features"])
 te_sparse = tfidf.transform(test_df["features"] )
clf2 = LogisticRegression(C=48, class_weight='None', fit_intercept= False, penalty='l2', solver='lbfgs')
 clf2.fit(X, y)
 y_preds_LR = clf2.predict(X_test ).astype(int)
 df_sample_sub.loc[:, 'Survived'] = y_preds_LR
df_sample_sub.to_csv('submission2.csv', index=False)
 display(df_sample_sub.head())
<save_to_csv>
train_X = sparse.hstack([train_df[features_to_use], tr_sparse] ).tocsr()
test_X = sparse.hstack([test_df[features_to_use], te_sparse] ).tocsr()
target_num_map = {'high':0, 'medium':1, 'low':2}
train_y = np.array(train_df['interest_level'].apply(lambda x: target_num_map[x]))
print(train_X.shape, test_X.shape )
clf3 = XGBClassifier(booster='gbtree', colsample_bytree= 0.6,
gamma=1, max_depth=5, min_child_weight=1, n_estimators=100, subsample=0.8)
 clf3.fit(X, y)
 y_preds_xgb = clf3.predict(X_test ).astype(int)
 df_sample_sub.loc[:, 'Survived'] = y_preds_xgb
df_sample_sub.to_csv('submission3.csv', index=False)
 display(df_sample_sub.head())
<choose_model_class>
cv_scores = []
kf = model_selection.KFold(n_splits=5, shuffle=True, random_state=2016)
 for dev_index, val_index in kf.split(range(train_X.shape[0])) :
dev_X, val_X = train_X[dev_index,:], train_X[val_index,:]
dev_y, val_y = train_y[dev_index], train_y[val_index]
preds, model = runXGB(dev_X, dev_y, val_X, val_y)
 cv_scores.append(log_loss(val_y, preds))
print(cv_scores)
 break
<split><EOS> 
preds, model = runXGB(train_X, train_y, test_X, num_rounds=400)
 out_df = pd.DataFrame(preds)
 out_df.columns = ["high", "medium", "low"]
out_df["listing_id"] = test_df.listing_id.values
out_df.to_csv("xgb_starter2.csv", index=False )