📜  讨论Keras(1)

📅  最后修改于: 2023-12-03 15:41:42.545000             🧑  作者: Mango

Keras 简介

Keras 是一个开源的深度学习框架,支持多种神经网络模型,包括 CNN(卷积神经网络)、RNN(递归神经网络)等。Keras 是建立在 Tensorflow、Theano 或者 CNTK 之上,使其具有了强大的计算能力和支持 GPU 计算的能力。

特征
  1. 易于使用:Keras 提供了更高层次的抽象,从而更轻松地构建模型和快速地试验。

  2. 跨平台:Keras 支持 Python 2.7 和 3.5 及以上版本,可以在 Windows、Linux 和 MacOS 等平台上运行。

  3. 支持多种神经网络模型:Keras 支持多种深度学习模型,包括 CNN、RNN 等。

  4. 多种数据格式:Keras 能够处理多种输入数据格式,例如 Numpy 数组、Pandas 数据框、图片和音频等。

安装

Keras 的安装非常简单,使用 pip install keras 命令即可完成安装。此外,还需要安装所需的后端框架,如 Tensorflow、Theano 等。

安装 Tensorflow
pip install tensorflow
安装 Theano
pip install theano
Hello World

下面是一个使用 Keras 构建神经网络的 Hello World 示例,使用的数据集是 MNIST 手写数字数据集。

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop

batch_size = 128
num_classes = 10
epochs = 20

# Load the MNIST dataset
(x_train, y_train), (x_test, y_test) = mnist.load_data()

# Preprocess the data
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

# Build the model
model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='softmax'))

model.summary()

# Compile the model
model.compile(loss='categorical_crossentropy',
              optimizer=RMSprop(),
              metrics=['accuracy'])

# Train the model
history = model.fit(x_train, y_train,
                    batch_size=batch_size,
                    epochs=epochs,
                    verbose=1,
                    validation_data=(x_test, y_test))

# Evaluate the model
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
结论

Keras 是一个易于使用的深度学习框架,提供了高层次的抽象,使模型构建变得更加容易。使用 Keras 进行深度学习可以缩短程序开发时间,提高代码可读性和维护性。