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

成功运行得出结果。

相关推荐
具身新纪元18 分钟前
CVPR 2026|新缺陷不断上线,如何让工业视觉检测模型不忘旧账?
人工智能·深度学习·目标检测·机器学习·计算机视觉·目标跟踪·视觉检测
weixin_BYSJ198722 分钟前
【java项目分享】springboot阅读推荐平台10600
java·javascript·spring boot·python·django·flask·php
阿kun要赚马内27 分钟前
工具在langchain agent中的调用
人工智能·后端·python
GrowthDiary00737 分钟前
Python 常用函数总结
开发语言·python
only-qi37 分钟前
大模型微调流程深度解析:从面试题到工程实践
人工智能·机器学习·ai·llm
2601_957883841 小时前
2026年8月:外星人笔记本维修服务揭秘
python·电脑
eric-sjq1 小时前
仅0.6B参数如何锁住超长记忆?Xiaothink-T17-RWKV5-MLA 架构深度解析:RWKV-v5 × MLA 的“降维打击“
python·架构
一次旅行1 小时前
Ollama本地私有化大模型完整工程实战
人工智能·机器学习·github
张小凡vip1 小时前
Python爬虫实战:高效稳定的文件下载模块设计与实现
开发语言·爬虫·python
小趴蔡ha10 小时前
02 Anaconda、Python 与机器学习开发环境入门
python·机器学习·anaconda