plt.style.use('./deeplearning.mplstyle')相对导入报错,求解决
问题:Matplotlib加载本地样式文件时出现相对导入错误
完成Deeplearning.AI机器学习专项课程后,复习相关概念与实验时已将所有文件下载并放在同一文件夹中,遇到如下错误:
TypeError: the 'package' argument is required to perform a relative import for './deeplearning'
运行的代码块:
import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.layers import Dense, Input from tensorflow.keras import Sequential from tensorflow.keras.losses import MeanSquaredError, BinaryCrossentropy from tensorflow.keras.activations import sigmoid from lab_utils_common import dlc
完整错误堆栈:
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[3], line 8 6 from tensorflow.keras.losses import MeanSquaredError, BinaryCrossentropy 7 from tensorflow.keras.activations import sigmoid ----> 8 from lab_utils_common import dlc 9 from lab_neurons_utils import plt_prob_1d, sigmoidnp, plt_linear, plt_logistic 10 plt.style.use('./deeplearning.mplstyle') File ~\Desktop\ML2\Week1\Files\Files\home\jovyan\work\lab_utils_common.py:22 20 dlblue = '#0096ff'; dlorange = '#FF9300'; dldarkred='#C00000'; dlmagenta='#FF40FF'; dlpurple='#7030A0'; dldarkblue = '#0D5BDC' 21 dlcolors = [dlblue, dlorange, dldarkred, dlmagenta, dlpurple] ---> 22 plt.style.use('./deeplearning.mplstyle') 24 def sigmoid(z): 25 """ 26 Compute the sigmoid of z 27 (...) 36 sigmoid(z) 37 """ File C:\ProgramData\anaconda3\lib\site-packages\matplotlib\style\core.py:153, in use(style) 151 pkg, _, name = style.rpartition(".") 152 try: ---> 153 path = (importlib_resources.files(pkg) 154 / f"{name}.{STYLE_EXTENSION}") 155 style = _rc_params_in_file(path) 156 except (ModuleNotFoundError, IOError) as exc: 157 # There is an ambiguity whether a dotted name refers to a 158 # package.style_name or to a dotted file path. Currently, (...) 161 # either use Path objects or be prepended with "./" and use 162 # the slash as marker for file paths. File C:\ProgramData\anaconda3\lib\importlib\_common.py:22, in files(package) 17 def files(package): 18 # type: (Package) -> Traversable 19 """ 20 Get a Traversable resource from a package 21 """ ---> 22 return from_package(get_package(package)) File C:\ProgramData\anaconda3\lib\importlib\_common.py:66, in get_package(package) 60 def get_package(package): 61 # type: (Package) -> types.ModuleType 62 """Take a package name or module object and return the module. 63 64 Raise an exception if the resolved module is not a package. 65 """ ---> 66 resolved = resolve(package) 67 if wrap_spec(resolved).submodule_search_locations is None: 68 raise TypeError(f'{package!r} is not a package') File C:\ProgramData\anaconda3\lib\importlib\_common.py:57, in resolve(cand) 55 def resolve(cand): 56 # type: (Package) -> types.ModuleType ---> 57 return cand if isinstance(cand, types.ModuleType) else importlib.import_module(cand) File C:\ProgramData\anaconda3\lib\importlib\__init__.py:121, in import_module(name, package) 118 if not package: 119 msg = ("the 'package' argument is required to perform a relative " 120 "import for {!r}") ---> 121 raise TypeError(msg.format(name)) 122 for character in name: 123 if character != '.': TypeError: the 'package' argument is required to perform a relative import for './deeplearning'
解决方案
不需要额外添加package参数,问题源于Matplotlib对相对路径的解析逻辑偏差,可通过以下三种方式解决:
方法一:替换为绝对路径
打开lab_utils_common.py文件,找到第22行,将相对路径替换为样式文件的绝对路径。示例:
plt.style.use('C:/Desktop/ML2/Week1/Files/deeplearning.mplstyle')
请根据自己的实际文件路径修改。
方法二:使用Path对象动态获取路径
通过pathlib模块的Path对象,自动根据脚本位置定位同级的样式文件,避免硬编码路径。修改lab_utils_common.py中的代码:
from pathlib import Path style_path = Path(__file__).parent / 'deeplearning.mplstyle' plt.style.use(style_path)
方法三:放入Matplotlib默认样式目录
- 运行以下代码查看Matplotlib的默认样式目录:
import matplotlib.pyplot as plt print(plt.style.core.STYLE_LIBRARY_PATH)
- 将
deeplearning.mplstyle复制到该目录下,之后直接用以下代码加载样式:
plt.style.use('deeplearning')
内容的提问来源于stack exchange,提问作者Kevin
相关产品推荐
相关产品推荐

