我在尝试对我的样本数据绘制SVM时遇到了一个问题:图表看起来完全不对劲,这很奇怪,因为我使用了这里的示例代码(更具体地说,是“What is happening?”部分)。他们的代码对我来说运行得很好,所以我认为问题可能与我的数据有关。我注意到拟合系数非常小,这可以理解地破坏了线条。
这是可复现的代码。
输出结果是:
如你所见,结果很糟糕。如果有人能解释我做错了什么,我将不胜感激。
编辑:我实际上已经成功解决了这个问题。这是我的代码:
plt.figure(figsize=(7,7))np.random.seed(420)ran = np.arange(-5,6)st = 1b, p = np.array([ (-3+np.random.normal(0,st), -2.5+np.random.normal(0,st)) for i in range(25) ]+\[ (2.5+np.random.normal(0,st), 3.5+np.random.normal(0,st)) for i in range(25) ]), np.array([ (np.random.normal(0,st), np.random.normal(0,st)) for i in range(50) ])plt.scatter(b[:,0], b[:,1], color='cornflowerblue')plt.scatter(p[:,0], p[:,1], color='magenta')plt.xlabel('$X_1$', fontsize=15)plt.ylabel('$X_2$', fontsize=15)x, y = np.concatenate( (np.concatenate( (b[:25], p) ), b[-25:]) ), [0]*25 + [1]*50 + [0]*25ft = svm.SVC(kernel='linear').fit(x, y)by, bx = np.meshgrid([-5, 6], [-5, 6])bo = ft.decision_function(np.vstack([by.ravel(), bx.ravel()]).T).reshape(bx.shape).Txx, yy = np.meshgrid(np.arange(-5.1, 4.6, 0.01), np.arange(-5.1, 5.6, 0.01))Z = ft.predict(np.c_[xx.ravel(), yy.ravel()])Z = Z.reshape(xx.shape)C = plt.contourf(xx, yy, Z,colors='none', hatches=['.'])colors=['cornflowerblue', 'magenta']for j, collection in enumerate(C.collections): if j == 0: collection.set_edgecolor(colors[0]) else: collection.set_edgecolor(colors[1])plt.contour(bx, by, bo, colors='0', levels=[-1, 0, 1], linestyles=['--', '-', '--'])plt.ylim(-5, 5.5)plt.xlim(-5, 4.5)plt.show()
结果是:
回答: