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

475 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 tqdm.notebook import tqdm as progressbar

from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

from sklearn.metrics import accuracy_score

import warnings
warnings.filterwarnings("ignore")
pd.set_option('display.max_columns', None)
In [7]:
# df_all.to_csv("telaviv_dataset.csv",index= False)
In [9]:
# df_all.info(verbose=True, show_counts=True)
In [ ]:
#build the 3 new features for grants/publications/patents before the founding year
#build continues older researcher vs new researcher feature 
In [16]:
# df_all.info(verbose=True, null_counts=True)
In [2]:
from sklearn import preprocessing
In [14]:
from sklearn.preprocessing import MinMaxScaler
In [15]:
df_founders = pd.read_csv(r"datasets_complete\\berkeley_features_dataset.csv")
df_nonfounders = pd.read_csv(r"datasets_complete\\berkeley_nonfounders_features_dataset.csv")

df_nonfounders = df_nonfounders[:1239]

df_all = df_founders.append(df_nonfounders, ignore_index=True)
df_all = df_all.sample(frac=1).reset_index(drop=True)

X = df_all.drop(['Company_founded'], axis=1)
y = df_all['Company_founded']
X = X[["h-index","i10-index", "g-index", "industry_collab_papers", "grant_research_impact", "grant_innovation_impact"
       ,"publications","pub_citation_mean","pub_citation_sum","linked_patents_to_publications","patents", 
       "pat_citation_mean", "grants", "affiliations"]]

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

train_norm = X_train
test_norm = X_test
# Normalize Training Data 
# std_scale = preprocessing.StandardScaler().fit(train_norm)
std_scale = preprocessing.MinMaxScaler().fit(train_norm)
x_train_norm = std_scale.transform(train_norm)
#Converting numpy array to dataframe
training_norm_col = pd.DataFrame(x_train_norm, index=train_norm.index, columns=train_norm.columns) 
# X_train.update(training_norm_col)

# Normalize Testing Data by using mean and SD of training set
x_test_norm = std_scale.transform(test_norm)
testing_norm_col = pd.DataFrame(x_test_norm, index=test_norm.index, columns=test_norm.columns) 
# X_test.update(testing_norm_col)

clf_dt_entropy = DecisionTreeClassifier(criterion='entropy', max_depth=5, random_state=42).fit(training_norm_col, y_train)

print('Decision Tree: Training set (Berkeley) score: {:.4f}'.format(clf_dt_entropy.score(training_norm_col, y_train)))
print('Decision Tree: Test set (Berkeley) score : {:.4f}'.format(clf_dt_entropy.score(testing_norm_col, y_test)))


from sklearn.ensemble import RandomForestClassifier
clf_rf = RandomForestClassifier(criterion = 'entropy', random_state = 42, max_depth= 5, min_samples_leaf=3).fit(training_norm_col, y_train)
print('Random Forest: Training set (Berkeley) score: {:.4f}'.format(clf_rf.score(X_train, y_train)))
print('Random Forest: Test set (Berkeley) score: {:.4f}'.format(clf_rf.score(testing_norm_col, y_test)))
Decision Tree: Training set (Berkeley) score: 0.8188
Decision Tree: Test set (Berkeley) score : 0.7369
Random Forest: Training set (Berkeley) score: 0.5643
Random Forest: Test set (Berkeley) score: 0.7664
In [9]:
df_founders = pd.read_csv(r"datasets_complete\\berkeley_features_dataset.csv")
df_nonfounders = pd.read_csv(r"datasets_complete\\berkeley_nonfounders_features_dataset.csv")

df_nonfounders = df_nonfounders[:1239]
# df_nonfounders = df_nonfounders[:630]
# df_founders["Company_founded"] = 1

df_all = df_founders.append(df_nonfounders, ignore_index=True)
df_all = df_all.sample(frac=1).reset_index(drop=True)

X = df_all.drop(['Company_founded'], axis=1)
y = df_all['Company_founded']
X = X[["h-index","i10-index", "g-index", "industry_collab_papers", "grant_research_impact", "grant_innovation_impact"
       ,"publications","pub_citation_mean","pub_citation_sum","linked_patents_to_publications","patents", 
       "pat_citation_mean", "grants", "affiliations"]]

X_train, X_test, y_train, y_test = train_test_split(X, y, train_size= 0.33, random_state = 42)
clf_dt_entropy = DecisionTreeClassifier(criterion='entropy', max_depth=5, random_state=42).fit(X_train, y_train)

print('Decision Tree: Training set (Berkeley) score: {:.4f}'.format(clf_dt_entropy.score(X_train, y_train)))
print('Decision Tree: Test set (Berkeley) score : {:.4f}'.format(clf_dt_entropy.score(X_test, y_test)))


from sklearn.ensemble import RandomForestClassifier
clf_rf = RandomForestClassifier(criterion = 'entropy', random_state = 42, max_depth= 5, min_samples_leaf=3).fit(X_train, y_train)
print('Random Forest: Training set (Berkeley) score: {:.4f}'.format(clf_rf.score(X_train, y_train)))
print('Random Forest: Test set (Berkeley) score: {:.4f}'.format(clf_rf.score(X_test, y_test)))
Decision Tree: Training set (Berkeley) score: 0.7931
Decision Tree: Test set (Berkeley) score : 0.7459
Random Forest: Training set (Berkeley) score: 0.8029
Random Forest: Test set (Berkeley) score: 0.7742
In [4]:
df_founders = pd.read_csv("berkeley_features_dataset.csv")
df_nonfounders = pd.read_csv("berkeley_nonfounders_features_dataset.csv")

# df_nonfounders = df_nonfounders[:630]
# df_founders["Company_founded"] = 1

df_all = df_founders.append(df_nonfounders, ignore_index=True)
df_all = df_all.sample(frac=1).reset_index(drop=True)

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" ]]

X_train, X_test, y_train, y_test = train_test_split(X, y, train_size= 0.33, random_state = 42)
clf_dt_entropy = DecisionTreeClassifier(criterion='entropy', max_depth=5, random_state=42).fit(X_train, y_train)

print('Decision Tree: Training set (Berkeley) score: {:.4f}'.format(clf_dt_entropy.score(X_train, y_train)))
print('Decision Tree: Test set (Berkeley) score : {:.4f}'.format(clf_dt_entropy.score(X_test, y_test)))


from sklearn.ensemble import RandomForestClassifier
clf_rf = RandomForestClassifier(criterion = 'entropy', random_state = 42, max_depth= 5, min_samples_leaf=3).fit(X_train, y_train)
print('Random Forest: Training set (Berkeley) score: {:.4f}'.format(clf_rf.score(X_train, y_train)))
print('Random Forest: Test set (Berkeley) score: {:.4f}'.format(clf_rf.score(X_test, y_test)))
Decision Tree: Training set (Berkeley) score: 0.7906
Decision Tree: Test set (Berkeley) score : 0.7626
Random Forest: Training set (Berkeley) score: 0.8081
Random Forest: Test set (Berkeley) score: 0.7870
In [8]:
# 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

clf_rf = RandomForestClassifier(criterion = 'entropy', random_state = 42, max_depth= 5, min_samples_leaf=3)
clf_dt = DecisionTreeClassifier(criterion='entropy', max_depth=5, random_state=42)
clf_rf_isotonic = CalibratedClassifierCV(clf_rf, cv=5, method='isotonic')
clf_dt_isotonic = CalibratedClassifierCV(clf_dt, cv=5, method='isotonic')

clf_list = [
    (clf_rf, "Random Forest"),
    (clf_dt, "Decision Tree"),
    (clf_rf_isotonic, "Random Forest + Isotonic"),
    (clf_dt_isotonic, "Decision Tree + Isotonic"),
]

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 [6]:
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 [6]:
Brier loss Log loss Precision Recall F1 Roc auc
Classifier
Random Forest 0.148618 0.457013 0.712991 0.609819 0.657382 0.737246
Decision Tree 0.155505 0.704047 0.674479 0.669251 0.671855 0.745594
Random Forest + Isotonic 0.148410 0.481405 0.703504 0.674419 0.688654 0.758862
Decision Tree + Isotonic 0.152292 0.467785 0.722892 0.620155 0.667594 0.744550
In [9]:
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"]]

X_train_telaviv, X_test_telaviv, y_train_telaviv, y_test_telaviv = train_test_split(X, y, test_size = 1, random_state = 42)

df_founders_stanford = pd.read_csv("stanford_features_dataset.csv")
df_nonfounders_stanford = pd.read_csv("stanford_nonfounders_features_dataset.csv")

df_all_stanford = df_founders_stanford.append(df_nonfounders_stanford, ignore_index=True)
df_all_stanford = df_all_stanford.sample(frac=1).reset_index(drop=True)

X_stanford = df_all_stanford.drop(['Company_founded'], axis=1)
y_stanford = df_all_stanford['Company_founded']
X_stanford = X_stanford[["h-index","i10-index","publications","pub_citation_mean","pub_citation_sum","linked_patents_to_publications",
       "patents", "pat_citation_mean", "pat_citation_sum", "grants", "affiliations"]]

X_train, X_test, y_train, y_test = train_test_split(X_stanford, y_stanford, train_size= 1, random_state = 42)

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

from sklearn.calibration import CalibratedClassifierCV, CalibrationDisplay

clf_rf = RandomForestClassifier(criterion = 'entropy', random_state = 42, max_depth= 5, min_samples_leaf=3)
clf_dt = DecisionTreeClassifier(criterion='entropy', max_depth=5, random_state=42)
clf_rf_isotonic = CalibratedClassifierCV(clf_rf, cv=5, method='isotonic')
clf_dt_isotonic = CalibratedClassifierCV(clf_dt, cv=5, method='isotonic')

clf_list = [
    (clf_rf, "Random Forest"),
    (clf_dt, "Decision Tree"),
    (clf_rf_isotonic, "Random Forest + Isotonic"),
    (clf_dt_isotonic, "Decision Tree + Isotonic"),
]

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_telaviv, y_train_telaviv)
    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 [10]:
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_telaviv, y_train_telaviv)
    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 [10]:
Brier loss Log loss Precision Recall F1 Roc auc
Classifier
Random Forest 0.145954 0.443187 0.805647 0.666124 0.729272 0.773409
Decision Tree 0.149371 0.537632 0.831111 0.609121 0.703008 0.758611
Random Forest + Isotonic 0.144893 0.439046 0.810287 0.658523 0.726565 0.772027
Decision Tree + Isotonic 0.148001 0.451627 0.794214 0.655809 0.718406 0.764825
In [11]:
#training on telaviv, testing on stanford
#adding the before features for training and testing
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", "publications_before_founding",
#        "patents_before_founding", "grants_before_founding", "publications_after_founding", "patents_after_founding",
#        "grants_after_founding", "activities_total", "activities_before_founding", "activities_after_founding" ]]

# 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", "publications_before_founding",
#        "patents_before_founding", "grants_before_founding", "activities_before_founding" ]]

X = X[["linked_patents_to_publications","pat_citation_mean", "h-index", "pub_citation_mean",
        "affiliations", "publications_before_founding",
       "patents_before_founding", "grants_before_founding", "activities_before_founding" ]]


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1, random_state = 42)
clf_dt = DecisionTreeClassifier(criterion='entropy', max_depth=5, random_state=42).fit(X_train, y_train)
clf_rf = RandomForestClassifier(criterion = 'entropy', max_depth= 5, random_state = 42, min_samples_leaf=3).fit(X_train, y_train)

df_founders_stanford = pd.read_csv("stanford_features_dataset.csv")
df_nonfounders_stanford = pd.read_csv("stanford_nonfounders_features_dataset.csv")

df_all_stanford = df_founders_stanford.append(df_nonfounders_stanford, ignore_index=True)
df_all_stanford = df_all_stanford.sample(frac=1).reset_index(drop=True)


X_stanford = df_all_stanford.drop(['Company_founded'], axis=1)
y_stanford = df_all_stanford['Company_founded']
# X_stanford = X_stanford[["h-index","i10-index","publications","pub_citation_mean","pub_citation_sum","linked_patents_to_publications",
#        "patents", "pat_citation_mean", "pat_citation_sum", "grants", "affiliations", "publications_before_founding",
#        "patents_before_founding", "grants_before_founding","activities_before_founding" ]]
X_stanford = X_stanford[["linked_patents_to_publications", "pat_citation_mean", "h-index", "pub_citation_mean",
        "affiliations", "publications_before_founding",
       "patents_before_founding", "grants_before_founding", "activities_before_founding" ]]

X_train, X_test, y_train, y_test = train_test_split(X_stanford, y_stanford, train_size= 1, random_state = 42)
# y_pred_gini = clf_gini.predict(X_test)
print('Decision Tree (Berkeley training): Test set (Stanford) score : {:.4f}'.format(clf_dt.score(X_test, y_test)))
print('Random Forest (Berkeley training): Test set (Stanford) score: {:.4f}'.format(clf_rf.score(X_test, y_test)))
# print('Model accuracy score with criterion gini index: {0:0.4f}'. format(accuracy_score(y_test, y_pred_gini)))
Decision Tree (Berkeley training): Test set (Stanford) score : 0.9325
Random Forest (Berkeley training): Test set (Stanford) score: 0.9299
In [12]:
X = df_all.drop(['Company_founded'], axis=1)
y = df_all['Company_founded']
X = X[["pub_citation_mean", "linked_patents_to_publications", "pat_citation_mean", "h-index",
        "affiliations", "publications_before_founding",
       "patents_before_founding", "grants_before_founding", "activities_before_founding" ]]

X_train_telaviv, X_test_telaviv, y_train_telaviv, y_test_telaviv = train_test_split(X, y, test_size = 1, random_state = 42)

df_founders_stanford = pd.read_csv("stanford_features_dataset.csv")
df_nonfounders_stanford = pd.read_csv("stanford_nonfounders_features_dataset.csv")

df_all_stanford = df_founders_stanford.append(df_nonfounders_stanford, ignore_index=True)
df_all_stanford = df_all_stanford.sample(frac=1).reset_index(drop=True)

X_stanford = df_all_stanford.drop(['Company_founded'], axis=1)
y_stanford = df_all_stanford['Company_founded']
X_stanford = X_stanford[["pub_citation_mean", "linked_patents_to_publications", "pat_citation_mean", "h-index",
        "affiliations", "publications_before_founding",
       "patents_before_founding", "grants_before_founding", "activities_before_founding" ]]

X_train, X_test, y_train, y_test = train_test_split(X_stanford, y_stanford, train_size= 1, random_state = 42)

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

from sklearn.calibration import CalibratedClassifierCV, CalibrationDisplay

clf_rf = RandomForestClassifier(criterion = 'entropy', random_state = 42, max_depth= 5, min_samples_leaf=3)
clf_dt = DecisionTreeClassifier(criterion='entropy', max_depth=5, random_state=42)
clf_rf_isotonic = CalibratedClassifierCV(clf_rf, cv=5, method='isotonic')
clf_dt_isotonic = CalibratedClassifierCV(clf_dt, cv=5, method='isotonic')

clf_list = [
    (clf_rf, "Random Forest"),
    (clf_dt, "Decision Tree"),
    (clf_rf_isotonic, "Random Forest + Isotonic"),
    (clf_dt_isotonic, "Decision Tree + Isotonic"),
]

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_telaviv, y_train_telaviv)
    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 [13]:
feature_importance=pd.DataFrame({
    'rfc':clf_rf.feature_importances_,
    'dt':clf_dt.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()

#try the features before the founding year
# pubs patents not all of them and check accuracy
In [5]:
#training on telaviv, testing on stanford
#this was the version which I had not attached the before/after founding metrics
X = df_all.drop(['Company_founded'], axis=1)
y = df_all['Company_founded']
X = X[["h-index","i10-index", "g-index", "industry_collab_papers", "grant_research_impact", "grant_innovation_impact"
       ,"publications","pub_citation_mean","linked_patents_to_publications","patents"
       ,"pat_citation_mean", "grants", "affiliations"]]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1, random_state = 42)
clf_dt = DecisionTreeClassifier(criterion='entropy', max_depth=5, random_state=42).fit(X_train, y_train)
clf_rf = RandomForestClassifier(criterion = 'entropy', max_depth= 5, random_state = 42, min_samples_leaf=3).fit(X_train, y_train)

df_founders_stanford = pd.read_csv(r"datasets_complete\\stanford_features_dataset.csv")
df_nonfounders_stanford = pd.read_csv(r"datasets_complete\\stanford_nonfounders_features_dataset.csv")

df_all_stanford = df_founders_stanford.append(df_nonfounders_stanford, ignore_index=True)
df_all_stanford = df_all_stanford.sample(frac=1).reset_index(drop=True)


X_stanford = df_all_stanford.drop(['Company_founded'], axis=1)
y_stanford = df_all_stanford['Company_founded']
X_stanford = X_stanford[["h-index","i10-index", "g-index", "industry_collab_papers", "grant_research_impact", "grant_innovation_impact"
       ,"publications","pub_citation_mean","linked_patents_to_publications","patents"
       ,"pat_citation_mean", "grants", "affiliations"]]

X_train, X_test, y_train, y_test = train_test_split(X_stanford, y_stanford, train_size= 1, random_state = 42)
# y_pred_gini = clf_gini.predict(X_test)
print('Decision Tree (Berkeley training): Test set (Stanford) score : {:.4f}'.format(clf_dt.score(X_test, y_test)))
print('Random Forest (Berkeley training): Test set (Stanford) score: {:.4f}'.format(clf_rf.score(X_test, y_test)))
# print('Model accuracy score with criterion gini index: {0:0.4f}'. format(accuracy_score(y_test, y_pred_gini)))
Decision Tree (Berkeley training): Test set (Stanford) score : 0.7791
Random Forest (Berkeley training): Test set (Stanford) score: 0.7833
In [6]:
#training on telaviv, testing on stanford
#this was the version which I had not attached the before/after founding metrics
X = df_all.drop(['Company_founded'], axis=1)
y = df_all['Company_founded']
X = X[["h-index","i10-index", "g-index", "industry_collab_papers", "grant_research_impact", "grant_innovation_impact"
       ,"publications","pub_citation_mean","linked_patents_to_publications","patents"
       ,"pat_citation_mean", "grants", "affiliations"]]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1, random_state = 42)
clf_dt = DecisionTreeClassifier(criterion='entropy', max_depth=5, random_state=42).fit(X_train, y_train)
clf_rf = RandomForestClassifier(criterion = 'entropy', max_depth= 5, random_state = 42, min_samples_leaf=3).fit(X_train, y_train)

df_founders_stanford = pd.read_csv(r"datasets_complete\\telaviv_features_dataset.csv")
df_nonfounders_stanford = pd.read_csv(r"datasets_complete\\telaviv_nonfounders_features_dataset.csv")

df_all_stanford = df_founders_stanford.append(df_nonfounders_stanford, ignore_index=True)
df_all_stanford = df_all_stanford.sample(frac=1).reset_index(drop=True)


X_stanford = df_all_stanford.drop(['Company_founded'], axis=1)
y_stanford = df_all_stanford['Company_founded']
X_stanford = X_stanford[["h-index","i10-index", "g-index", "industry_collab_papers", "grant_research_impact", "grant_innovation_impact"
       ,"publications","pub_citation_mean","linked_patents_to_publications","patents"
       ,"pat_citation_mean", "grants", "affiliations"]]
X_train, X_test, y_train, y_test = train_test_split(X_stanford, y_stanford, train_size= 1, random_state = 42)
# y_pred_gini = clf_gini.predict(X_test)
print('Decision Tree (Berkeley training): Test set (telaviv) score : {:.4f}'.format(clf_dt.score(X_test, y_test)))
print('Random Forest (Berkeley training): Test set (telaviv) score: {:.4f}'.format(clf_rf.score(X_test, y_test)))
# print('Model accuracy score with criterion gini index: {0:0.4f}'. format(accuracy_score(y_test, y_pred_gini)))
Decision Tree (Berkeley training): Test set (telaviv) score : 0.8428
Random Forest (Berkeley training): Test set (telaviv) score: 0.8551
In [7]:
feature_importance=pd.DataFrame({
    'rfc':clf_rf.feature_importances_,
    'dt':clf_dt.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()
In [15]:
feature_importance=pd.DataFrame({
    'rfc':clf_rf.feature_importances_,
    'dt':clf_dt.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()
In [35]:
from dtreeviz.trees import dtreeviz # remember to load the package

viz = dtreeviz(clf_gini, X_train, y_train,
                target_name="Company_founded",
                feature_names=X_train.columns,
                class_names=[0,1],
                fancy=False)

viz
Out [35]:
In [18]:
from sklearn.model_selection import cross_val_score
clf_gini = DecisionTreeClassifier(criterion='gini', max_depth=4, random_state=42)
scores = cross_val_score(clf_gini, X_train, y_train, cv=10)
scores
print("%0.2f accuracy with a standard deviation of %0.2f" % (scores.mean(), scores.std()))

from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV

clf = DecisionTreeClassifier(criterion='entropy', random_state=42)

parameters = {'max_depth':range(3,20), 'min_samples_split':range(2,10)}
clf = GridSearchCV(clf, parameters, n_jobs=4)
clf.fit(X, y)
tree_model = clf.best_estimator_
print (clf.best_score_, clf.best_params_) 

#performed cross validation to make sure the model's generalization
#used gridsearch to estimate model hyperparameter tuning
0.97 accuracy with a standard deviation of 0.02