hw7_correct

.py

School

Arizona State University *

*We aren’t endorsed by this school

Course

591PYTHON

Subject

Electrical Engineering

Date

Jan 9, 2024

Type

py

Pages

8

Uploaded by UltraBoulderHare16

################################################################################### # # Additional project for EEE591 # # # # The code for the first part has not been changed # # from the previous submission. However, in my previous submission, I used combined# # accuracies, here I am using Test accuracies as mentioned in the problem statement# ################################################################################### # import matplotlib.pyplot as plt from sklearn import datasets import numpy as np # needed for arrays from sklearn.model_selection import train_test_split # splits database from sklearn.preprocessing import StandardScaler # standardize data # the algorithm from sklearn.metrics import accuracy_score # grade the results import pandas as pd from pandas import DataFrame,read_csv import seaborn as sns from sklearn.linear_model import Perceptron # Perceptron Algorithm from sklearn.svm import SVC # SVM Algorithm from sklearn.linear_model import LogisticRegression # Logistic Regression Algorithm from sklearn.ensemble import RandomForestClassifier # Random Forest Algorithm from sklearn.neighbors import KNeighborsClassifier # KNN Algorithm from sklearn.tree import DecisionTreeClassifier # Decision Tree Algorithm from sklearn.tree import export_graphviz from sklearn.model_selection import train_test_split # split the data ################################################################################### ####### # The first part (below) of the code reads the data and # # converts it into aalatable form # # Note : throughout the code, ignore comments which begin with the header Debug Comments # ################################################################################### ####### heartdata = pd.read_csv ("heart1.csv") # read the data into a dataframe X = heartdata [['age','sex','cpt', 'rbp','sc','fbs','rer','mhr','eia','opst','dests','nmvcf','thal' ]] #extracting only the features from the dataframe Y = heartdata [['a1p2' ]] #extracting the classifcation X_array = X.to_numpy() #converting the dataframes to arrays for easy manipulation
Y_array = Y.to_numpy() X_train, X_test, Y_train, Y_test= \ train_test_split(X_array,Y_array,test_size=0.3,random_state=0) #splitting data in train and test # converting Y_train and Y_test from an array of arrays to a singular array Y_test_normal = [] for i in Y_test : Y_test_normal.append(i[0]) Y_test = Y_test_normal Y_train_normal = [] for i in Y_train : Y_train_normal.append(i[0]) Y_train = Y_train_normal ############################################### # Converting above data into standard scalars # ############################################### sc = StandardScaler() # create the standard scalar sc.fit(X_train) # compute the required transformation X_train_std = sc.transform(X_train) # apply to the training data X_test_std = sc.transform(X_test) # and SAME transformation of test data ################################################################################### ########## # The next part of the code runs the extracted data through various machine learning models # # and prints out the "test accuracy", previously I used combined, but now test # ################################################################################### ########## ######################################################### # # # Running the above extracted data through a Perceptron # # # ######################################################### ppn = Perceptron(max_iter=100, tol=1e-3, eta0=0.001, # Increasing max_iter to 100 increased accuracy for me fit_intercept=True, random_state=0, verbose=True) ppn.fit(X_train_std, Y_train) # do the training print ("\n") print ("Results for perceptron are : \n") y_pred_ppn = ppn.predict(X_test_std) # applying on test data X_combined_std = np.vstack((X_train_std, X_test_std)) # vstack puts first array above the second in a vertical stack
y_combined = np.hstack((Y_train, Y_test)) # hstack puts first array to left of the second in a horizontal stack # The below part shows how the combination of test and train data did, but we are not going to use it here for eee591 project # but calculating just for reference y_combined_pred = ppn.predict(X_combined_std) ################################################### # printing test accuracy of perceptron # ################################################### print('Misclassified test samples of perceptron : %d' % \ (Y_test != y_pred_ppn).sum()) print ("Test accuracy of perceptron is : %.2f" % accuracy_score(Y_test, y_pred_ppn),"\n") #################################################### # # # Running data through SVM # # # #################################################### for c_val in [0.9]: # I found c_val = 0.9 yields highest value svm = SVC(kernel='linear', C=c_val, random_state=0) svm.fit(X_train_std, Y_train) # do the training y_pred_svm = svm.predict(X_test_std) # work on the test data # The below part shows how the combination of test and train data did, but we are not going to use it here for eee591 project # but calculating just for reference X_combined_std = np.vstack((X_train_std, X_test_std)) y_combined = np.hstack((Y_train, Y_test)) ################################################### # printing test accuracy of SVM # ################################################### print('\nMisclassified test samples of SVM : %d' % \ (Y_test != y_pred_svm).sum()) print ("Test accuracy of SVM is : %.2f" % accuracy_score(Y_test, y_pred_svm),"\n") #################################################################### # # # Running the data through Logistic Regression # # # #################################################################### for c_val in [1]: # c_val = 1 yielded highes combined accuracy for me lr = LogisticRegression(C=c_val, solver='liblinear', \ multi_class='ovr', random_state=0) lr.fit(X_train_std, Y_train) # apply the algorithm to training data # combine the train and test data X_combined_std = np.vstack((X_train_std, X_test_std)) # vstack puts first array
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
  • Access to all documents
  • Unlimited textbook solutions
  • 24/7 expert homework help