python分类算法的应用_python3机器学习经典实例-学习笔记7-分类算法

本文介绍了如何使用Python的sklearn库创建一个逻辑回归分类器,并通过示例展示了训练过程。通过画图展示分类边界,探讨了不同步长对分类效果的影响。
摘要由CSDN通过智能技术生成

创建一个逻辑回归分类器

逻辑回归是用于解决分类的一种方法。我们的目的是在给定的一组数据,我么们通过建立模型找到分类数据的分界线。

导入必要的数据包--生成样本数据和分类标签

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

未完待续。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值