cnn机器学习时python版本不兼容报错

在使用python执行CNN算法时,发生如下报错:

复制代码
A module that was compiled using NumPy 1.x cannot be run in NumPy 2.1.1 as it may crash. 
To support both 1.x and 2.x versions of NumPy, modules must be compiled with NumPy 2.0. Some module may need to rebuild instead e.g. with 'pybind11>=2.12'. 

If you are a user of the module, the easiest solution will be to downgrade to 'numpy<2' or try to upgrade the affected module. 
We expect that some modules will need time to support NumPy 2.

这时候需要安装指定版本。

复制代码
pip install numpy==1.26.4

安装完成后重新运行代码。

复制代码
import tensorflow as tf
from keras import datasets, layers, models
import matplotlib.pyplot as plt

# 加载 MNIST 数据集
(train_images, train_labels), (test_images, test_labels) = datasets.mnist.load_data()
train_images, test_images = train_images / 255.0, test_images / 255.0
train_images = train_images.reshape((train_images.shape[0], 28, 28, 1))
test_images = test_images.reshape((test_images.shape[0], 28, 28, 1))

# 构建 CNN 模型
model = models.Sequential([
    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.MaxPooling2D((2, 2)),
    layers.Conv2D(64, (3, 3), activation='relu'),
    layers.Flatten(),
    layers.Dense(64, activation='relu'),
    layers.Dense(10, activation='softmax')
])

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

# 训练模型
history = model.fit(train_images, train_labels, epochs=10, 
                    validation_data=(test_images, test_labels))

# 评估模型
test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2)
print(f'\nTest accuracy: {test_acc:.4f}')

# 绘制训练过程中的准确率
plt.figure(figsize=(12, 4))

plt.subplot(1, 2, 1)
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.title('Accuracy Over Time')
plt.show()

成功运行得出结果。

相关推荐
鸿蒙布道师17 分钟前
英伟达开源Llama-Nemotron系列模型:14万H100小时训练细节全解析
深度学习·神经网络·opencv·机器学习·自然语言处理·数据挖掘·llama
Cloud Traveler38 分钟前
Java并发编程常见问题与陷阱解析
java·开发语言·python
山海不说话1 小时前
PyGame游戏开发(含源码+演示视频+开结题报告+设计文档)
python·pygame
Y3174292 小时前
Python Day 22 学习
python·学习
正在走向自律3 小时前
Python 自动化脚本开发秘籍:从入门到实战进阶(6/10)
开发语言·python
白熊1883 小时前
【计算机视觉】基于Python的相机标定项目Camera-Calibration深度解析
python·数码相机·计算机视觉
仙人掌_lz3 小时前
深入理解深度Q网络DQN:基于python从零实现
python·算法·强化学习·dqn·rl
Joern-Lee3 小时前
机器学习极简入门:从基础概念到行业应用
人工智能·机器学习
小雅痞4 小时前
[Java][Leetcode middle] 80. 删除有序数组中的重复项 II
java·python·leetcode
大叔_爱编程4 小时前
p020基于Django的4S店客户管理系统
vue.js·python·django·毕业设计·源码·课程设计·4s店客户管理系统