# I'm trying to read the data given by python and apply KNN. However my graph has no data and I get ax and y must have same first dimension, but have shapes (8,) and (1,) error.
# I have tried using .shape to no luck.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
df = pd.read_csv ('/content/heart.csv')
df.head()
df.shape
x = df.drop('target', axis=1).values
y = df['target'].values
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x,y, test_size=0.4,random_state=42, stratify=y)
from sklearn.neighbors import KNeighborsClassifier
neighbors = np.arange(1,9)
train_accuracy = np.empty(len(neighbors))
test = np.empty(len(neighbors))
knn = KNeighborsClassifier(n_neighbors=2)
knn.fit(x_train, y_train)
train_accuracy = knn.score(x_train,y_train)
test_accuracy = knn.score(x_test, y_test)
test_accuracy = knn.score(x_test, y_test)
plt.title('k-NN Varying number of neighbors')
plt.plot(neighbors, test_accuracy, label='Testing Accuracy')
plt.plot(neighbors, train_accuracy, label='Training Accuracy')
plt.legend()
plt.xlabel('Number of neighbors')
plt.ylabel('Accuracy')
plt.show()
Should plot a graph,
however, the graph has no info on it.
The shapes (8,) and (1,) error
is because you are trying to plot a graph with neighbors
(numpy array) on x-axis which has 8 values inside it and test_accuracy
on y-axis which has only one value the score
. This graph doesn't make sense and cannot be plotted. I'm not sure what you are trying to achieve in the program. Can you update with the result you want?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.