美文网首页
【2019-03-16】神经网络简单认识和应用

【2019-03-16】神经网络简单认识和应用

作者: BigBigFlower | 来源:发表于2019-03-16 01:29 被阅读0次

    神经网络如何通过反向传播与梯度下降进行学习

    (1)初识神经网络

    加载 Keras 中的 MNIST 数据集

    from keras.datasets import mnist

    (train_images, train_labels), (test_images, test_labels) = mnist.load_data()

    train_images.shape #训练数据

    len(train_labels)

    test_labels

    ps:图像被编码为 Numpy 数组,而标签是数字数组,取值范围为 0~9。图像和标签一一对应。

    运行结果

    (i)将训练数据(train_images 和 train_labels)输入神经网络;

    (ii)其网络学习将图像和标签关联在一起;

    (iii)网络对 test_images 生成预测, 而我们将验证这些预测与 test_labels 中的标签是否匹配。

    要想训练网络,我们还需要选择编译(compile)步骤的三个参数。

    �--损失函数(loss function):网络如何衡量在训练数据上的性能,即网络如何朝着正确的方向前进。

    �-- 优化器(optimizer):基于训练数据和损失函数来更新网络的机制。

    �-- 在训练和测试过程中需要监控的指标(metric):本例只关心精度,即正确分类的图像所占的比例。

    from keras.datasets import mnist

    from keras import models

    from keras import layers

    from keras.utils import to_categorical

    #to_categorical就是将类别向量转换为二进制(只有0和1)的矩阵类型表示。其表现为将原有的类别向量转换为独热编码的形式。

    network = models.Sequential() #顺序模型

    network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))

    network.add(layers.Dense(10, activation='softmax'))

    #编译

    network.compile(optimizer='rmsprop',

                    loss='categorical_crossentropy',

                    metrics=['accuracy'])

    (train_images, train_labels), (test_images, test_labels) = mnist.load_data()

    #准备图像数据

    train_images = train_images.reshape((60000, 28 * 28))

    train_images = train_images.astype('float32') / 255

    test_images = test_images.reshape((10000, 28 * 28))

    test_images = test_images.astype('float32') / 255

    #准备标签

    train_labels = to_categorical(train_labels)

    test_labels = to_categorical(test_labels)

    #开始拟合训练数据(epochs 训练次数,batch_size 批尺寸,梯度下降的方向)

    network.fit(train_images, train_labels, epochs=5, batch_size=128)

    #检测在测试集上的性能

    test_loss, test_acc = network.evaluate(test_images, test_labels)

    print('test_acc:', test_acc)

    运行结果

    相关文章

      网友评论

          本文标题:【2019-03-16】神经网络简单认识和应用

          本文链接:https://www.haomeiwen.com/subject/vatjmqtx.html