search
HomeTechnology peripheralsAIBuild deep learning models with TensorFlow and Keras

Build deep learning models with TensorFlow and Keras

Jan 24, 2024 am 09:18 AM
machine learningdeep learning

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)

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"),
    ]
)

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))

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)

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()

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!

Statement
This article is reproduced at:网易伏羲. If there is any infringement, please contact admin@php.cn delete
Are You At Risk Of AI Agency Decay? Take The Test To Find OutAre You At Risk Of AI Agency Decay? Take The Test To Find OutApr 21, 2025 am 11:31 AM

This article explores the growing concern of "AI agency decay"—the gradual decline in our ability to think and decide independently. This is especially crucial for business leaders navigating the increasingly automated world while retainin

How to Build an AI Agent from Scratch? - Analytics VidhyaHow to Build an AI Agent from Scratch? - Analytics VidhyaApr 21, 2025 am 11:30 AM

Ever wondered how AI agents like Siri and Alexa work? These intelligent systems are becoming more important in our daily lives. This article introduces the ReAct pattern, a method that enhances AI agents by combining reasoning an

Revisiting The Humanities In The Age Of AIRevisiting The Humanities In The Age Of AIApr 21, 2025 am 11:28 AM

"I think AI tools are changing the learning opportunities for college students. We believe in developing students in core courses, but more and more people also want to get a perspective of computational and statistical thinking," said University of Chicago President Paul Alivisatos in an interview with Deloitte Nitin Mittal at the Davos Forum in January. He believes that people will have to become creators and co-creators of AI, which means that learning and other aspects need to adapt to some major changes. Digital intelligence and critical thinking Professor Alexa Joubin of George Washington University described artificial intelligence as a “heuristic tool” in the humanities and explores how it changes

Understanding LangChain Agent FrameworkUnderstanding LangChain Agent FrameworkApr 21, 2025 am 11:25 AM

LangChain is a powerful toolkit for building sophisticated AI applications. Its agent architecture is particularly noteworthy, allowing developers to create intelligent systems capable of independent reasoning, decision-making, and action. This expl

What are the Radial Basis Functions Neural Networks?What are the Radial Basis Functions Neural Networks?Apr 21, 2025 am 11:13 AM

Radial Basis Function Neural Networks (RBFNNs): A Comprehensive Guide Radial Basis Function Neural Networks (RBFNNs) are a powerful type of neural network architecture that leverages radial basis functions for activation. Their unique structure make

The Meshing Of Minds And Machines Has ArrivedThe Meshing Of Minds And Machines Has ArrivedApr 21, 2025 am 11:11 AM

Brain-computer interfaces (BCIs) directly link the brain to external devices, translating brain impulses into actions without physical movement. This technology utilizes implanted sensors to capture brain signals, converting them into digital comman

Insights on spaCy, Prodigy and Generative AI from Ines MontaniInsights on spaCy, Prodigy and Generative AI from Ines MontaniApr 21, 2025 am 11:01 AM

This "Leading with Data" episode features Ines Montani, co-founder and CEO of Explosion AI, and co-developer of spaCy and Prodigy. Ines offers expert insights into the evolution of these tools, Explosion's unique business model, and the tr

A Guide to Building Agentic RAG Systems with LangGraphA Guide to Building Agentic RAG Systems with LangGraphApr 21, 2025 am 11:00 AM

This article explores Retrieval Augmented Generation (RAG) systems and how AI agents can enhance their capabilities. Traditional RAG systems, while useful for leveraging custom enterprise data, suffer from limitations such as a lack of real-time dat

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools