tryhardyoninfinityhz

Dhruv Kothai and Aadhathmik Varahagiri: Titanic Project

Dec 8th, 2023
970
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.03 KB | None | 0 0
  1. #by Dhruv and Aadhyathmik
  2.  
  3. from sklearn.linear_model import LinearRegression
  4. from sklearn.feature_selection import RFE
  5. # Compare Algorithms
  6. import pandas as pd
  7. import matplotlib.pyplot as plt
  8. import numpy as np
  9.  
  10. from matplotlib import pyplot
  11. from sklearn.metrics import accuracy_score
  12. from sklearn.model_selection import KFold, train_test_split
  13. from sklearn.model_selection import cross_val_score
  14. from sklearn.linear_model import LinearRegression
  15. from sklearn.linear_model import LinearRegression
  16. from sklearn.feature_selection import RFE
  17. from sklearn.linear_model import LogisticRegression
  18. from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier
  19. import seaborn as sns
  20. from sklearn.svm import SVC
  21. from sklearn.tree import DecisionTreeRegressor, DecisionTreeClassifier
  22. from sklearn.neural_network import MLPClassifier
  23.  
  24. import warnings
  25.  
  26. warnings.filterwarnings("ignore")
  27.  
  28.  
  29. def sibSpToInt(SibSp):
  30.     if SibSp >= 1:
  31.         SibSp = 'Accompanied'
  32.         return SibSp
  33.     SibSp = 'Alone'
  34.     return SibSp
  35.  
  36. def ageToInt(age):
  37.     if age < 18:
  38.         age = 1
  39.         return age
  40.     elif age < 38:
  41.         age = 2
  42.         return age
  43.     else:
  44.         age = 3
  45.         return age
  46.  
  47.  
  48.  
  49.  
  50.  
  51. cabin_set = set([])
  52.  
  53. path = '/Users/dhruvk/Desktop/titanic/'
  54. train = pd.read_csv(path + "train.csv")
  55. test = pd.read_csv(path + "test.csv")
  56. submission = pd.read_csv(path + "gender_submission.csv")
  57.  
  58. df = train
  59. df = df.drop(['Cabin', 'Name', 'Parch', 'Ticket', 'Embarked'], axis=1)
  60. df['Age'] = df['Age'].fillna(df['Age'].median())
  61. df['Age'] = df['Age'].apply(ageToInt)
  62. df['SibSp'] = df['SibSp'].apply(sibSpToInt)
  63. encoded_df = pd.get_dummies(df['SibSp'], prefix='SibSp')
  64. df = pd.concat([df, encoded_df], axis=1)
  65. df = df.drop('SibSp', axis=1)
  66.  
  67. trainset, testset = train_test_split(df, test_size=0.3, random_state=0)
  68.  
  69. genderToInt = {'male': 1, 'female': 2}
  70. trainset['Sex'] = trainset['Sex'].map(genderToInt)
  71. testset['Sex'] = testset['Sex'].map(genderToInt)
  72.  
  73. Y_train = trainset['Survived']
  74. X_train = trainset[['Pclass', 'Sex', 'Age', 'Fare', 'SibSp_Accompanied', 'SibSp_Alone']]
  75. X_test = testset[['Pclass', 'Sex', 'Age', 'Fare', 'SibSp_Accompanied', 'SibSp_Alone']]
  76. Y_test = testset['Survived']
  77.  
  78. dtreeC = DecisionTreeClassifier()
  79. dtreeC.fit(X_train, Y_train)
  80. y_test1 = dtreeC.predict(X_test)
  81. # print(len(Y_test, y_test))
  82.  
  83. print("Decision Tree Classifier Accuracy:",accuracy_score(y_test1, Y_test) * 100)
  84.  
  85. models = []
  86. models.append(("Decision Tree Classifier", dtreeC))
  87.  
  88. ltree = LogisticRegression()
  89. ltree.fit(X_train, Y_train)
  90. y_test2 = ltree.predict(X_test)
  91.  
  92. print("Logistic Regression Accuracy:", accuracy_score(y_test2, Y_test) * 100)
  93.  
  94. models.append(("Logistic Regression", ltree))
  95.  
  96. ada_clf = AdaBoostClassifier(
  97.     DecisionTreeClassifier(max_depth=5), n_estimators=200,
  98.     algorithm="SAMME.R", learning_rate=.19, random_state=42)
  99. ada_clf.fit(X_train, Y_train)
  100. y_test3 = ada_clf.predict(X_test)
  101.  
  102. print("Ada Boost Classifier Accuracy:", accuracy_score(y_test3, Y_test) * 100)
  103.  
  104. models.append(("Ada Boost Classifier", ada_clf))
  105.  
  106. for depth in [3,4,5, 6]:
  107.     rnd_clf = RandomForestClassifier(n_estimators=500, max_depth=depth, n_jobs=-1, random_state=42)
  108.     rnd_clf.fit(X_train, Y_train)
  109.     y_pred_rf = rnd_clf.predict(X_test)
  110.     print("Random Forest Classifier Depth "+str(depth)+" Accuracy: ", accuracy_score(y_pred_rf, Y_test) * 100)
  111.     models.append(("Random Forest: Depth "+str(depth), rnd_clf))
  112.  
  113.  
  114. results = []
  115. names = []
  116. # scoring = 'accuracy'
  117. scoring = 'r2'
  118. for name, model in models:
  119.     kfold = KFold(n_splits=10)  # , random_state=7)
  120.     # kfold = KFold(n_splits=10) #, random_state=None)
  121.     cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)
  122.     results.append(cv_results)
  123.     names.append(name)
  124.     msg = "%s: %f (%f)" % (name, cv_results.mean(), cv_results.std())
  125.     print(msg)
  126. # boxplot algorithm comparison
  127. fig = pyplot.figure()
  128. fig.suptitle('Algorithm Comparison')
  129. ax = fig.add_subplot(111)
  130. pyplot.boxplot(results)
  131. ax.set_xticklabels(names)
  132. pyplot.show()
Advertisement
Add Comment
Please, Sign In to add comment