| 42 | |
| 43 | # 画决策边界 |
| 44 | def plot_decisionBoundary(X, y, model, class_='linear'): |
| 45 | plt = plot_data(X, y) |
| 46 | |
| 47 | # 线性边界 |
| 48 | if class_ == 'linear': |
| 49 | w = model.coef_ |
| 50 | b = model.intercept_ |
| 51 | xp = np.linspace(np.min(X[:, 0]), np.max(X[:, 0]), 100) |
| 52 | yp = -(w[0, 0] * xp + b) / w[0, 1] |
| 53 | plt.plot(xp, yp, 'b-', linewidth=2.0) |
| 54 | plt.show() |
| 55 | else: # 非线性边界 |
| 56 | x_1 = np.transpose(np.linspace(np.min(X[:, 0]), np.max(X[:, 0]), 100).reshape(1, -1)) |
| 57 | x_2 = np.transpose(np.linspace(np.min(X[:, 1]), np.max(X[:, 1]), 100).reshape(1, -1)) |
| 58 | X1, X2 = np.meshgrid(x_1, x_2) |
| 59 | vals = np.zeros(X1.shape) |
| 60 | for i in range(X1.shape[1]): |
| 61 | this_X = np.hstack((X1[:, i].reshape(-1, 1), X2[:, i].reshape(-1, 1))) |
| 62 | vals[:, i] = model.predict(this_X) |
| 63 | |
| 64 | plt.contour(X1, X2, vals, [0, 1], color='blue') |
| 65 | plt.show() |
| 66 | |
| 67 | |
| 68 | if __name__ == "__main__": |