欢迎来到 TensorFlow Keras 教程页面!在这里,你将学习如何使用 Keras,TensorFlow 的高级 API,来构建和训练神经网络。

快速开始

  1. 安装 TensorFlow
    在开始之前,请确保你已经安装了 TensorFlow。你可以通过以下命令安装:

    pip install tensorflow
    
  2. 创建第一个模型
    下面是一个简单的神经网络模型示例:

    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense
    
    model = Sequential()
    model.add(Dense(10, input_dim=8, activation='relu'))
    model.add(Dense(1, activation='sigmoid'))
    
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    
  3. 训练模型
    接下来,你需要准备一些数据来训练模型:

    from tensorflow.keras.datasets import mnist
    from tensorflow.keras.utils import to_categorical
    
    (X_train, y_train), (X_test, y_test) = mnist.load_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 = to_categorical(y_train, 10)
    y_test = to_categorical(y_test, 10)
    

    现在你可以开始训练模型了:

    model.fit(X_train, y_train, epochs=5, batch_size=128)
    
  4. 评估模型
    训练完成后,你可以使用测试数据来评估模型的性能:

    scores = model.evaluate(X_test, y_test, verbose=0)
    print('Test loss:', scores[0])
    print('Test accuracy:', scores[1])
    

更多资源

想要了解更多关于 Keras 的信息,请访问 TensorFlow 官方文档

TensorFlow Logo


如果你对深度学习有更深入的兴趣,不妨看看我们的 深度学习教程