You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm中无法从tf.keras.datasets导入示例数据集的问题

解决方案

1. 处理包冲突问题

TensorFlow 2.12.0本身内置了对应版本的Keras,没必要单独安装keras包,单独安装反而会打乱模块结构。先卸载单独安装的keras:

pip uninstall -y keras

接着强制重新安装TensorFlow,确保安装包完整:

pip install --force-reinstall tensorflow==2.12.0

2. 验证模块完整性

重新安装后,查看虚拟环境的/venv/Lib/site-packages/tensorflow/python/keras目录下是否出现datasets文件夹。如果仍未出现,执行以下命令检查TensorFlow包的文件列表,确认是否包含datasets相关文件:

pip show -f tensorflow==2.12.0 | grep "datasets"

如果输出中没有datasets相关内容,说明安装缓存损坏,清理缓存后重新安装:

pip cache purge
pip install tensorflow==2.12.0

3. 使用标准导入语句

不要使用tensorflow.python.keras这类内部私有路径,官方推荐的标准导入方式是:

from tensorflow.keras.datasets import mnist

4. 确认PyCharm解释器配置

检查PyCharm是否确实使用了当前项目的虚拟环境:

  • 打开File > Settings > Project: [你的项目名] > Python Interpreter
  • 确认解释器路径为/venv/Scripts/python.exe(Windows)或/venv/bin/python(Linux/macOS)
  • 配置无误的话,点击右上角的刷新按钮,让PyCharm重新识别已安装的包

5. 备选方案:手动加载MNIST数据集

如果上述方法均无效,可以直接手动下载并加载数据集:

import numpy as np
import os

# 创建数据集存放目录
data_path = "./mnist_data"
os.makedirs(data_path, exist_ok=True)

def load_mnist():
    from urllib.request import urlretrieve
    import gzip

    # MNIST官方下载链接
    urls = [
        "http://yann.lecun.com/exdb/mnist/train-images-idx3-ubyte.gz",
        "http://yann.lecun.com/exdb/mnist/train-labels-idx1-ubyte.gz",
        "http://yann.lecun.com/exdb/mnist/t10k-images-idx3-ubyte.gz",
        "http://yann.lecun.com/exdb/mnist/t10k-labels-idx1-ubyte.gz"
    ]

    files = []
    for url in urls:
        filename = os.path.join(data_path, url.split("/")[-1])
        if not os.path.exists(filename):
            urlretrieve(url, filename)
        files.append(filename)

    # 解析压缩文件
    with gzip.open(files[0], 'rb') as f:
        x_train = np.frombuffer(f.read(), np.uint8, offset=16).reshape(-1, 28, 28)
    with gzip.open(files[1], 'rb') as f:
        y_train = np.frombuffer(f.read(), np.uint8, offset=8)
    with gzip.open(files[2], 'rb') as f:
        x_test = np.frombuffer(f.read(), np.uint8, offset=16).reshape(-1, 28, 28)
    with gzip.open(files[3], 'rb') as f:
        y_test = np.frombuffer(f.read(), np.uint8, offset=8)
    
    return (x_train, y_train), (x_test, y_test)

# 加载数据集
(x_train, y_train), (x_test, y_test) = load_mnist()

内容的提问来源于stack exchange,提问作者denz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:08:01