创建一个逻辑回归分类器
逻辑回归是用于解决分类的一种方法。我们的目的是在给定的一组数据,我么们通过建立模型找到分类数据的分界线。
导入必要的数据包--生成样本数据和分类标签
import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
# input data
X = np.array([[4, 7], [3.5, 8], [3.1, 6.2], [0.5, 1], [1, 2], [1.2, 1.9], [6, 2], [5.7, 1.5], [5.4, 2.2]])
y = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2])
初始化逻辑回归分类器:
# initialize the logistic regression classifier
classifier = linear_model.LogisticRegression(solver='liblinear', C=100)
有许多输入参数可以为前面的函数指定,但其中一些重要的参数是求解器和C.求解器参数指定算法将用来求解方程组的解算器的类型。C参数控制正规化强度。 较低的值表示较高的调节强度。训练数据到分类器:
# train the classifier
classifier.fit(X, y)画出数据点和分界线
def plot_classifier(classifier, X, y):
# define ranges to plot the figure: 定义画图的边界长和宽扩充2个单位
x_min, x_max = min(X[:, 0]) - 1.0, max(X[:, 0]) + 1.0
y_min, y_max = min(X[:, 1]) - 1.0, max(X[:, 1]) + 1.0
# denotes the step size that will be used in the mesh grid:定义网孔的大小
step_size = 0.01
# define the mesh grid:定义网格大小的区间
x_values, y_values = np.meshgrid(np.arange(x_min, x_max, step_size), np.arange(y_min, y_max, step_size))
# compute the classifier output:计算网格区域分类结果的输出
mesh_output = classifier.predict(np.c_[x_values.ravel(), y_values.ravel()])
x_values.ravel()---默认是行序优先
# reshape the array
mesh_output = mesh_output.reshape(x_values.shape)
# Plot the output using a colored plot
plt.figure()
# choose a color scheme you can find all the options
# here: http://matplotlib.org/examples/color/colormaps_reference.html
plt.pcolormesh(x_values, y_values, mesh_output, cmap=plt.cm.GnBu)
# Overlay the training points on the plot 画出训练点
plt.scatter(X[:, 0], X[:, 1], c=y, s=80, edgecolors='black', linewidth=1, cmap=plt.cm.Paired)
# specify the boundaries of the figure图形的边界
plt.xlim(x_values.min(), x_values.max())
plt.ylim(y_values.min(), y_values.max())
# specify the ticks on the X and Y axes:制定刻度
plt.xticks((np.arange(int(min(X[:, 0])-1), int(max(X[:, 0])+1), 1.0)))
plt.yticks((np.arange(int(min(X[:, 1])-1), int(max(X[:, 1])+1), 1.0)))
plt.show()
结果输出如下图:
网孔的值为0.1和1时的结果如下:step_size = 0.1step_size = 1
未完待续。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。