网络编程
位置:首页>> 网络编程>> Python编程>> python神经网络学习使用Keras进行简单分类

python神经网络学习使用Keras进行简单分类

作者:Bubbliiiing  发布时间:2023-09-18 04:37:23 

标签:python,神经网络,Keras,分类

学习前言

上一篇讲了如何构建回归算法,这一次将怎么进行简单分类。

Keras中分类的重要函数

1、np_utils.to_categorical

np_utils.to_categorical用于将标签转化为形如(nb_samples, nb_classes)的二值序列。

假设num_classes = 10。

如将[1,2,3,……4]转化成:

[[0,1,0,0,0,0,0,0]
[0,0,1,0,0,0,0,0]
[0,0,0,1,0,0,0,0]
……
[0,0,0,0,1,0,0,0]]

这样的形态。

如将Y_train转化为二值序列,可以用如下方式:

Y_train = np_utils.to_categorical(Y_train,num_classes= 10)

2、Activation

Activation是激活函数,一般在每一层的输出使用。

当我们使用Sequential模型构建函数的时候,只需要在每一层Dense后面添加Activation就可以了。

Sequential函数也支持直接在参数中完成所有层的构建,使用方法如下。

model = Sequential([
   Dense(32,input_dim = 784),
   Activation("relu"),
   Dense(10),
   Activation("softmax")
   ]
)

其中两次Activation分别使用了relu函数和softmax函数。

3、metrics=[‘accuracy’]

在model.compile中添加metrics=[‘accuracy’]表示需要计算分类精确度,具体使用方式如下:

model.compile(
loss = 'categorical_crossentropy',
optimizer = rmsprop,
metrics=['accuracy']
)

全部代码

这是一个简单的仅含有一个隐含层的神经网络,用于完成手写体识别。在本例中,使用的优化器是RMSprop,具体可以使用的优化器可以参照Keras中文文档。

import numpy as np
from keras.models import Sequential
from keras.layers import Dense,Activation ## 全连接层
from keras.datasets import mnist
from keras.utils import np_utils
from keras.optimizers import RMSprop
# 获取训练集
(X_train,Y_train),(X_test,Y_test) = mnist.load_data()
# 首先进行标准化
X_train = X_train.reshape(X_train.shape[0],-1)/255
X_test = X_test.reshape(X_test.shape[0],-1)/255
# 计算categorical_crossentropy需要对分类结果进行categorical
# 即需要将标签转化为形如(nb_samples, nb_classes)的二值序列
Y_train = np_utils.to_categorical(Y_train,num_classes= 10)
Y_test = np_utils.to_categorical(Y_test,num_classes= 10)
# 构建模型
model = Sequential([
   Dense(32,input_dim = 784),
   Activation("relu"),
   Dense(10),
   Activation("softmax")
   ]
)
rmsprop = RMSprop(lr = 0.001,rho = 0.9,epsilon = 1e-08,decay = 0)
## compile
model.compile(loss = 'categorical_crossentropy',optimizer = rmsprop,metrics=['accuracy'])
print("\ntraining")
cost = model.fit(X_train,Y_train,nb_epoch = 2,batch_size = 32)
print("\nTest")
cost,accuracy = model.evaluate(X_test,Y_test)
## W,b = model.layers[0].get_weights()
print("accuracy:",accuracy)

实验结果为:

Epoch 1/2
60000/60000 [==============================] - 12s 202us/step - loss: 0.3512 - acc: 0.9022
Epoch 2/2
60000/60000 [==============================] - 11s 183us/step - loss: 0.2037 - acc: 0.9419
Test
10000/10000 [==============================] - 1s 108us/step
accuracy: 0.9464

来源:https://blog.csdn.net/weixin_44791964/article/details/101170430

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com