你能帮我修改一下二维可视化内核的代码吗

2024-04-23 10:00:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将内核绘制成2D,但遇到了一个问题。这里我在二维空间绘制多项式核。 你们能帮帮我吗。谢谢

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.datasets import make_blobs, make_circles

#Generate the data
X, y = make_blobs(centers=4, random_state=8)  
y = y % 2

#Linear model
linear_svm_3d = LinearSVC().fit(X_3D, y)  
coef, intercept = linear_svm_3d.coef_.ravel(), linear_svm_3d.intercept_  

#Map data into 3D
to3d = lambda x : [x[0] ** 2, np.sqrt(2) * x[0] * x[1], x[1] ** 2]
X_3D = np.array(list(map(to3d, X)))

# show linear decision boundary  
figure = plt.figure()  
xx = np.linspace(X_3D[:, 0].min(), X_3D[:, 0].max(), 50)  
yy = np.linspace(X_3D[:, 1].min(), X_3D[:, 1].max(), 50)  
XX, YY = np.meshgrid(xx, yy)  
ZZ = (coef[0] * XX + coef[1] * YY + intercept) / -coef[2]  
ZZ = YY ** 2  
dec = linear_svm_3d.decision_function(np.c_[XX.ravel(), YY.ravel(), ZZ.ravel()])  
plt.contourf(XX, YY, dec.reshape(XX.shape), levels=[dec.min(), 0, dec.max()], cmap=mglearn.cm2, alpha=0.5)  
plt.scatter(X[:, 0], X[:, 1], c=y, s=60, cmap=mglearn.cm2)  
plt.xlabel("feature1")
plt.ylabel("feature2")  
plt.show()

这是错误:

ValueError                                Traceback (most recent call last)
<ipython-input-48-6b9361a03b65> in <module>()
     26 ZZ = YY ** 2
     27 dec = linear_svm_3d.decision_function(np.c_[XX.ravel(), YY.ravel(), ZZ.ravel()])
---> 28 plt.contourf(XX, YY, dec.reshape(XX.shape), levels=[dec.min(), 0, dec.max()], cmap=mglearn.cm2, alpha=0.5)
     29 plt.scatter(X[:, 0], X[:, 1], c=y, s=60, cmap=mglearn.cm2)
     30 plt.xlabel("feature1")

ValueError: Contour levels must be increasing

Tags: importnppltminmaxdeccmaplinear