Skip to content

Keras入门—Hello,World #69

Open
@johnnian

Description

@johnnian

一、Keras安装步骤

  1. 运行环境:使用Python3, 具体安装方法,可以参考博文: 开发工具系列之—pyenv:python版本切换 #61 (开发工具系列之—pyenv:python版本切换)
  2. 安装keras:
pip install tensenflow
pip install keras

3、安装 Jupyter

开发工具上,试了下 Jupyter,确实很方便,比 Pycharm 更加方便,因为可以运行多个代码片段,比较适合在开发阶段,安装步骤如下:

pip install jupyter 
python3 -m pip install ipykernel  		# 同时支持python3
python3 -m ipykernel install --user		# 同时支持python3

二、Hello,World

步骤1: 启动 Jupyter

➜  ~ jupyter notebook

步骤2:在Jupyter上编写代码

点击“New”,新建“Python3”模块,输入代码:

from keras import models
from keras import layers
from keras.datasets import mnist
import numpy as np
from keras.utils import to_categorical

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

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_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)

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

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

print('test_acc:', test_acc, 'test_loss:', test_loss)

运行结果:

Epoch 1/5
60000/60000 [==============================] - 2s 27us/step - loss: 0.2559 - accuracy: 0.9257
Epoch 2/5
60000/60000 [==============================] - 2s 25us/step - loss: 0.1027 - accuracy: 0.9698
Epoch 3/5
60000/60000 [==============================] - 2s 27us/step - loss: 0.0682 - accuracy: 0.9798
Epoch 4/5
60000/60000 [==============================] - 2s 26us/step - loss: 0.0499 - accuracy: 0.9845
Epoch 5/5
60000/60000 [==============================] - 2s 25us/step - loss: 0.0375 - accuracy: 0.9887

10000/10000 [==============================] - 0s 29us/step
test_acc: 0.9789000153541565 test_loss: 0.07354914876233087

上面的代码,就是Keras版本的“Helloworld”。

下面这个是Jupyter的代码:

keras_mnist_test.ipynb.zip

三、问题

1、numpy报错

FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecat

在运行keras的“helloword”的时候,报上面错误,这个是因为numpy版本问题,解决方法:

pip install numpy==1.16.0

2、测试数据集合的下载问题

在运行加载语句的时候,报错:mnist.load_data()

Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz
---------------------------------------------------------------------------
ConnectionRefusedError                    Traceback (most recent call last)
...
Exception: URL fetch failure on https://s3.amazonaws.com/img-datasets/mnist.npz: None -- [Errno 111] Connection refused

解决办法: 通过百度/谷歌,下载数据集,放在指定路径下即可: ~/.keras/datasets, 这个在源码的注释里面也有写到:

"""MNIST handwritten digits dataset.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from ..utils.data_utils import get_file
import numpy as np


def load_data(path='mnist.npz'):
    """Loads the MNIST dataset.

    # Arguments
        path: path where to cache the dataset locally
            (relative to ~/.keras/datasets).

    # Returns
        Tuple of Numpy arrays: `(x_train, y_train), (x_test, y_test)`.
    """
    path = get_file(path,
                    origin='https://s3.amazonaws.com/img-datasets/mnist.npz',
                    file_hash='8a61469f7ea1b51cbae51d4f78837e45')
    with np.load(path, allow_pickle=True) as f:
        x_train, y_train = f['x_train'], f['y_train']
        x_test, y_test = f['x_test'], f['y_test']
    return (x_train, y_train), (x_test, y_test)

备注:

四、参考

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions