Python利用scikit-learn实现近邻算法分类的示例详解
作者:吃肉的小馒头 发布时间:2021-01-09 18:43:44
标签:Python,scikit-learn,近邻算法
scikit-learn库
scikit-learn已经封装好很多数据挖掘的算法
现介绍数据挖掘框架的搭建方法
1.转换器(Transformer)用于数据预处理,数据转换
2.流水线(Pipeline)组合数据挖掘流程,方便再次使用(封装)
3.估计器(Estimator)用于分类,聚类,回归分析(各种算法对象)
所有的估计器都有下面2个函数
fit() 训练
用法:estimator.fit(X_train, y_train)
estimator = KNeighborsClassifier() 是scikit-learn算法对象
X_train = dataset.data 是numpy数组
y_train = dataset.target 是numpy数组
predict() 预测
用法:estimator.predict(X_test)
estimator = KNeighborsClassifier() 是scikit-learn算法对象
X_test = dataset.data 是numpy数组
示例
%matplotlib inline
# Ionosphere数据集
# https://archive.ics.uci.edu/ml/machine-learning-databases/ionosphere/
# 下载ionosphere.data和ionosphere.names文件,放在 ./data/Ionosphere/ 目录下
import os
home_folder = os.path.expanduser("~")
print(home_folder) # home目录
# Change this to the location of your dataset
home_folder = "." # 改为当前目录
data_folder = os.path.join(home_folder, "data")
print(data_folder)
data_filename = os.path.join(data_folder, "ionosphere.data")
print(data_filename)
import csv
import numpy as np
# Size taken from the dataset and is known已知数据集形状
X = np.zeros((351, 34), dtype='float')
y = np.zeros((351,), dtype='bool')
with open(data_filename, 'r') as input_file:
reader = csv.reader(input_file)
for i, row in enumerate(reader):
# Get the data, converting each item to a float
data = [float(datum) for datum in row[:-1]]
# Set the appropriate row in our dataset用真实数据覆盖掉初始化的0
X[i] = data
# 1 if the class is 'g', 0 otherwise
y[i] = row[-1] == 'g' # 相当于if row[-1]=='g': y[i]=1 else: y[i]=0
# 数据预处理
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=14)
print("训练集数据有 {} 条".format(X_train.shape[0]))
print("测试集数据有 {} 条".format(X_test.shape[0]))
print("每条数据有 {} 个features".format(X_train.shape[1]))
输出:
训练集数据有 263 条
测试集数据有 88 条
每条数据有 34 个features
# 实例化算法对象->训练->预测->评价
from sklearn.neighbors import KNeighborsClassifier
estimator = KNeighborsClassifier()
estimator.fit(X_train, y_train)
y_predicted = estimator.predict(X_test)
accuracy = np.mean(y_test == y_predicted) * 100
print("准确率 {0:.1f}%".format(accuracy))
# 其他评价方式
from sklearn.cross_validation import cross_val_score
scores = cross_val_score(estimator, X, y, scoring='accuracy')
average_accuracy = np.mean(scores) * 100
print("平均准确率 {0:.1f}%".format(average_accuracy))
avg_scores = []
all_scores = []
parameter_values = list(range(1, 21)) # Including 20
for n_neighbors in parameter_values:
estimator = KNeighborsClassifier(n_neighbors=n_neighbors)
scores = cross_val_score(estimator, X, y, scoring='accuracy')
avg_scores.append(np.mean(scores))
all_scores.append(scores)
输出:
准确率 86.4%
平均准确率 82.3%
from matplotlib import pyplot as plt
plt.figure(figsize=(32,20))
plt.plot(parameter_values, avg_scores, '-o', linewidth=5, markersize=24)
#plt.axis([0, max(parameter_values), 0, 1.0])
for parameter, scores in zip(parameter_values, all_scores):
n_scores = len(scores)
plt.plot([parameter] * n_scores, scores, '-o')
plt.plot(parameter_values, all_scores, 'bx')
from collections import defaultdict
all_scores = defaultdict(list)
parameter_values = list(range(1, 21)) # Including 20
for n_neighbors in parameter_values:
for i in range(100):
estimator = KNeighborsClassifier(n_neighbors=n_neighbors)
scores = cross_val_score(estimator, X, y, scoring='accuracy', cv=10)
all_scores[n_neighbors].append(scores)
for parameter in parameter_values:
scores = all_scores[parameter]
n_scores = len(scores)
plt.plot([parameter] * n_scores, scores, '-o')
plt.plot(parameter_values, avg_scores, '-o')
来源:https://blog.csdn.net/qq_42034590/article/details/129243282


猜你喜欢
- 配置Laravel 的邮件服务可以通过 config/mail.php 配置文件进行配置。邮件中的每一项都在配置文件中有单独的配置项,甚至是
- <script type="text/javascript"> // Close HTML Tags ---
- transpose() 这个函数如果括号内不带参数,就相当于转置,和.T效果一样,而今天主要来讲解其带参数。我们看如下一个numpy的数组:
- pyecharts是一个封装百度开源图表库echarts的包,使用pyecharts可以生成独立的网页,也可以在flask、django中集
- lambdalambda可以理解为一种小函数,但是它是一个表达式,而不是一个语句,所以在def不允许出现的地方仍然可以使用lambda函数,
- 一、引言 背景我们在做系统时,很多时候是处理实时的任务,请求来了马上就处理,然后立刻给用户以反馈。但有时也会遇到非实时的任务,比如确定的时间
- Socket 是进程间通信的一种方式,它与其他进程间通信的一个主要不同是:它能实现不同主机间的进程间通信,我们网络上各种各样的服务大多都是基
- 今天整理之前写的代码,发现在做数模期间写的用python实现的遗传算法,感觉还是挺有意思的,就拿出来分享一下。首先遗传算法是一种优化算法,通
- 1.分析 我们在用 php 制作网站时,分类是很重要的,在分类下面又再分类这第二个分类称为次分类,而现在大多
- numpy.mean计算矩阵均值计算矩阵的均值>>> a = np.array([[1, 2], [3, 4]])>
- 锁机制NOLOCK和READPAST的区别。1. 开启一个事务执行插
- 版本:ant design vue 3.2.4场景:使用Image图片组件预览功能需求:自定义预览遮罩层及预览图片的样式;不得影响到其他页面
- 玩过knockoutjs的都知道,有一个强大的功能叫做component,而这个component有个牛逼的地方就是拥有自己的viewmod
- #-*- encoding: utf-8 -*-'''Created on 2014-4-24@author: Le
- 本文实例为大家分享了vue+echarts封装气泡图的具体代码,供大家参考,具体内容如下前端可视化封装气泡图1. html<templ
- 1.jsvar obj=document.getElementById(selectid);obj.options.length = 0;
- 这是一个很和谐很实用的网站管理程序,和我以前介绍的服务器管理程序不同的是,这个程序只有一个功能,就是实现远程Web方式删除文件(实际上是重命
- 1 模型定义和TF很像,Pytorch也通过继承父类来搭建模型,同样也是实现两个方法。在TF中是__init__()和
- 一. 安装 Beautiful Soup首先,您需要安装 Beautiful Soup。在终端或命令提示符中运行以下命令:pip insta
- 0x00 字符的编码计算机毕竟是西方国家的发明,最开始并没有想到会普及到全世界,只用一个字节中的7位(ASCII)来表示字符对于现在庞大的文