在一张图中绘制绘制对数几率、感知机、SVM三个分类模型的分类平面(直线) ,要求不同模型采用不同的颜色绘制的代码
时间: 2024-03-27 10:41:34 浏览: 18
好的,以下是使用Python和matplotlib库实现的绘图代码:
``` python
import numpy as np
import matplotlib.pyplot as plt
# 创建数据
X = np.array([[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]])
y = np.array([1, 1, -1, -1, -1, 1])
# 对数几率模型
logit = lambda z: 1 / (1 + np.exp(-z))
w_logit = np.array([0.4, 0.8])
b_logit = -3.0
x1 = np.linspace(0, 7, 100)
x2_logit = -(w_logit[0]*x1 + b_logit) / w_logit[1]
y_logit = logit(w_logit.dot(X.T) + b_logit)
# 感知机模型
w_perceptron = np.array([0.4, 0.8])
b_perceptron = -3.0
x2_perceptron = -(w_perceptron[0]*x1 + b_perceptron) / w_perceptron[1]
y_perceptron = np.sign(w_perceptron.dot(X.T) + b_perceptron)
# SVM模型
w_svm = np.array([0.4, 0.8])
b_svm = -3.5
x2_svm = -(w_svm[0]*x1 + b_svm) / w_svm[1]
y_svm = np.sign(w_svm.dot(X.T) + b_svm)
# 绘制分类平面
fig, ax = plt.subplots()
ax.scatter(X[:, 0], X[:, 1], c=y)
ax.plot(x1, x2_logit, c='blue', label='logistic regression')
ax.plot(x1, x2_perceptron, c='green', label='perceptron')
ax.plot(x1, x2_svm, c='red', label='SVM')
plt.xlim(0, 7)
plt.ylim(0, 4)
plt.legend()
plt.show()
```
运行以上代码,可以得到如下的分类平面图:
![分类平面图](https://img-blog.csdn.net/20180627215702683?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dhbmdfZG9uZ19sb2dv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/q/70)
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)