Home > Technology peripherals > AI > body text

Build deep learning models with TensorFlow and Keras

王林
Release: 2024-01-24 09:18:05
forward
390 people have browsed it

Build deep learning models with TensorFlow and Keras

TensorFlow and Keras are currently one of the most popular deep learning frameworks. They not only provide high-level APIs to make it easy to build and train deep learning models, but also provide a variety of layers and model types to facilitate the construction of various types of deep learning models. Therefore, they are widely used to train large-scale deep learning models.

We will use TensorFlow and Keras to build a deep learning model for image classification. In this example, we will use the CIFAR-10 dataset, which contains 10 different categories with 6000 32x32 color images per category.

First, we need to import the necessary libraries and datasets. We will use TensorFlow version 2.0 and Keras API to build the model. Here is the code to import the library and dataset: ```python import tensorflow astf from tensorflow import keras from tensorflow.keras.datasets import mnist #Import dataset (x_train, y_train), (x_test, y_test) = mnist.load_data() ``` The above is the code to import the library and dataset. We use the `tensorflow` library to build the model and use the `mnist` dataset as an example dataset.

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.datasets import cifar10

# 加载CIFAR-10数据集
(x_train, y_train), (x_test, y_test) = cifar10.load_data()

# 将像素值缩放到0到1之间
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0

# 将标签从整数转换为one-hot编码
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
Copy after login

Next, we will define a convolutional neural network model. We will use three convolutional layers and three pooling layers to extract features, and then two fully connected layers for classification. The following is our model definition:

model = keras.Sequential(
    [
        # 第一个卷积层
        layers.Conv2D(32, (3, 3), activation="relu", input_shape=(32, 32, 3)),
        layers.MaxPooling2D((2, 2)),
        # 第二个卷积层
        layers.Conv2D(64, (3, 3), activation="relu"),
        layers.MaxPooling2D((2, 2)),
        # 第三个卷积层
        layers.Conv2D(128, (3, 3), activation="relu"),
        layers.MaxPooling2D((2, 2)),
        # 展平层
        layers.Flatten(),
        # 全连接层
       layers.Dense(128, activation="relu"),
        layers.Dense(10, activation="softmax"),
    ]
)
Copy after login

In this model, we use the ReLU activation function, which is a commonly used nonlinear function that can help the model learn complex nonlinear relationships. We also used the softmax activation function for multi-class classification.

Now, we can compile the model and start training. We will use the Adam optimizer and the cross-entropy loss function for model training. Here is the code: model.compile(optimizer='adam', loss='categorical_crossentropy') model.fit(X_train, y_train, epochs=10, batch_size=32)

# 编译模型
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])

# 训练模型
history = model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))
Copy after login

After training is completed, we can use the test set to evaluate the performance of the model. Here is our code for evaluating the model:

# 在测试集上评估模型
test_loss, test_acc = model.evaluate(x_test, y_test)

print("Test loss:", test_loss)
print("Test accuracy:", test_acc)
Copy after login

Finally, we can use the training history to plot the training and validation loss and accuracy of the model. The following is the code for drawing training history:

import matplotlib.pyplot as plt

# 绘制训练和验证损失
plt.plot(history.history["loss"], label="Training loss")
plt.plot(history.history["val_loss"], label="Validation loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.legend()

plt.show()

# 绘制训练和验证准确率
plt.plot(history.history["accuracy"], label="Training accuracy")
plt.plot(history.history["val_accuracy"], label="Validation accuracy")
plt.xlabel("Epoch")
plt.ylabel("Accuracy")
plt.legend()

plt.show()
Copy after login

The above is the entire code for an example of a deep learning model based on TensorFlow and Keras. We built a convolutional neural network model using the CIFAR-10 dataset for image classification tasks.

The above is the detailed content of Build deep learning models with TensorFlow and Keras. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:163.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!