#Cp交叉验证,选择最优的k值进行判别分析from sklearn.model_selection import cross_val_score
from sklearn.neighbors import KNeighborsClassifierX = heart.iloc[:,0:5]
y = heart.loc[:,'y']
k_range =range(1,31)
k_scores =[]for k in k_range:knn = KNeighborsClassifier(n_neighbors=k)scores = cross_val_score(knn, X, y, cv=10, scoring='accuracy')k_scores.append(scores.mean())plt.plot(k_range, k_scores)
plt.xlabel('Value of K for KNN')
plt.ylabel('Cross-Validated Accuracy')#选择最优的k值
k = k_scores.index(max(k_scores))+1print('Optimal k: %d'% k)#绘制最优k值在图中的位置
plt.plot(k_range, k_scores)
plt.xlabel('Value of K for KNN')
plt.ylabel('Cross-Validated Accuracy')
plt.scatter(k,max(k_scores), color='red')#显示最优k直在图中等于多少
plt.text(k,max(k_scores),'(%d, %.2f)'%(k,max(k_scores)), ha='center', va='bottom')
plt.show()
#使用SVM进行分类import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_scorefrom sklearn.svm import SVC# Load the dataset
heart = pd.read_csv(r"heart.csv", sep=',')# Select features and target
X = heart.iloc[:,0:5]
y = heart.loc[:,'y']# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)# Initialize and fit the SVM classifier
svm = SVC(kernel='linear', C=1.0, random_state=0)
svm.fit(X_train, y_train)# Predict and print accuracy
y_pred = svm.predict(X_test)print('Accuracy: %.2f'% accuracy_score(y_test, y_pred))
Accuracy: 0.66
# Plot decision regions using PCA-transformed features
X_combined = np.vstack((X_train, X_test))
y_combined = np.hstack((y_train, y_test))
plot_decision_regions(X=X_combined, y=y_combined, classifier=svm, test_idx=range(len(y_train),len(y_train)+len(y_test)))
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.legend(loc='upper left')
plt.show()
# Import necessary librariesimport matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_graphviz
import pydotplus
from IPython.display import Image# Load the dataset
heart = pd.read_csv(r"heart.csv", sep=',')# Select features and target
X = heart.iloc[:,0:5]
y = heart.loc[:,'y']# Split the dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)# Initialize and fit the Decision Tree classifier
tree = DecisionTreeClassifier(max_depth=3, random_state=0)
tree.fit(X_train, y_train)# Predict and print accuracy
y_pred = tree.predict(X_test)print('Accuracy: %.2f'% accuracy_score(y_test, y_pred))# Export the decision tree to a file
export_graphviz(tree, out_file='tree.dot', feature_names=X.columns)# Convert the dot file to a png
graph = pydotplus.graph_from_dot_file('tree.dot')
Image(graph.create_png())# Plot decision regions using PCA-transformed features
X_combined = np.vstack((X_train, X_test))
y_combined = np.hstack((y_train, y_test))
plot_decision_regions(X=X_combined, y=y_combined, classifier=tree, test_idx=range(len(y_train),len(y_train)+len(y_test)))
plt.xlabel('Principal Component 1')
plt.ylabel('Principal Component 2')
plt.legend(loc='upper left')
plt.show()