Python Keras 神经网络

Python 模块 Keras 支持 TensorFlowCNTKTheano 等多个深度学习框架,为研究者提供了简洁易用的 API 接口,在工业和学术界应用广泛。

Python Keras 安装

1
2
pip install keras
pip install theano

更改 Keras 配置文件 ~/.keras/keras.json 将后台系统设置为 Theano

1
2
# change backend to theano
vim ~/.keras/keras.json

用 Keras 实现一个简单的神经网络

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import SGD

# create train data using Numpy
# x is the feature matrix and y is the label vector
x_train = np.array([[0, 0],
                    [0, 1],
                    [1, 0],
                    [1, 1]])
y_train = np.array([[0],
                    [1],
                    [1],
                    [0]])

# load NN model
model = Sequential()

# specify the number of neurons in hidden layer
num_neurons = 10

# use Dense to create a fully connected feed forward network
model.add(Dense(num_neurons, input_dim=2))

# specify the activation function for the hidden layer
model.add(Activation('tanh'))

# create the output layer
model.add(Dense(1))
model.add(Activation('sigmoid'))
print(model.summary())

# specify the learning rate for the stochastic gradient descent algorithm
sgd = SGD(lr=0.1)

# specify the loss function
model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy'])

# train the model and learn all the parameters
model.fit(x_train, y_train, epochs=1000)