实践案例 - 使用Python和TensorFlow构建简单的图像分类模型

这里我们将利用TensorFlow库来创建一个基本的卷积神经网络(CNN),用于识别MNIST手写数字数据集中的图片。这个例子展示了如何轻松地应用深度学习技术解决问题。

```python

import tensorflow as tf

from tensorflow.keras import datasets, layers, models

import matplotlib.pyplot as plt

加载数据

(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()

数据预处理

train_images = train_images.reshape((60000, 28, 28, 1))

test_images = test_images.reshape((10000, 28, 28, 1))

归一化像素值到 0, 1 区间

train_images, test_images = train_images / 255.0, test_images / 255.0

构建CNN模型

model = models.Sequential()

model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))

model.add(layers.MaxPooling2D((2, 2)))

model.add(layers.Conv2D(64, (3, 3), activation='relu'))

model.add(layers.MaxPooling2D((2, 2)))

model.add(layers.Conv2D(64, (3, 3), activation='relu'))

添加全连接层

model.add(layers.Flatten())

model.add(layers.Dense(64, activation='relu'))

model.add(layers.Dense(10))

编译模型

model.compile(optimizer='adam',

loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),

metrics='accuracy')

训练模型

history = model.fit(train_images, train_labels, epochs=5,

validation_data=(test_images, test_labels))

评估模型

test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)

print('\nTest accuracy:', test_acc)

绘制训练过程中的损失和准确率变化

plt.figure(figsize=(12, 4))

plt.subplot(1, 2, 1)

plt.plot(history.history'loss', label='Training Loss')

plt.plot(history.history'val_loss', label='Validation Loss')

plt.legend()

plt.title('Loss over Epochs')

plt.subplot(1, 2, 2)

plt.plot(history.history'accuracy', label='Training Accuracy')

plt.plot(history.history'val_accuracy', label='Validation Accuracy')

plt.legend()

plt.title('Accuracy over Epochs')

plt.show()

```

这段代码首先加载了MNIST数据集并对图像进行了预处理;接着定义了一个包含三个卷积层和两个全连接层的简单CNN架构;最后训练该模型并在测试集上评估其性能。此外,还绘制了训练过程中损失值及准确率的变化曲线图,以便直观地了解模型的学习情况。

相关推荐
Thomas.Sir4 天前
第26课:TensorFlow|循环神经网络RNN原理【时序数据处理、序列依赖关系讲解】
人工智能·rnn·tensorflow
Thomas.Sir4 天前
第24课:TensorFlow|图像分类实战训练【手写数字、日常图像分类完整项目】
人工智能·分类·tensorflow
2601_962077985 天前
机器学习及其Python实践
pytorch·python·机器学习·tensorflow·scikit-learn
2601_962300475 天前
Python TensorFlow对比PyTorch_Python TensorFlow和PyTorch在机器学习中的差异
pytorch·python·深度学习·机器学习·tensorflow
2601_962381586 天前
[Python人工智能] 九.gensim词向量Word2Vec安装及《庆余年》中文短文本相似度计算
人工智能·python·tensorflow·word2vec·文本相似度
小江的记录本6 天前
【CSS】CSS 核心:盒模型、BFC/IFC、Flex/Grid 布局、响应式布局、移动端适配(附《思维导图》)
前端·css·面试·前端框架·tensorflow·html5·xss
CIO_Alliance15 天前
AI深度系列(1)|神经元激活函数与MLP原理:理解神经网络的基础
人工智能·深度学习·神经网络·机器学习·tensorflow·ai+ipaas·企业cio联盟
老郑聊AI业财智造15 天前
TensorFlow 技术架构与源码分析
人工智能·python·深度学习·架构·tensorflow·软件工程
CarIise18 天前
CSS选择器与样式关联
前端·css·tensorflow
现代野蛮人20 天前
【深度学习实验】—— 利用 RNN 模型进行心脏病预测
pytorch·python·tensorflow·ml