人工分类
特征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 | 1 |
5 | 1 | 0 |
案例:
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 = x[:, 0].min() - 1, x[:, 0].max() + 1
b, t = x[:, 1].min() - 1, x[:, 1].max() + 1
n = 500
grid_x, grid_y = np.meshgrid(np.linspace(l, r, n), np.linspace(b, t, n))
grid_z = np.piecewise(grid_x, [grid_x>grid_y, grid_x<grid_y], [1, 0])
mp.figure('Simple Classification', facecolor='lightgray')
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, grid_y, grid_z, cmap='gray')
mp.scatter(x[:, 0], x[:, 1], c=y, cmap='brg', s=80)
mp.show()
逻辑分类
通过输入的样本数据,基于多元线型回归模型求出线性预测方程。
y = w0+w1x1+w2x2
但通过线型回归方程返回的是连续值,不可以直接用于分类业务模型,所以急需一种方式使得把连续的预测值->离散的预测值。 [-∞, +∞]->{0, 1}
逻辑函数: y = 1 1 + e − x 逻辑函数:y = \frac{1}{1+e^{-x}} 逻辑函数:y=1+e−x1
该逻辑函数当x>0,y>0.5;当x<0, y<0.5; 可以把样本数据经过线性预测模型求得的值带入逻辑函数的x,即将预测函数的输出看做输入被划分为1类的概率,择概率大的类别作为预测结果,可以根据函数值确定两个分类。这是线性函数非线性化的一种方式。
逻辑回归相关API:
import sklearn.linear_model as lm
# 构建逻辑回归器
# solver:逻辑函数中指数的函数关系(liblinear为线型函数关系)
# C:参数代表正则强度,为了防止过拟合。正则越大拟合效果越小。
model = lm.LogisticRegression(solver='liblinear', C=正则强度)
model.fit(训练输入集,训练输出集)
result = model.predict(带预测输入集)
案例:基于逻辑回归器绘制网格化坐标颜色矩阵。
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, 1, 1, 0, 0, 1, 1, 0])`
# 逻辑分类器
model = lm.LogisticRegression(solver='liblinear', C=1)
model.fit(x, y)
l, r = x[:, 0].min() - 1, x[:, 0].max() + 1
b, t = x[:, 1].min() - 1, x[:, 1].max() + 1
n = 500
grid_x, grid_y = np.meshgrid(np.linspace(l, r, n), np.linspace(b, t, n))
samples = np.column_stack((grid_x.ravel(), grid_y.ravel()))
grid_z = model.predict(samples)
grid_z = grid_z.reshape(grid_x.shape)
mp.figure('Logistic Classification', facecolor='lightgray')
mp.title('Logistic Classification', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
mp.tick_params