运行TensorFlow加载Fashion-MNIST数据时遇SSL证书验证失败
解决TensorFlow加载Fashion MNIST时的SSL证书验证失败问题
运行TensorFlow加载Fashion MNIST数据集时出现ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)错误,已尝试运行Install Certificates.command和pip install --upgrade certifi但无效,以下是可行的解决方法:
方案1:匹配Python版本执行证书安装脚本
你当前使用的是Python 3.11的虚拟环境,但运行的是Python 3.12的证书脚本,导致虚拟环境未获取正确证书:
- 找到Python 3.11对应的证书脚本,路径通常为
/Applications/Python 3.11/Install Certificates.command,双击运行。 - 激活虚拟环境后重新升级certifi:
source /Users/lorenliu/PROGRAM/NeuralFuck/venv/bin/activate pip install --upgrade certifi
方案2:在代码中指定SSL上下文
修改代码,让Keras的下载逻辑使用正确的证书配置:
import ssl import certifi import tensorflow as tf # 方法1:临时跳过证书验证(快速解决,不推荐长期使用) ssl._create_default_https_context = ssl._create_unverified_context # 方法2:使用certifi提供的证书(更安全) # ssl._create_default_https_context = lambda: ssl.create_default_context(cafile=certifi.where()) print(tf.__version__) mnist = tf.keras.datasets.fashion_mnist (training_images, training_labels), (test_images, test_labels) = mnist.load_data()
方案3:手动下载数据集绕过网络请求
直接下载数据集文件到本地缓存目录,无需通过代码下载:
- 下载4个数据集文件:
train-labels-idx1-ubyte.gz、train-images-idx3-ubyte.gz、t10k-labels-idx1-ubyte.gz、t10k-images-idx3-ubyte.gz - 创建目录
~/.keras/datasets/fashion_mnist/(不存在则新建),将文件放入该目录 - 重新运行加载代码,会自动读取本地文件
说明你之前尝试的代码问题
你之前写的urlopen(dataResult = mnist.load_data(), context=...)写法错误,mnist.load_data()内部会自行发起下载请求,外部套urlopen无法干预它的请求上下文,因此没有效果。
内容的提问来源于stack exchange,提问作者LorenLiu
相关产品推荐
相关产品推荐

