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

成功运行得出结果。

相关推荐
东方佑29 分钟前
利用Python和SQLite进行数据处理与优化——从数据库操作到高级数据压缩
数据库·python·sqlite
CsbLanca1 小时前
本地部署【LLM-deepseek】大模型 ollama+deepseek/conda(python)+openwebui/docker+openwebui
python·docker·conda
winfredzhang1 小时前
使用Python开发PPTX压缩工具
python·进程条·jpeg·压缩pptx
程序员小远2 小时前
Postman接口测试:postman设置接口关联,实现参数化
自动化测试·软件测试·python·测试工具·测试用例·接口测试·postman
智商不在服务器2 小时前
利用二分法进行 SQL 盲注
数据库·python·sql
测试19982 小时前
Selenium:网页frame与多窗口处理
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
大得3692 小时前
django中间件,中间件给下面传值
python·中间件·django
明月看潮生2 小时前
青少年编程与数学 02-009 Django 5 Web 编程 07课题、数据迁移
数据库·python·青少年编程·django·编程与数学
不亭2 小时前
python自动化测试之Pytest断言及Allure报告定制
开发语言·python·pytest
.Net Core 爱好者2 小时前
基于Flask搭建AI应用,本地私有化部署开源大语言模型
人工智能·后端·python·语言模型·自然语言处理·flask