Files
founding-potential/evaluation/randorm_forest_classifier.ipynb
2023-03-15 14:31:15 +01:00

262 KiB

In [1]:
import matplotlib.pyplot as plt

import plotly.express as px
from plotly.offline import plot

import sys, json, time
import pandas as pd
import numpy as np

import seaborn as sns

from sklearn.model_selection import train_test_split


import warnings
warnings.filterwarnings("ignore")

pd.set_option('display.max_columns', None)
In [3]:
# from sklearn.datasets import load_iris
# from sklearn.model_selection import train_test_split
# from sklearn.naive_bayes import GaussianNB
# from sklearn import metrics
# X, y = load_iris(return_X_y=True)
# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=0)
# gnb = GaussianNB()
# y_pred = gnb.fit(X_train, y_train).predict(X_test)
# print("Number of mislabeled points out of a total %d points : %d"
#       % (X_test.shape[0], (y_test != y_pred).sum()))

# print("Naive Bayes Accuracy:",metrics.accuracy_score(y_test, y_pred))
Number of mislabeled points out of a total 75 points : 4
Naive Bayes Accuracy: 0.9466666666666667
In [6]:
df_founders_stanford = pd.read_csv("stanford_features_dataset.csv")
df_nonfounders_stanford = pd.read_csv("stanford_nonfounders_features_dataset.csv")

df_founders_telaviv = pd.read_csv("telaviv_features_dataset.csv")
df_nonfounders_telaviv = pd.read_csv("telaviv_nonfounders_features_dataset.csv")
In [7]:
df_all = pd.concat([df_founders_stanford, df_nonfounders_stanford, df_founders_telaviv, df_nonfounders_telaviv], ignore_index=True)
In [8]:
df_all.shape
Out [8]:
(5629, 148)
In [9]:
df_all = df_all.sample(frac=1).reset_index(drop=True)
In [10]:
df_all.groupby('Company_founded').count().reset_index().plot("Company_founded","name",kind="bar")
Out [10]:
<AxesSubplot:xlabel='Company_founded'>
In [70]:
X = df_all.drop(['Company_founded'], axis=1)
y = df_all['Company_founded']
X = X[["h-index","i10-index","publications","pub_citation_mean","pub_citation_sum","linked_patents_to_publications",
       "patents", "pat_citation_mean", "pat_citation_sum", "grants", "affiliations"]]
In [35]:
from sklearn.decomposition import PCA
pca = PCA(n_components=2)
pca_result = pca.fit_transform(X)
In [10]:
# plt.plot(range(2), pca.explained_variance_ratio_)
# plt.plot(range(2), np.cumsum(pca.explained_variance_ratio_))
# plt.title("Component-wise and Cumulative Explained Variance")
Out [10]:
Text(0.5, 1.0, 'Component-wise and Cumulative Explained Variance')
In [36]:
import seaborn as sns
plt.style.use('fivethirtyeight')
fig, axarr = plt.subplots(1, 2, figsize=(8, 5))
sns.heatmap(pca.components_[0, :].reshape(11, 1), ax=axarr[0], cmap='gray_r')
sns.heatmap(pca.components_[1, :].reshape(11, 1), ax=axarr[1], cmap='gray_r')
axarr[0].set_title(
"{0:.2f}% Explained Variance".format(pca.explained_variance_ratio_[0]*100),
fontsize=12
)
axarr[1].set_title(
"{0:.2f}% Explained Variance".format(pca.explained_variance_ratio_[1]*100),
fontsize=12
)
axarr[0].set_aspect('equal')
axarr[1].set_aspect('equal')

plt.suptitle('2-Component PCA')
Out [36]:
Text(0.5, 0.98, '2-Component PCA')
In [37]:
my_df = pd.DataFrame({"x":pca_result[:,0], "y":pca_result[:,1], "founding_state":y})
In [74]:
cdict = {0: 'red', 1: 'navy'}
fig, ax = plt.subplots(figsize=(8,6))
for g in np.unique(y):
    ix = np.where(y == g)
    ax.scatter(pca_result[ix, 0], pca_result[ix, 1], c = cdict[g], label = g)
ax.legend()
plt.xlabel('Feature 1');
plt.ylabel('Feature 2');
plt.title('Classification Data')
plt.show()
In [ ]:
# import plotly.express as px

# # hover_data=["technology",
# #             "cent_diff",
# #             "amp_diff",
# #             "sig_diff"
# #             ]
# fig = px.scatter(my_df, x="x",color="founding_state", y="y", title="extracted features")

# fig.show()
In [ ]:
# I'll bring over my comments from the Stackoverflow question.

# (1) RF outputs are votes, not proportions. My advice is to try to set parameters for RF or just use a different kind of tree or different model altogether to get at least proportion of positive examples in each leaf. Starting from votes is just setting your starting position farther away from the goal.

# (2) Since the cases are highly imbalanced, consider constructing generative models, one for positive, one for negative cases, then combine them via Bayes rule (which brings the base rates into play). If there is anything you know specifically about the minor class, try to build that into the generative model.

# Whatever you know about how the data are generated is very relevant, especially in the case of building a generative model. So any further information about that will help others help you.
In [40]:
# X_train.shape, X_test.shape

from sklearn.ensemble import RandomForestClassifier
clf_rf = RandomForestClassifier(criterion = 'entropy', random_state = 0, max_depth= 5, min_samples_leaf=3).fit(X_train, y_train)
predictions_rf = clf_rf.predict_proba(X_test)

# Isotonic calibration
from sklearn.calibration import CalibratedClassifierCV
clf_ca = RandomForestClassifier(criterion = 'entropy', random_state = 0, max_depth= 5, min_samples_leaf=3)
clf_isotonic = CalibratedClassifierCV(clf_ca, method='isotonic').fit(X_train, y_train)
predictions_isotonic = clf_isotonic.predict_proba(X_test)

from sklearn.linear_model import LogisticRegression
clf_log = LogisticRegression(random_state=0).fit(X_train, y_train)
predictions_log = clf_log.predict_proba(X_test)


from sklearn import metrics
y_pred = clf_rf.predict(X_test)
print("Random Forest Accuracy:",metrics.accuracy_score(y_test, y_pred))

y_pred = clf_isotonic.predict(X_test)
print("Random Forest Calibrated Accuracy:",metrics.accuracy_score(y_test, y_pred))

y_pred = clf_log.predict(X_test)
print("Logistic Regression Accuracy:",metrics.accuracy_score(y_test, y_pred))
Random Forest Accuracy: 0.7960172228202368
Random Forest Calibrated Accuracy: 0.8003229278794403
Logistic Regression Accuracy: 0.7438105489773951
In [ ]:
#new features:
#number of patents/publications/grants before the founding year, is there a pattern? count them as a feature
#number of above before the founding year and on the founding year
#can we build a regressor or classifier here?
#can we elaborate on younger researchers and older players?
#first/last publication/patent/grant year
In [42]:
#do we have a higher accuracy if we take only the most important features from decision tress or rf?

from sklearn.naive_bayes import GaussianNB
clf_nb = GaussianNB().fit(X_train, y_train)
predictions_nb = clf_nb.predict_proba(X_test)

y_pred = clf_nb.predict(X_test)
print("Naive Bayes Accuracy:",metrics.accuracy_score(y_test, y_pred))
Naive Bayes Accuracy: 0.45479009687836386
In [43]:
print("Brier scores: (smaller is better)")

from sklearn.metrics import brier_score_loss
clf_score = brier_score_loss(y_test, predictions_rf[:,1])
print("No calibration: %1.3f" % clf_score)

clf_isotonic_score = brier_score_loss(y_test, predictions_isotonic[:,1])
print("With isotonic calibration: %1.3f" % clf_isotonic_score)
Brier scores: (smaller is better)
No calibration: 0.140
With isotonic calibration: 0.140
In [68]:
# bins = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1]

# predictions_df = pd.DataFrame(predictions_rf)
# predictions_df['actual'] = list(y_test)
# predictions_df['bin'] = pd.cut(predictions_df[1], bins)
# predictions_df['bin_mid'] = predictions_df['bin'].apply(lambda x: x.mid).astype(float)
# bin_df = predictions_df.groupby('bin_mid').actual.mean().reset_index()


# predictions_isotonic_df = pd.DataFrame(predictions_log)
# predictions_isotonic_df['actual'] = list(y_test)
# predictions_isotonic_df['bin'] = pd.cut(predictions_isotonic_df[1], bins)
# predictions_isotonic_df['bin_mid'] = predictions_isotonic_df['bin'].apply(lambda x: x.mid).astype(float)
# bin_isotonic_df = predictions_isotonic_df.groupby('bin_mid').actual.mean().reset_index()


# predictions_log_df = pd.DataFrame(predictions_isotonic)
# predictions_log_df['actual'] = list(y_test)
# predictions_log_df['bin'] = pd.cut(predictions_log_df[1], bins)
# predictions_log_df['bin_mid'] = predictions_log_df['bin'].apply(lambda x: x.mid).astype(float)
# bin_log_df = predictions_log_df.groupby('bin_mid').actual.mean().reset_index()


# # predictions_svc_df = pd.DataFrame(predictions_svc)
# # predictions_svc_df['actual'] = list(y_test)
# # predictions_svc_df['bin'] = pd.cut(predictions_svc_df[1], bins)
# # predictions_svc_df['bin_mid'] = predictions_svc_df['bin'].apply(lambda x: x.mid).astype(float)
# # bin_svc_df = predictions_svc_df.groupby('bin_mid').actual.mean().reset_index()


# predictions_nb_df = pd.DataFrame(predictions_nb)
# predictions_nb_df['actual'] = list(y_test)
# predictions_nb_df['bin'] = pd.cut(predictions_nb_df[1], bins)
# predictions_nb_df['bin_mid'] = predictions_nb_df['bin'].apply(lambda x: x.mid).astype(float)
# bin_nb_df = predictions_nb_df.groupby('bin_mid').actual.mean().reset_index()

# ## Finally, plot the binned predictions
# plt.figure(figsize=(10,10))
# plt.plot(bin_df.bin_mid, bin_df.actual, '.-');
# plt.plot(bin_isotonic_df.bin_mid, bin_isotonic_df.actual, '.-');
# plt.plot(bin_log_df.bin_mid, bin_log_df.actual, '.-');
# plt.plot(bin_nb_df.bin_mid, bin_nb_df.actual, '.-');
# plt.plot([0,1], [0,1], '--')
# plt.legend(['Random Forest', 'Isotonic Calibration', 'Logistic', 'Naive Bayes','x=y']);
# plt.xlabel('Predicted probability of positive class');
# plt.ylabel('Fraction belonging to positive class');
# plt.title('Calibration Curves');
    

# plt.tight_layout()
# plt.show()
In [95]:
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split

# X, y = make_classification(n_samples=100_000, n_features=20, n_informative=2, n_redundant=10, random_state=42)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

from sklearn.calibration import CalibratedClassifierCV, CalibrationDisplay
from sklearn.linear_model import LogisticRegression
from sklearn.naive_bayes import GaussianNB

from sklearn.ensemble import RandomForestClassifier
clf_rf = RandomForestClassifier(criterion = 'entropy', random_state = 0, max_depth= 5, min_samples_leaf=3)
# predictions_rf = clf_rf.predict_proba(X_test)
clf_nb = GaussianNB()
clf_isotonic = CalibratedClassifierCV(clf_rf,cv=5, method='isotonic')
clf_log = LogisticRegression(random_state=0)

clf_list = [
    (clf_rf, "Random Forest"),
    (clf_nb, "Naive Bayes"),
    (clf_isotonic, "Random Forest + Isotonic"),
    (clf_log, "Logisitic Regression"),
]

fig = plt.figure(figsize=(15, 10))
gs = GridSpec(4, 2)
colors = plt.cm.get_cmap("Dark2")

ax_calibration_curve = fig.add_subplot(gs[:2, :2])
calibration_displays = {}
for i, (clf, name) in enumerate(clf_list):
    clf.fit(X_train, y_train)
    display = CalibrationDisplay.from_estimator(
        clf,
        X_test,
        y_test,
        n_bins=10,
        name=name,
        ax=ax_calibration_curve,
        color=colors(i),
    )
    calibration_displays[name] = display

# ax_calibration_curve.grid()
ax_calibration_curve.set_title("Calibration plots")

# Add histogram
grid_positions = [(2, 0), (2, 1), (3, 0), (3, 1)]
for i, (_, name) in enumerate(clf_list):
    row, col = grid_positions[i]
    ax = fig.add_subplot(gs[row, col])

    ax.hist(
        calibration_displays[name].y_prob,
        range=(0, 1),
        bins=10,
        label=name,
        color=colors(i),
    )
    ax.set(title=name, xlabel="Mean predicted probability", ylabel="Count")

plt.tight_layout()
plt.grid(True)
plt.show()
In [96]:
from collections import defaultdict

import pandas as pd

from sklearn.metrics import (
    precision_score,
    recall_score,
    f1_score,
    brier_score_loss,
    log_loss,
    roc_auc_score,
)

scores = defaultdict(list)
for i, (clf, name) in enumerate(clf_list):
    clf.fit(X_train, y_train)
    y_prob = clf.predict_proba(X_test)
    y_pred = clf.predict(X_test)
    scores["Classifier"].append(name)

    for metric in [brier_score_loss, log_loss]:
        score_name = metric.__name__.replace("_", " ").replace("score", "").capitalize()
        scores[score_name].append(metric(y_test, y_prob[:, 1]))

    for metric in [precision_score, recall_score, f1_score, roc_auc_score]:
        score_name = metric.__name__.replace("_", " ").replace("score", "").capitalize()
        scores[score_name].append(metric(y_test, y_pred))

    score_df = pd.DataFrame(scores).set_index("Classifier")
    score_df.round(decimals=3)

score_df
Out [96]:
Brier loss Log loss Precision Recall F1 Roc auc
Classifier
Random Forest 0.139695 0.422255 0.813636 0.677175 0.739160 0.780841
Naive Bayes 0.540378 5.616762 0.436782 0.958386 0.600079 0.519099
Random Forest + Isotonic 0.140117 0.424477 0.810294 0.694830 0.748133 0.786851
Logisitic Regression 0.199696 0.608708 0.857788 0.479193 0.614887 0.710019
In [ ]:
# Notice that although calibration improves the Brier score loss (a metric composed of calibration term and refinement term) and 
# Log loss, it does not significantly alter the prediction accuracy measures (precision, recall and F1 score). 
# This is because calibration should not significantly change prediction probabilities at the location of the decision 
# threshold (at x = 0.5 on the graph). Calibration should however, make the predicted probabilities more accurate and thus more 
# useful for making allocation decisions under uncertainty. Further, ROC AUC, should not change at all because calibration is a 
# monotonic transformation. Indeed, no rank metrics are affected by calibration.
In [ ]:
# Uncalibrated GaussianNB is poorly calibrated because of the redundant features 
# which violate the assumption of feature-independence and result in an overly confident 
# classifier, which is indicated by the typical transposed-sigmoid curve.
In [ ]:
from sklearn.tree import DecisionTreeClassifier

clf_dtc = DecisionTreeClassifier(criterion='gini', max_depth=3, random_state=0)

clf_dtc.fit(X_train, y_train)
In [ ]:
y_pred_gini = clf_dtc.predict(X_test)
In [ ]:
from sklearn.metrics import accuracy_score

print('Training set score: {:.4f}'.format(clf_dtc.score(X_train, y_train)))

print('Test set score: {:.4f}'.format(clf_dtc.score(X_test, y_test)))
In [ ]:
from sklearn.ensemble import RandomForestClassifier
clf_rfc = RandomForestClassifier(criterion = 'gini', random_state = 42)
clf_rfc.fit(X_train, y_train)

# Evaluating on Training set
rfc_pred_train = clf_rfc.predict(X_train)

print('Training set score: {:.4f}'.format(clf_rfc.score(X_train, y_train)))

print('Test set score: {:.4f}'.format(clf_rfc.score(X_test, y_test)))
In [ ]:
from sklearn.model_selection import GridSearchCV
In [ ]:
clf = DecisionTreeClassifier(criterion='gini', random_state=42)

parameters = {'max_depth':range(3,20)}
clf = GridSearchCV(clf, parameters, n_jobs=4)
clf.fit(X, y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
In [ ]:
clf = RandomForestClassifier(criterion='gini', random_state=42)

#(n_estimators= 50, criterion='gini', max_depth=5, random_state=42
parameters = {'max_depth':range(3,20), 'n_estimators':range(5,150), "criterion":["gini","entropy","log_loss"] }
clf = GridSearchCV(clf, parameters, n_jobs=6)
clf.fit(X, y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 
In [ ]:
from sklearn.model_selection import cross_val_score

clf_rfc = RandomForestClassifier(n_estimators= 50, criterion='gini', max_depth=5, random_state=42)
scores = cross_val_score(clf_rfc, X, y, cv=10)
scores
In [ ]:
print("%0.2f accuracy with a standard deviation of %0.2f" % (scores.mean(), scores.std()))
In [ ]:
feature_importance=pd.DataFrame({
    'rfc':clf_rfc.feature_importances_,
    'dt':clf_dtc.feature_importances_
},index=X.columns)
feature_importance.sort_values(by='rfc',ascending=True,inplace=True)

index = np.arange(len(feature_importance))
fig, ax = plt.subplots(figsize=(18,8))
rfc_feature=ax.barh(index,feature_importance['rfc'],0.4,color='purple',label='Random Forest')
dt_feature=ax.barh(index+0.4,feature_importance['dt'],0.4,color='lightgreen',label='Decision Tree')
ax.set(yticks=index+0.4,yticklabels=feature_importance.index)

ax.legend()
plt.show()