1,上篇博文简单的一个回归的神经网络.
2,分类。
用的数据时keras数据可中MNIST。
import numpy as np
np.random.seed(1337)
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import RMSprop
a.对数据做些简单处理。x,每张图片都是28x28的像素点,像素值在 0 到 255 之间的,除以 255 进行标准化,就变成了 0 到 1 之间。y的话改成label值,共有是个label,也就是0~9,numpy 的一个函数 np_utils.to_categorical,改成一个大小为 10 的向量,它属于哪个数字,就在哪个位置为 1,其他位置都是 0。
b.建立模型,回归网络中用到的是 model.add 一层一层添加神经层,今天的方法是直接在模型的里面加多个神经层。好比一个水管,一段一段的,数据是从上面一段掉到下面一段,再掉到下面一段。第一段就是加入 Dense 神经层。32 是输出的维度,784 是输入的维度。 第一层传出的数据有 32 个 feature,传给激励单元,激励函数用到的是 relu 函数。 经过激励函数之后,就变成了非线性的数据。 然后再把这个数据传给下一个神经层,这个 Dense 我们定义它有 10 个输出的 feature。同样的,此处不需要再定义输入的维度,因为它接收的是上一层的输出。 接下来再输入给下面的 softmax 函数,用来分类。
c.优化器用的也不一样,RMSprop 作为优化器,它的参数包括学习率等
d.激活模型,model.compile 激励神经网络。优化器,可以是默认的,也可以是我们在上一步定义的。 损失函数,分类和回归问题的不一样,用的是交叉熵。 metrics,里面可以放入需要计算的 cost,accuracy,score 等。
f.训练模型,有点类似sklearn, fit一下。
g.测试模型,evaluate()
(X_train, y_train), (X_test, y_test) = mnist.load_data()
X_train = X_train.reshape(X_train.shape[0], -1) / 255 # normalise标准化
X_test = X_test.reshape(X_test.shape[0], -1) / 255 # normalise标准化
y_train = np_utils.to_categorical(y_train, num_classes=10) #将转换成10个类别
y_test = np_utils.to_categorical(y_test,num_classes= 10)
# another way to build your neural net
model = Sequential([
Dense(32, input_dim= 784),
Activation('relu'),
Dense(10), #上一次层的输出自然会作为这一层输入,不需再设置输入了
Activation('softmax')
])
# Another way to define your optimizer
rmsprop = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)
# We add metrics to get more results you want to see
model.compile(
optimizer=rmsprop,
loss='categorical_crossentropy',
metrics=['accuracy'], #矩阵中可计算准确率,recall...
)
print('Training -----------')
# another way to train the model
model.fit(X_train, y_train, nb_epoch=2,batch_size= 32)
print('\nTest -----------')
# Evaluate the model with the metrics we defined earlier
loss, accuracy = model.evaluate(X_test, y_test)
print('test loss', loss)
print('test accuracy:', accuracy)
也是根据莫凡教程学的分类。