#我正在尝试读取python给定的数据并应用KNN。但是我的图形没有数据,并且我得到的x和y必须具有相同的第一维,但形状有(8,)和(1,)误差。
# 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.
答案 0 :(得分:0)
shapes (8,) and (1,) error
是因为您试图在x轴上绘制带有neighbors
(numpy数组)的图形,其中内部有8个值,在y轴上绘制test_accuracy
score
中只有一个值。此图没有意义,无法绘制。我不确定您要在程序中实现什么。您可以更新所需的结果吗?