https://blog.csdn.net/zlrai5895/article/details/79560353

多类分类问题本质上可以分解为多个二分类问题,而解决二分类问题的方法有很多。这里我们利用Keras机器学习框架中的ANN(artificial neural network)来解决多分类问题。这里我们采用的例子是著名的UCI Machine Learning Repository中的鸢尾花数据集(iris flower dataset)。

1. 编码输出便签
多类分类问题与二类分类问题类似,需要将类别变量(categorical function)的输出标签转化为数值变量。这个问题在二分类的时候直接转换为(0,1)(输出层采用sigmoid函数)或(-1,1)(输出层采用tanh函数)。类似的,在多分类问题中我们将转化为虚拟变量(dummy variable):即用one hot encoding方法将输出标签的向量(vector)转化为只在出现对应标签的那一列为1,其余为0的布尔矩阵。以我们所用的鸢尾花数据为例:

sample,    label
1, Iris-setosa
2, Iris-versicolor
3, Iris-virginica

用one hot encoding转化后如下:

sample, Iris-setosa, Iris-versicolor, Iris-virginica
1, 1, 0, 0
2, 0, 1, 0
3, 0, 0, 1

注意这里不要将label直接转化成数值变量,如1,2,3,这样的话与其说是预测问题更像是回归预测的问题,后者的难度比前者大。(当类别比较多的时候输出值的跨度就会比较大,此时输出层的激活函数就只能用linear)

这一步转化工作我们可以利用keras中的np_utils.to_categorical函数来进行。

2. 构建神经网络模型
Keras是基于Theano或Tensorflow底层开发的简单模块化的神经网络框架,因此用Keras搭建网络结构会比Tensorflow更加简单。这里我们将使用Keras提供的KerasClassifier类,这个类可以在scikit-learn包中作为Estimator使用,故利用这个类我们就可以方便的调用sklearn包中的一些函数进行数据预处理和结果评估(此为sklearn包中模型(model)的基本类型)。
对于网络结构,我们采用3层全向连接的,输入层有4个节点,隐含层有10个节点,输出层有3个节点的网络。其中,隐含层的激活函数为relu(rectifier),输出层的激活函数为softmax。损失函数则相应的选择categorical_crossentropy(此函数来着theano或tensorflow,具体可以参见这里)(二分类的话一般选择activation=‘sigmoid’, loss=‘binary_crossentropy’)。
PS:对于多类分类网络结构而言,增加中间隐含层能够提升训练精度,但是所需的计算时间和空间会增大,因此需要测试选择一个合适的数目,这里我们设为10;此外,每一层的舍弃率(dropout)也需要相应调整(太高容易欠拟合,太低容易过拟合),这里我们设为0.2。

3. 评估模型
这里我们利用评估机器学习模型的经典方法: k折交叉检验(k-fold cross validation)。这里我们采用10折(k=10)。

4. 代码实现

import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn.preprocessing import LabelEncoder # load dataset
dataframe = pd.read_csv("iris.csv", header=None)
dataset = dataframe.values
X = dataset[:, 0:4].astype(float)
Y = dataset[:, 4] # encode class values as integers
encoder = LabelEncoder()
encoded_Y = encoder.fit_transform(Y)
# convert integers to dummy variables (one hot encoding)
dummy_y = np_utils.to_categorical(encoded_Y) # define model structure
def baseline_model():
model = Sequential()
model.add(Dense(output_dim=10, input_dim=4, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(output_dim=3, input_dim=10, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
estimator = KerasClassifier(build_fn=baseline_model, nb_epoch=40, batch_size=256)
# splitting data into training set and test set. If random_state is set to an integer, the split datasets are fixed.
X_train, X_test, Y_train, Y_test = train_test_split(X, dummy_y, test_size=0.3, random_state=0)
estimator.fit(X_train, Y_train) # make predictions
pred = estimator.predict(X_test) # inverse numeric variables to initial categorical labels
init_lables = encoder.inverse_transform(pred) # k-fold cross-validate
seed = 42
np.random.seed(seed) # numpy.random.seed()的使用
kfold = KFold(n_splits=10, shuffle=True, random_state=seed)
results = cross_val_score(estimator, X, dummy_y, cv=kfold)

fit_transform()和transform()的区别

np_utils.to_categorical的更多相关文章

  1. TypeError: to_categorical() got an unexpected keyword argument 'nb_classes'

    在学习莫烦教程中keras教程时,报错:TypeError: to_categorical() got an unexpected keyword argument 'nb_classes',代码如下 ...

  2. [Keras] Develop Neural Network With Keras Step-By-Step

    简单地训练一个四层全连接网络. Ref: http://machinelearningmastery.com/tutorial-first-neural-network-python-keras/ 1 ...

  3. 如何用卷积神经网络CNN识别手写数字集?

    前几天用CNN识别手写数字集,后来看到kaggle上有一个比赛是识别手写数字集的,已经进行了一年多了,目前有1179个有效提交,最高的是100%,我做了一下,用keras做的,一开始用最简单的MLP, ...

  4. [Keras] mnist with cnn

    典型的卷积神经网络. Keras傻瓜式读取数据:自动下载,自动解压,自动加载. # X_train: array([[[[ 0., 0., 0., ..., 0., 0., 0.], [ 0., 0. ...

  5. Keras学习~试用卷积~跑CIFAR-10

    import numpy as np import cPickle import keras as ks from keras.layers import Dense, Activation, Fla ...

  6. Keras学习~第一个例子~跑MNIST

    import numpy as npimport gzip import struct import keras as ks import logging from keras.layers impo ...

  7. Keras

    sudo pip install keras --安装 新建一个文件,里面存储的数据:第一列是属性,第二列是类别 11220044 011220044 011220044 011220033 1112 ...

  8. 用keras的cnn做人脸分类

    keras介绍 Keras是一个简约,高度模块化的神经网络库.采用Python / Theano开发. 使用Keras如果你需要一个深度学习库: 可以很容易和快速实现原型(通过总模块化,极简主义,和可 ...

  9. 【Python与机器学习】:利用Keras进行多类分类

    多类分类问题本质上可以分解为多个二分类问题,而解决二分类问题的方法有很多.这里我们利用Keras机器学习框架中的ANN(artificial neural network)来解决多分类问题.这里我们采 ...

随机推荐

  1. 浏览器的DNS缓存查看和清除

    有dns的地方,就有缓存.浏览器.操作系统.Local DNS.根域名服务器,它们都会对DNS结果做一定程度的缓存.本文总结一些常见的浏览器和操作系统的DNS缓存时间 浏览器先查询自己的缓存,查不到, ...

  2. nginx $document_uri 参数使用

    $document_uri  表示访问的url 现在我的需求是,访问 www.abc.com  请求到 www.abc.com/abc/在nginx配置文件中加入 if ($document_uri ...

  3. S5PV210之内外存学习

    RAM,内部存储器,用来运行程序(DRAM,SRAM,DDR) ROM,外部存储器,存储数据.程序(硬盘,FLASH等) 内存:SRAM,静态内存,容量下,价格高,不需要初始化,上电后直接使用 DRA ...

  4. .net开发常用的第三方开发组件

    转自:http://www.cnblogs.com/damsoft/p/6100323.html .net开发常用的第三方组件: 1.RSS.NET.dll: RSS.NET是一款操作RSS feed ...

  5. boost/config.hpp文件详解

    简要概述 今天突发奇想想看一下boost/config.hpp的内部实现,以及他有哪些功能. 这个头文件都有一个类似的结构,先包含一个头文件,假设为头文件1,然后包含这个头文 件中定义的宏.对于头文件 ...

  6. [Functional Programming] Combine State Dependent Transactions with the State ADT (composeK to replace multi chian call)

    When developing a Finite State Machine, it is often necessary to apply multiple transitions in tande ...

  7. 创建你的第一个ionic+cordova应用(1)

    前面我们安装了前端的神器webstorm11,体验到了强大的开发体验,接着我们来安装ionic 必备: Node.js (npm安装工具) 百度下载 官网下载  注:如果官网新版不能安装请用百度下载0 ...

  8. css3中的新特性经典应用

    这篇文章主要分析css3新特性的典型应用,都是干活,没得水分. 1.动画属性:animation. 利用animation可以实现元素的动画效果,他是一个简写属性,用于设置6个动画属性:aminati ...

  9. Hbase笔记3 shell命令

    http://www.jb51.net/article/31172.htm 这个文章写得挺好 1.HBase的shell就和我们用Mysql的终端是一个意思,比如我们安装好Mysql,配置好了环境变量 ...

  10. IDEA报compilation failed:internal java compiler error解决方法

    java complier 设置的问题  ,项目中有的配jdk1.6,有的配jdk1.7,版本不一样,导致这样的错误,提示这样的报错时,从file-Settings进入