Keras 是一个高级神经网络 API,可以运行在 TensorFlow、CNTK 和 Theano 后端之上。以下是一些入门级的教程,帮助您开始使用 Keras。

安装 Keras

首先,确保您已经安装了 Python。然后,可以通过 pip 安装 Keras:

pip install keras

您也可以选择安装 TensorFlow,因为 Keras 已经集成到 TensorFlow 中:

pip install tensorflow

简单的神经网络

以下是一个简单的神经网络示例,用于分类任务:

from keras.models import Sequential
from keras.layers import Dense

model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

数据准备

在进行模型训练之前,您需要准备一些数据。以下是一个使用 NumPy 创建随机数据的示例:

import numpy as np

# 输入数据
X_train = np.random.random((1000, 8))
# 输出数据
y_train = np.random.randint(2, size=(1000, 1))

训练模型

使用以下代码来训练模型:

model.fit(X_train, y_train, epochs=150, batch_size=10)

模型评估

在训练完成后,您可以评估模型的性能:

score = model.evaluate(X_train, y_train, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

更多资源

如果您想要深入了解 Keras,可以访问以下链接:

神经网络

Keras Logo

返回首页