使用keras.utils.get_file()触发TypeError:int与NoneType无法比较
keras.utils.get_file()调用触发TypeError错误
环境信息
- Windows 10
- Python 3.9.19
- Tensorflow 2.10.1
代码片段
dataset_path = keras.utils.get_file("auto-mpg.data", "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data")
问题描述
学习《Applied Deep Learning and Computer Vision for Self-Driving Cars》一书时,运行示例代码调用keras.utils.get_file()获取数据集文件,触发TypeError,错误提示'<' not supported between instances of 'int' and 'NoneType'。期望成功下载并获取文件路径,已查阅相关Stack Overflow帖子但仅得到“It works for me”的回复,无法解决问题。
报错详情
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[2], line 2 1 # Datapath to import auto-mpg data ----> 2 dataset_path = keras.utils.get_file("auto-mpg.data", "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data") File ~\anaconda3\envs\AVTech\lib\site-packages\keras\utils\data_utils.py:296, in get_file(fname, origin, untar, md5_hash, file_hash, cache_subdir, hash_algorithm, extract, archive_format, cache_dir) 294 try: 295 try: ---> 296 urlretrieve(origin, fpath, DLProgbar()) 297 except urllib.error.HTTPError as e: 298 raise Exception(error_msg.format(origin, e.code, e.msg)) File ~\anaconda3\envs\AVTech\lib\site-packages\keras\utils\data_utils.py:86, in urlretrieve(url, filename, reporthook, data) 84 response = urlopen(url, data) 85 with open(filename, "wb") as fd: ---> 86 for chunk in chunk_read(response, reporthook=reporthook): 87 fd.write(chunk) File ~\anaconda3\envs\AVTech\lib\site-packages\keras\utils\data_utils.py:78, in urlretrieve.<locals>.chunk_read(response, chunk_size, reporthook) 76 count += 1 77 if reporthook is not None: ---> 78 reporthook(count, chunk_size, total_size) 79 if chunk: 80 yield chunk File ~\anaconda3\envs\AVTech\lib\site-packages\keras\utils\data_utils.py:287, in get_file.<locals>.DLProgbar.__call__(self, block_num, block_size, total_size) 285 self.progbar = Progbar(total_size) 286 current = block_num * block_size ---> 287 if current < total_size: 288 self.progbar.update(current) 289 elif not self.finished: TypeError: '<' not supported between instances of 'int' and 'NoneType'
解决方案
该错误源于服务器返回的响应未提供文件总大小(Content-Length),导致total_size为None,进度条更新时触发类型不匹配错误,可通过以下方式解决:
跳过进度条逻辑:
修改get_file调用,手动设置reporthook=None,绕过进度条的更新判断:dataset_path = keras.utils.get_file( "auto-mpg.data", "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data", reporthook=None )手动指定本地文件路径:
直接访问URL下载auto-mpg.data文件,保存到本地后,将文件路径直接赋值给变量:dataset_path = "本地文件存储路径/auto-mpg.data"升级TensorFlow版本:
该问题在TensorFlow 2.11及以上版本中已被修复,升级到稳定新版本即可解决:pip install --upgrade tensorflow
内容的提问来源于stack exchange,提问作者RPBruiser
相关产品推荐
相关产品推荐

