可视化函数
1.matplotlib.pyplot里contour
画等高线
def visualize(data, C, res):
"""
将模型结果可视化
"""
# 创建一个图形框
fig = plt.figure(figsize=(12, 6), dpi=80)
# 在图形框里画两幅图
ax = fig.add_subplot(1, 2, 1)
label1 = data[data["y"]>0]
ax.scatter(label1[["x1"]], label1[["x2"]], marker="o")
label0 = data[data["y"]==0]
ax.scatter(label0[["x1"]], label0[["x2"]], marker="^", color="k")
x1 = np.linspace(-4, 6, 100)
x2 = np.linspace(-8, 8, 100)
X1, X2 = np.meshgrid(x1, x2)
# Soft margin
soft = res[0].decision_function(np.c_[X1.ravel(), X2.ravel()])
soft = soft.reshape(X1.shape)
CS = ax.contour(X1, X2, soft, levels=[-1, 0, 1], colors=["r", "r", "r"],
linestyles=["--", "-", "--"])
# Hard margin
hard = res[-1].decision_function(np.c_[X1.ravel(), X2.ravel()])
hard = hard.reshape(X1.shape)
ax.contour(X1, X2, hard, levels=[-1, 0, 1], colors=["g", "g", "g"],
linestyles=["--", "-.", "--"])
ax1 = fig.add_subplot(1, 2, 2)
# Python2和Python3的map并不兼容,所以使用list(map)
coef = list(map(lambda x: x.coef_, res))
margin = list(map(lambda x: 2.0 / np.sqrt(x.dot(x.T)).item(), coef))
ax1.plot(C, margin, label="margin width")
ax1.set_xscale('log')
legend = plt.legend(shadow=True, loc="best")
plt.show()
图: