八、人工分类
输入1 | 输入2 | 输出 |
---|---|---|
3 | 1 | 0 |
2 | 5 | 1 |
1 | 8 | 1 |
6 | 4 | 0 |
5 | 2 | 0 |
3 | 5 | 1 |
4 | 7 | 1 |
4 | -1 | 0 |
6 | 8 | ? |
5 | 1 | ? |
import numpy as np
import matplotlib.pyplot as mp
x = np.array([
[3, 1],
[2, 5],
[1, 8],
[6, 4],
[5, 2],
[3, 5],
[4, 7],
[4, -1]])
y = np.array([0, 1, 1, 0, 0, 1, 1, 0])
# l左边界,r右边界,h水平边界
l, r, h = x[:, 0].min() - 1, x[:, 0].max() + 1, 0.005
#
b, t, v = x[:, 1].min() - 1, x[:, 1].max() + 1, 0.005
grid_x = np.meshgrid(np.arange(l, r, h), np.arange(b, t, v))
flat_x = np.c_[grid_x[0].ravel(), grid_x[1].ravel()]
flat_y = np.zeros(len(flat_x), dtype=int)
flat_y[flat_x[:, 0] < flat_x[:, 1]] = 1
grid_y = flat_y.reshape(grid_x[0].shape)
mp.figure('Simple Classification', dpi=120)
mp.title('Simple Classification', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.pcolormesh(grid_x[0], grid_x[1], grid_y, cmap='gray')
mp.scatter(x[:, 0], x[:, 1], c=y, cmap='brg', s=80)
mp.show()
九、逻辑分类
y = w 0 + w 1 x 1 + w 2 x 2 y = w_0+w_1x_1+w_2x_2 y=w0+w1x1+w2x2
- 连续的预测值->离散的预测值,使用逻辑函数:
s i g m o i d = 1 1 + e − x sigmoid=\frac{1}{1+e^-x} sigmoid=1+e−x1
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-10, 10, 1000)
y = 1 / (1 + np.exp(-x))
mp.figure('Sigmoid', dpi=120)
mp.title('Sigmoid', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.plot(x, y, c='dodgerblue')
mp.show()
- 非线性化
y = 1 1 + e − ( w 0 + w 1 x 1 + w 2 x 2 ) y=\frac{1}{1+e^-(w0+w1x1+w2x2)} y=1+e−(w0+w1x1+w2x2)1
- 将预测函数的输出看做输入被划分为1类的概率,择概率大的类别作为预测结果。
输入1 | 输入2 | 概率 | 预测结果 |
---|---|---|---|
3 | 1 | 0.2 | 0 |
2 | 5 | 0.8 | 1 |
1 | 8 | 0.7 | 1 |
6 | 4 | 0.3 | 0 |
import numpy as np
import sklearn.linear_model as lm
import matplotlib.pyplot as mp
x = np.array([
[3, 1],
[2, 5],
[1, 8],
[6, 4],
[5, 2],
[3, 5],
[4, 7],
[4, -1]])
y = np.array([0,