需要二维数组但已经是二维了?

问题描述 投票:0回答:0

我正在尝试实现 KNN 机器学习算法,但我正在努力做某事

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn import neighbors, datasets
from matplotlib.colors import ListedColormap

data = np.loadtxt("accelerometer.csv", skiprows=1, delimiter=",")
ds = np.concatenate((data, np.zeros((data.shape[0],1))), 1)

threshold = 0.25*max(max(abs(data[:,2])),abs(max(data[:,3])))
for i in range(data.shape[0]):
    a,b,c = abs(data[i,2]),abs(data[i,3]),abs(data[i,4])
    if max(a,b,c)>threshold:
        ds[i,5]=1

X = np.hstack((data[:, :5], np.zeros((data.shape[0], 1))))
X = X[X[:, 0] == 1]
X = X[:, [2,3,4]]
taille = len(X)
target = ds[:, 5]
target = target[:taille]

n_neighbors = 10
clf = neighbors.KNeighborsClassifier(n_neighbors)
clf.fit(X, target)
clf.predict(X)
clf.score(X,target)

h = 2
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000', '#00FF00', '#0000FF'])

clf = neighbors.KNeighborsClassifier(n_neighbors, weights='uniform')
clf.fit(X, target)

x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
z_min, z_max = X[:, 2].min() - 1, X[:, 2].max() + 1
xx, yy, zz = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h), np.arange(z_min, z_max, h))

mesh_data = np.c_[xx.ravel(), yy.ravel(), zz.ravel()]
Z = clf.predict(np.c_[xx.ravel(), yy.ravel(), zz.ravel()])
Z = Z.reshape((-1, 1))

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(xx, yy, zz)
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=target, cmap=cmap_bold)
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_zlim(zz.min(), zz.max())
plt.show()

问题出在第 49 行的 Z:

ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=target, cmap=cmap_bold)
即使 Z 是二维的,我也会出现“参数 Z 必须是二维的”错误。它应该是保存我的 3D 地图的所有预测结果的地方。有什么线索吗?

如果需要,我的数据库是https://archive.ics.uci.edu/ml/datasets/Accelerometer

python numpy machine-learning knn
© www.soinside.com 2019 - 2024. All rights reserved.