Skip to content

Instantly share code, notes, and snippets.

@purva91
purva91 / click_rate_context.py
Last active Dec 6, 2019
counterfactual analysis
View click_rate_context.py
# set ads
num_ads = 3
ads = np.asarray(["ad_{}".format(i) for i in range(num_ads)])
# assign random priors to contexts
ad_interaction_priors = np.asarray([0.1, 0.3, 0.6])
user_context_priors = {context:np.random.permutation(ad_interaction_priors) for context in user_contexts}
View prc_auc
# calculate precision-recall AUC
auc_prc = auc(recall, precision)
print(auc_prc)
View prc_plot
precision, recall, thresholds = precision_recall_curve(y_test, y_pred_proba)
plt.figure(figsize=(10,8))
plt.plot([0, 1], [0.5, 0.5],'k--')
plt.plot(recall, precision, label='Knn')
plt.xlabel('recall')
plt.ylabel('precision')
plt.title('Knn(n_neighbors=5) PRC curve')
plt.show()
View roc_auc
roc_auc_score(y_test, y_pred_proba)
View roc_plot
plt.figure(figsize=(10,8))
plt.plot([0,1],[0,1],'k--')
plt.plot(fpr,tpr, label='Knn')
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.title('Knn(n_neighbors=5) ROC curve')
plt.show()
View ROC_curve
y_pred_proba = knn.predict_proba(X_test)[:,1]
fpr, tpr, thresholds = roc_curve(y_test, y_pred_proba)
View report
print(classification_report(y_test,y_pred))
View confusion_matrix
y_pred = knn.predict(X_test)
confusion_matrix(y_test,y_pred)
pd.crosstab(y_test, y_pred, rownames=['Actual'], colnames=['Predicted'], margins=True)
View final_fit
#Setup a knn classifier with k neighbors
knn = KNeighborsClassifier(8)
knn.fit(X_train,y_train)
knn.score(X_test,y_test)