系统学习Python——警告信息的控制模块warnings:常用函数-[warnings.warn_explicit]

本文介绍了Python中的warnings模块,包括其基本概念、warn_explicit函数的用法,以及如何控制和过滤警告信息,如类别、文件名和行号等参数的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

分类目录:《系统学习Python》总目录
相关文章:


函数

warnings.warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)

这个函数是warn()函数的底层接口,显式传入消息、类别、文件名和行号,以及可选的模块名和注册表(应为模块的__warningregistry__字典)。 模块名称默认为去除了.py的文件名;如果未传递注册表,警告就不会被抑制。

参数

  • message:输出的警告信息,应是一个字符串或Warning的实例
  • category:是Warning的子类;若messageWarning的实例,则category将被忽略。
  • module_globals应为发出警告的代码所用的全局命名空间。(该参数用于从zip文件或其他非文件系统导入模块时显式源码)。
  • source是发出ResourceWarning的被销毁对象
#下面程序运行时报错: C:\Users\Administrator\AppData\Local\Programs\Python\Python312\python.exe C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\utils\generic.py Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python312\Lib\site-packages\transformers\utils\generic.py", line 34, in <module> from ..utils import logging ImportError: attempted relative import with no known parent package 进程已结束,退出代码为 1 ------------------------------------------------------------------------------------------------ import inspect import json import os import tempfile import warnings from collections import OrderedDict, UserDict, defaultdict from collections.abc import Iterable, MutableMapping from contextlib import ExitStack, contextmanager from dataclasses import dataclass, fields, is_dataclass from enum import Enum from functools import partial, wraps from typing import Any, Callable, ContextManager, Optional, TypedDict import numpy as np from packaging import version from ..utils import logging from .import_utils import ( get_torch_version, is_flax_available, is_mlx_available, is_tf_available, is_torch_available, is_torch_fx_proxy, requires, ) _CAN_RECORD_REGISTRY = {} logger = logging.get_logger(__name__) if is_torch_available(): # required for @can_return_tuple decorator to work with torchdynamo import torch # noqa: F401 from ..model_debugging_utils import model_addition_debugger_context class cached_property(property): """ Descriptor that mimics @property but caches output in member variable. From tensorflow_datasets Built-in in functools from Python 3.8. """ def __get__(self, obj, objtype=None): # See docs.python.org/3/howto/descriptor.html#properties if obj is None: return self if self.fget is None: raise AttributeError("unreadable attribute") attr = "__cached_" + self.fget.__name__ cached = getattr(obj, attr, None) if cached is None: cached = self.fget(obj) setattr(obj, attr, cached) return cached # vendored from distutils.util def strtobool(val): """Convert a string representation of truth to true (1) or false (0). True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', 'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. """ val = val.lower() if val in {"y", "yes", "t", "true", "on", "1"}: return 1 if val in {"n", "no", "f", "false", "off", "0"}: return 0 raise ValueError(f"invalid truth value {val!r}") def infer_framework_from_repr(x): """ Tries to guess the framework of an object `x` from its repr (brittle but will help in `is_tensor` to try the frameworks in a smart order, without the need to import the frameworks). """ representation = str(type(x)) if representation.startswith("<class 'torch."): return "pt" elif representation.startswith("<class 'tensorflow."): return "tf" elif representation.startswith("<class 'jax"): return "jax" elif representation.startswith("<class 'numpy."): return "np" elif representation.startswith("<class 'mlx."): return "mlx" def _get_frameworks_and_test_func(x): """ Returns an (ordered since we are in Python 3.7+) dictionary framework to test function, which places the framework we can guess from the repr first, then Numpy, then the others. """ framework_to_test = { "pt": is_torch_tensor, "tf": is_tf_tensor, "jax": is_jax_tensor, "np": is_numpy_array, "mlx": is_mlx_array, } preferred_framework = infer_framework_from_repr(x) # We will test this one first, then numpy, then the others. frameworks = [] if preferred_framework is None else [preferred_framework] if preferred_framework != "np": frameworks.append("np") frameworks.extend([f for f in framework_to_test if f not in [preferred_framework, "np"]]) return {f: framework_to_test[f] for f in frameworks} def is_tensor(x): """ Tests if `x` is a `torch.Tensor`, `tf.Tensor`, `jaxlib.xla_extension.DeviceArray`, `np.ndarray` or `mlx.array` in the order defined by `infer_framework_from_repr` """ # This gives us a smart order to test the frameworks with the corresponding tests. framework_to_test_func = _get_frameworks_and_test_func(x) for test_func in framework_to_test_func.values(): if test_func(x): return True # Tracers if is_torch_fx_proxy(x): return True if is_flax_available(): from jax.core import Tracer if isinstance(x, Tracer): return True return False def _is_numpy(x): return isinstance(x, np.ndarray) def is_numpy_array(x): """ Tests if `x` is a numpy array or not. """ return _is_numpy(x) def _is_torch(x): import torch return isinstance(x, torch.Tensor) def is_torch_tensor(x): """ Tests if `x` is a torch tensor or not. Safe to call even if torch is not installed. """ return False if not is_torch_available() else _is_torch(x) def _is_torch_device(x): import torch return isinstance(x, torch.device) def is_torch_device(x): """ Tests if `x` is a torch device or not. Safe to call even if torch is not installed. """ return False if not is_torch_available() else _is_torch_device(x) def _is_torch_dtype(x): import torch if isinstance(x, str): if hasattr(torch, x): x = getattr(torch, x) else: return False return isinstance(x, torch.dtype) def is_torch_dtype(x): """ Tests if `x` is a torch dtype or not. Safe to call even if torch is not installed. """ return False if not is_torch_available() else _is_torch_dtype(x) def _is_tensorflow(x): import tensorflow as tf return isinstance(x, tf.Tensor) def is_tf_tensor(x): """ Tests if `x` is a tensorflow tensor or not. Safe to call even if tensorflow is not installed. """ return False if not is_tf_available() else _is_tensorflow(x) def _is_tf_symbolic_tensor(x): import tensorflow as tf # the `is_symbolic_tensor` predicate is only available starting with TF 2.14 if hasattr(tf, "is_symbolic_tensor"): return tf.is_symbolic_tensor(x) return isinstance(x, tf.Tensor) def is_tf_symbolic_tensor(x): """ Tests if `x` is a tensorflow symbolic tensor or not (ie. not eager). Safe to call even if tensorflow is not installed. """ return False if not is_tf_available() else _is_tf_symbolic_tensor(x) def _is_jax(x): import jax.numpy as jnp # noqa: F811 return isinstance(x, jnp.ndarray) def is_jax_tensor(x): """ Tests if `x` is a Jax tensor or not. Safe to call even if jax is not installed. """ return False if not is_flax_available() else _is_jax(x) def _is_mlx(x): import mlx.core as mx return isinstance(x, mx.array) def is_mlx_array(x): """ Tests if `x` is a mlx array or not. Safe to call even when mlx is not installed. """ return False if not is_mlx_available() else _is_mlx(x) def to_py_obj(obj): """ Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a python list. """ if isinstance(obj, (int, float)): return obj elif isinstance(obj, (dict, UserDict)): return {k: to_py_obj(v) for k, v in obj.items()} elif isinstance(obj, (list, tuple)): try: arr = np.array(obj) if np.issubdtype(arr.dtype, np.integer) or np.issubdtype(arr.dtype, np.floating): return arr.tolist() except Exception: pass return [to_py_obj(o) for o in obj] framework_to_py_obj = { "pt": lambda obj: obj.tolist(), "tf": lambda obj: obj.numpy().tolist(), "jax": lambda obj: np.asarray(obj).tolist(), "np": lambda obj: obj.tolist(), } # This gives us a smart order to test the frameworks with the corresponding tests. framework_to_test_func = _get_frameworks_and_test_func(obj) for framework, test_func in framework_to_test_func.items(): if test_func(obj): return framework_to_py_obj[framework](obj) # tolist also works on 0d np arrays if isinstance(obj, np.number): return obj.tolist() else: return obj def to_numpy(obj): """ Convert a TensorFlow tensor, PyTorch tensor, Numpy array or python list to a Numpy array. """ framework_to_numpy = { "pt": lambda obj: obj.detach().cpu().numpy(), "tf": lambda obj: obj.numpy(), "jax": lambda obj: np.asarray(obj), "np": lambda obj: obj, } if isinstance(obj, (dict, UserDict)): return {k: to_numpy(v) for k, v in obj.items()} elif isinstance(obj, (list, tuple)): return np.array(obj) # This gives us a smart order to test the frameworks with the corresponding tests. framework_to_test_func = _get_frameworks_and_test_func(obj) for framework, test_func in framework_to_test_func.items(): if test_func(obj): return framework_to_numpy[framework](obj) return obj class ModelOutput(OrderedDict): """ Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular python dictionary. <Tip warning={true}> You can't unpack a `ModelOutput` directly. Use the [`~utils.ModelOutput.to_tuple`] method to convert it to a tuple before. </Tip> """ def __init_subclass__(cls) -> None: """Register subclasses as pytree nodes. This is necessary to synchronize gradients when using `torch.nn.parallel.DistributedDataParallel` with `static_graph=True` with modules that output `ModelOutput` subclasses. """ if is_torch_available(): if version.parse(get_torch_version()) >= version.parse("2.2"): from torch.utils._pytree import register_pytree_node register_pytree_node( cls, _model_output_flatten, partial(_model_output_unflatten, output_type=cls), serialized_type_name=f"{cls.__module__}.{cls.__name__}", ) else: from torch.utils._pytree import _register_pytree_node _register_pytree_node( cls, _model_output_flatten, partial(_model_output_unflatten, output_type=cls), ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Subclasses of ModelOutput must use the @dataclass decorator # This check is done in __init__ because the @dataclass decorator operates after __init_subclass__ # issubclass() would return True for issubclass(ModelOutput, ModelOutput) when False is needed # Just need to check that the current class is not ModelOutput is_modeloutput_subclass = self.__class__ != ModelOutput if is_modeloutput_subclass and not is_dataclass(self): raise TypeError( f"{self.__module__}.{self.__class__.__name__} is not a dataclass." " This is a subclass of ModelOutput and so must use the @dataclass decorator." ) def __post_init__(self): """Check the ModelOutput dataclass. Only occurs if @dataclass decorator has been used. """ class_fields = fields(self) # Safety and consistency checks if not len(class_fields): raise ValueError(f"{self.__class__.__name__} has no fields.") if not all(field.default is None for field in class_fields[1:]): raise ValueError(f"{self.__class__.__name__} should not have more than one required field.") first_field = getattr(self, class_fields[0].name) other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:]) if other_fields_are_none and not is_tensor(first_field): if isinstance(first_field, dict): iterator = first_field.items() first_field_iterator = True else: try: iterator = iter(first_field) first_field_iterator = True except TypeError: first_field_iterator = False # if we provided an iterator as first field and the iterator is a (key, value) iterator # set the associated fields if first_field_iterator: for idx, element in enumerate(iterator): if not isinstance(element, (list, tuple)) or len(element) != 2 or not isinstance(element[0], str): if idx == 0: # If we do not have an iterator of key/values, set it as attribute self[class_fields[0].name] = first_field else: # If we have a mixed iterator, raise an error raise ValueError( f"Cannot set key/value for {element}. It needs to be a tuple (key, value)." ) break setattr(self, element[0], element[1]) if element[1] is not None: self[element[0]] = element[1] elif first_field is not None: self[class_fields[0].name] = first_field else: for field in class_fields: v = getattr(self, field.name) if v is not None: self[field.name] = v def __delitem__(self, *args, **kwargs): raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.") def setdefault(self, *args, **kwargs): raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.") def pop(self, *args, **kwargs): raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.") def update(self, *args, **kwargs): raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.") def __getitem__(self, k): if isinstance(k, str): inner_dict = dict(self.items()) return inner_dict[k] else: return self.to_tuple()[k] def __setattr__(self, name, value): if name in self.keys() and value is not None: # Don't call self.__setitem__ to avoid recursion errors super().__setitem__(name, value) super().__setattr__(name, value) def __setitem__(self, key, value): # Will raise a KeyException if needed super().__setitem__(key, value) # Don't call self.__setattr__ to avoid recursion errors super().__setattr__(key, value) def __reduce__(self): if not is_dataclass(self): return super().__reduce__() callable, _args, *remaining = super().__reduce__() args = tuple(getattr(self, field.name) for field in fields(self)) return callable, args, *remaining def to_tuple(self) -> tuple[Any]: """ Convert self to a tuple containing all the attributes/keys that are not `None`. """ return tuple(self[k] for k in self.keys()) if is_torch_available(): import torch.utils._pytree as _torch_pytree def _model_output_flatten(output: ModelOutput) -> tuple[list[Any], "_torch_pytree.Context"]: return list(output.values()), list(output.keys()) def _model_output_unflatten( values: Iterable[Any], context: "_torch_pytree.Context", output_type=None, ) -> ModelOutput: return output_type(**dict(zip(context, values))) if version.parse(get_torch_version()) >= version.parse("2.2"): _torch_pytree.register_pytree_node( ModelOutput, _model_output_flatten, partial(_model_output_unflatten, output_type=ModelOutput), serialized_type_name=f"{ModelOutput.__module__}.{ModelOutput.__name__}", ) else: _torch_pytree._register_pytree_node( ModelOutput, _model_output_flatten, partial(_model_output_unflatten, output_type=ModelOutput), ) class ExplicitEnum(str, Enum): """ Enum with more explicit error message for missing values. """ @classmethod def _missing_(cls, value): raise ValueError( f"{value} is not a valid {cls.__name__}, please select one of {list(cls._value2member_map_.keys())}" ) class PaddingStrategy(ExplicitEnum): """ Possible values for the `padding` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an IDE. """ LONGEST = "longest" MAX_LENGTH = "max_length" DO_NOT_PAD = "do_not_pad" class TensorType(ExplicitEnum): """ Possible values for the `return_tensors` argument in [`PreTrainedTokenizerBase.__call__`]. Useful for tab-completion in an IDE. """ PYTORCH = "pt" TENSORFLOW = "tf" NUMPY = "np" JAX = "jax" MLX = "mlx" class ContextManagers: """ Wrapper for `contextlib.ExitStack` which enters a collection of context managers. Adaptation of `ContextManagers` in the `fastcore` library. """ def __init__(self, context_managers: list[ContextManager]): self.context_managers = context_managers self.stack = ExitStack() def __enter__(self): for context_manager in self.context_managers: self.stack.enter_context(context_manager) def __exit__(self, *args, **kwargs): self.stack.__exit__(*args, **kwargs) def can_return_loss(model_class): """ Check if a given model can return loss. Args: model_class (`type`): The class of the model. """ framework = infer_framework(model_class) if framework == "tf": signature = inspect.signature(model_class.call) # TensorFlow models elif framework == "pt": signature = inspect.signature(model_class.forward) # PyTorch models else: signature = inspect.signature(model_class.__call__) # Flax models for p in signature.parameters: if p == "return_loss" and signature.parameters[p].default is True: return True return False def find_labels(model_class): """ Find the labels used by a given model. Args: model_class (`type`): The class of the model. """ model_name = model_class.__name__ framework = infer_framework(model_class) if framework == "tf": signature = inspect.signature(model_class.call) # TensorFlow models elif framework == "pt": signature = inspect.signature(model_class.forward) # PyTorch models else: signature = inspect.signature(model_class.__call__) # Flax models if "QuestionAnswering" in model_name: return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")] else: return [p for p in signature.parameters if "label" in p] def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."): """Flatten a nested dict into a single level dict.""" def _flatten_dict(d, parent_key="", delimiter="."): for k, v in d.items(): key = str(parent_key) + delimiter + str(k) if parent_key else k if v and isinstance(v, MutableMapping): yield from flatten_dict(v, key, delimiter=delimiter).items() else: yield key, v return dict(_flatten_dict(d, parent_key, delimiter)) @contextmanager def working_or_temp_dir(working_dir, use_temp_dir: bool = False): if use_temp_dir: with tempfile.TemporaryDirectory() as tmp_dir: yield tmp_dir else: yield working_dir def transpose(array, axes=None): """ Framework-agnostic version of `numpy.transpose` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.transpose(array, axes=axes) elif is_torch_tensor(array): return array.T if axes is None else array.permute(*axes) elif is_tf_tensor(array): import tensorflow as tf return tf.transpose(array, perm=axes) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.transpose(array, axes=axes) else: raise ValueError(f"Type not supported for transpose: {type(array)}.") def reshape(array, newshape): """ Framework-agnostic version of `numpy.reshape` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.reshape(array, newshape) elif is_torch_tensor(array): return array.reshape(*newshape) elif is_tf_tensor(array): import tensorflow as tf return tf.reshape(array, newshape) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.reshape(array, newshape) else: raise ValueError(f"Type not supported for reshape: {type(array)}.") def squeeze(array, axis=None): """ Framework-agnostic version of `numpy.squeeze` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.squeeze(array, axis=axis) elif is_torch_tensor(array): return array.squeeze() if axis is None else array.squeeze(dim=axis) elif is_tf_tensor(array): import tensorflow as tf return tf.squeeze(array, axis=axis) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.squeeze(array, axis=axis) else: raise ValueError(f"Type not supported for squeeze: {type(array)}.") def expand_dims(array, axis): """ Framework-agnostic version of `numpy.expand_dims` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.expand_dims(array, axis) elif is_torch_tensor(array): return array.unsqueeze(dim=axis) elif is_tf_tensor(array): import tensorflow as tf return tf.expand_dims(array, axis=axis) elif is_jax_tensor(array): import jax.numpy as jnp return jnp.expand_dims(array, axis=axis) else: raise ValueError(f"Type not supported for expand_dims: {type(array)}.") def tensor_size(array): """ Framework-agnostic version of `numpy.size` that will work on torch/TensorFlow/Jax tensors as well as NumPy arrays. """ if is_numpy_array(array): return np.size(array) elif is_torch_tensor(array): return array.numel() elif is_tf_tensor(array): import tensorflow as tf return tf.size(array) elif is_jax_tensor(array): return array.size else: raise ValueError(f"Type not supported for tensor_size: {type(array)}.") def infer_framework(model_class): """ Infers the framework of a given model without using isinstance(), because we cannot guarantee that the relevant classes are imported or available. """ for base_class in inspect.getmro(model_class): module = base_class.__module__ name = base_class.__name__ if module.startswith("tensorflow") or module.startswith("keras") or name == "TFPreTrainedModel": return "tf" elif module.startswith("torch") or name == "PreTrainedModel": return "pt" elif module.startswith("flax") or module.startswith("jax") or name == "FlaxPreTrainedModel": return "flax" else: raise TypeError(f"Could not infer framework from class {model_class}.") def torch_int(x): """ Casts an input to a torch int64 tensor if we are in a tracing context, otherwise to a Python int. """ if not is_torch_available(): return int(x) import torch return x.to(torch.int64) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x) def torch_float(x): """ Casts an input to a torch float32 tensor if we are in a tracing context, otherwise to a Python float. """ if not is_torch_available(): return int(x) import torch return x.to(torch.float32) if torch.jit.is_tracing() and isinstance(x, torch.Tensor) else int(x) def filter_out_non_signature_kwargs(extra: Optional[list] = None): """ Decorator to filter out named arguments that are not in the function signature. This decorator ensures that only the keyword arguments that match the function's signature, or are specified in the `extra` list, are passed to the function. Any additional keyword arguments are filtered out and a warning is issued. Parameters: extra (`Optional[list]`, *optional*): A list of extra keyword argument names that are allowed even if they are not in the function's signature. Returns: Callable: A decorator that wraps the function and filters out invalid keyword arguments. Example usage: ```python @filter_out_non_signature_kwargs(extra=["allowed_extra_arg"]) def my_function(arg1, arg2, **kwargs): print(arg1, arg2, kwargs) my_function(arg1=1, arg2=2, allowed_extra_arg=3, invalid_arg=4) # This will print: 1 2 {"allowed_extra_arg": 3} # And issue a warning: "The following named arguments are not valid for `my_function` and were ignored: 'invalid_arg'" ``` """ extra = extra or [] extra_params_to_pass = set(extra) def decorator(func): sig = inspect.signature(func) function_named_args = set(sig.parameters.keys()) valid_kwargs_to_pass = function_named_args.union(extra_params_to_pass) # Required for better warning message is_instance_method = "self" in function_named_args is_class_method = "cls" in function_named_args # Mark function as decorated func._filter_out_non_signature_kwargs = True @wraps(func) def wrapper(*args, **kwargs): valid_kwargs = {} invalid_kwargs = {} for k, v in kwargs.items(): if k in valid_kwargs_to_pass: valid_kwargs[k] = v else: invalid_kwargs[k] = v if invalid_kwargs: invalid_kwargs_names = [f"'{k}'" for k in invalid_kwargs] invalid_kwargs_names = ", ".join(invalid_kwargs_names) # Get the class name for better warning message if is_instance_method: cls_prefix = args[0].__class__.__name__ + "." elif is_class_method: cls_prefix = args[0].__name__ + "." else: cls_prefix = "" warnings.warn( f"The following named arguments are not valid for `{cls_prefix}{func.__name__}`" f" and were ignored: {invalid_kwargs_names}", UserWarning, stacklevel=2, ) return func(*args, **valid_kwargs) return wrapper return decorator class TransformersKwargs(TypedDict, total=False): """ Keyword arguments to be passed to the loss function Attributes: num_items_in_batch (`Optional[torch.Tensor]`, *optional*): Number of items in the batch. It is recommended to pass it when you are doing gradient accumulation. output_hidden_states (`Optional[bool]`, *optional*): Most of the models support outputing all hidden states computed during the forward pass. output_attentions (`Optional[bool]`, *optional*): Turn this on to return the intermediary attention scores. output_router_logits (`Optional[bool]`, *optional*): For MoE models, this allows returning the router logits to compute the loss. cumulative_seqlens_q (`torch.LongTensor`, *optional*) Gets cumulative sequence length for query state. cumulative_seqlens_k (`torch.LongTensor`, *optional*) Gets cumulative sequence length for key state. max_length_q (`int`, *optional*): Maximum sequence length for query state. max_length_k (`int`, *optional*): Maximum sequence length for key state. """ num_items_in_batch: Optional["torch.Tensor"] output_hidden_states: Optional[bool] output_attentions: Optional[bool] output_router_logits: Optional[bool] cumulative_seqlens_q: Optional["torch.LongTensor"] cumulative_seqlens_k: Optional["torch.LongTensor"] max_length_q: Optional[int] max_length_k: Optional[int] def is_timm_config_dict(config_dict: dict[str, Any]) -> bool: """Checks whether a config dict is a timm config dict.""" return "pretrained_cfg" in config_dict def is_timm_local_checkpoint(pretrained_model_path: str) -> bool: """ Checks whether a checkpoint is a timm model checkpoint. """ if pretrained_model_path is None: return False # in case it's Path, not str pretrained_model_path = str(pretrained_model_path) is_file = os.path.isfile(pretrained_model_path) is_dir = os.path.isdir(pretrained_model_path) # pretrained_model_path is a file if is_file and pretrained_model_path.endswith(".json"): with open(pretrained_model_path) as f: config_dict = json.load(f) return is_timm_config_dict(config_dict) # pretrained_model_path is a directory with a config.json if is_dir and os.path.exists(os.path.join(pretrained_model_path, "config.json")): with open(os.path.join(pretrained_model_path, "config.json")) as f: config_dict = json.load(f) return is_timm_config_dict(config_dict) return False def set_attribute_for_modules(module: "torch.nn.Module", key: str, value: Any): """ Set a value to a module and all submodules. """ setattr(module, key, value) for submodule in module.children(): set_attribute_for_modules(submodule, key, value) def del_attribute_from_modules(module: "torch.nn.Module", key: str): """ Delete a value from a module and all submodules. """ # because we might remove it previously in case it's a shared module, e.g. activation function if hasattr(module, key): delattr(module, key) for submodule in module.children(): del_attribute_from_modules(submodule, key) def can_return_tuple(func): """ Decorator to wrap model method, to call output.to_tuple() if return_dict=False passed as a kwarg or use_return_dict=False is set in the config. Note: output.to_tuple() convert output to tuple skipping all `None` values. """ @wraps(func) def wrapper(self, *args, **kwargs): return_dict = self.config.return_dict if hasattr(self, "config") else True return_dict_passed = kwargs.pop("return_dict", return_dict) if return_dict_passed is not None: return_dict = return_dict_passed output = func(self, *args, **kwargs) if not return_dict and not isinstance(output, tuple): output = output.to_tuple() return output return wrapper # if is_torch_available(): # @torch._dynamo.disable @dataclass @requires(backends=("torch",)) class OutputRecorder: """ Configuration for recording outputs from a model via hooks. Attributes: target_class (Type): The class (e.g., nn.Module) to which the hook will be attached. index (Optional[int]): If the output is a tuple/list, optionally record only at a specific index. layer_name (Optional[str]): Name of the submodule to target (if needed), e.g., "transformer.layer.3.attn". class_name (Optional[str]): Name of the class to which the hook will be attached. Could be the suffix of class name in some cases. """ target_class: "type[torch.nn.Module]" index: Optional[int] = 0 layer_name: Optional[str] = None class_name: Optional[str] = None def check_model_inputs(func): """ Decorator to intercept specific layer outputs without using hooks. Compatible with torch.compile (Dynamo tracing). """ @wraps(func) def wrapper(self, *args, **kwargs): use_cache = kwargs.get("use_cache") if use_cache is None: use_cache = getattr(self.config, "use_cache", False) return_dict = kwargs.pop("return_dict", None) if return_dict is None: return_dict = getattr(self.config, "return_dict", True) if getattr(self, "gradient_checkpointing", False) and self.training and use_cache: logger.warning_once( "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`." ) use_cache = False kwargs["use_cache"] = use_cache all_args = kwargs.copy() if "kwargs" in all_args: for k, v in all_args["kwargs"].items(): all_args[k] = v capture_flags = _CAN_RECORD_REGISTRY.get(str(self.__class__), {}) # there is a weak ref for executorch recordable_keys = { f"output_{k}": all_args.get( f"output_{k}", getattr( self.config, f"output_{k}", all_args.get("output_attentions", getattr(self.config, "output_attentions", False)), ), ) for k in capture_flags } collected_outputs = defaultdict(tuple) monkey_patched_layers = [] def make_capture_wrapper(module, orig_forward, key, index): @wraps(orig_forward) def wrapped_forward(*args, **kwargs): if key == "hidden_states" and len(collected_outputs[key]) == 0: collected_outputs[key] += (args[0],) if kwargs.get("debug_io", False): with model_addition_debugger_context( module, kwargs.get("debug_io_dir", "~/model_debug"), kwargs.get("prune_layers") ): output = orig_forward(*args, **kwargs) else: output = orig_forward(*args, **kwargs) if not isinstance(output, tuple): collected_outputs[key] += (output,) elif output[index] is not None: if key not in collected_outputs: collected_outputs[key] = (output[index],) else: collected_outputs[key] += (output[index],) return output return wrapped_forward if any(recordable_keys.values()): capture_tasks = [] for key, layer_specs in capture_flags.items(): if not recordable_keys.get(f"output_{key}", False): continue if not isinstance(layer_specs, list): layer_specs = [layer_specs] for specs in layer_specs: if not isinstance(specs, OutputRecorder): index = 0 if "hidden_states" in key else 1 class_name = None if not isinstance(specs, str) else specs target_class = specs if not isinstance(specs, str) else None specs = OutputRecorder(target_class=target_class, index=index, class_name=class_name) capture_tasks.append((key, specs)) for name, module in self.named_modules(): for key, specs in capture_tasks: # The second check is for multimodals where only backbone layer suffix is available if (specs.target_class is not None and isinstance(module, specs.target_class)) or ( specs.class_name is not None and name.endswith(specs.class_name) ): if specs.layer_name is not None and specs.layer_name not in name: continue # Monkey patch forward original_forward = module.forward module.forward = make_capture_wrapper(module, original_forward, key, specs.index) monkey_patched_layers.append((module, original_forward)) outputs = func(self, *args, **kwargs) # Restore original forward methods for module, original_forward in monkey_patched_layers: module.forward = original_forward # Inject collected outputs into model output for key in collected_outputs: if key == "hidden_states": collected_outputs[key] = collected_outputs[key][:-1] if hasattr(outputs, "vision_hidden_states"): collected_outputs[key] += (outputs.vision_hidden_states,) elif hasattr(outputs, "last_hidden_state"): collected_outputs[key] += (outputs.last_hidden_state,) outputs[key] = collected_outputs[key] elif key == "attentions": if isinstance(capture_flags[key], list) and len(capture_flags[key]) == 2: outputs[key] = collected_outputs[key][0::2] outputs["cross_" + key] = collected_outputs[key][1::2] else: outputs[key] = collected_outputs[key] else: outputs[key] = collected_outputs[key] if return_dict is False: outputs = outputs.to_tuple() return outputs return wrapper class GeneralInterface(MutableMapping): """ Dict-like object keeping track of a class-wide mapping, as well as a local one. Allows to have library-wide modifications though the class mapping, as well as local modifications in a single file with the local mapping. """ # Class instance object, so that a call to `register` can be reflected into all other files correctly, even if # a new instance is created (in order to locally override a given function) _global_mapping = {} def __init__(self): self._local_mapping = {} def __getitem__(self, key): # First check if instance has a local override if key in self._local_mapping: return self._local_mapping[key] return self._global_mapping[key] def __setitem__(self, key, value): # Allow local update of the default functions without impacting other instances self._local_mapping.update({key: value}) def __delitem__(self, key): del self._local_mapping[key] def __iter__(self): # Ensure we use all keys, with the overwritten ones on top return iter({**self._global_mapping, **self._local_mapping}) def __len__(self): return len(self._global_mapping.keys() | self._local_mapping.keys()) @classmethod def register(cls, key: str, value: Callable): cls._global_mapping.update({key: value}) def valid_keys(self) -> list[str]: return list(self.keys())
最新发布
08-08
(pmdarima_312_env) PS C:\Users\zhuxinyu> & C:/Users/zhuxinyu/AppData/Local/Programs/Python/Python312/python.exe c:/Users/zhuxinyu/Desktop/数模代码/ARIMA.py Traceback (most recent call last): File "c:\Users\zhuxinyu\Desktop\数模代码\ARIMA.py", line 6, in <module> from pmdarima import auto_arima File "C:\Users\zhuxinyu\AppData\Local\Programs\Python\Python312\Lib\site-packages\pmdarima\__init__.py", line 52, in <module> from .arima import auto_arima, ARIMA, AutoARIMA, StepwiseContext, decompose File "C:\Users\zhuxinyu\AppData\Local\Programs\Python\Python312\Lib\site-packages\pmdarima\arima\__init__.py", line 5, in <module> from .approx import * File "C:\Users\zhuxinyu\AppData\Local\Programs\Python\Python312\Lib\site-packages\pmdarima\arima\approx.py", line 9, in <module> from ..utils.array import c, check_endog File "C:\Users\zhuxinyu\AppData\Local\Programs\Python\Python312\Lib\site-packages\pmdarima\utils\__init__.py", line 5, in <module> from .array import * File "C:\Users\zhuxinyu\AppData\Local\Programs\Python\Python312\Lib\site-packages\pmdarima\utils\array.py", line 13, in <module> from ._array import C_intgrt_vec File "pmdarima\\utils\\_array.pyx", line 1, in init pmdarima.utils._array ValueError: numpy.dtype size changed, maypip install numpy==1.26.0 # 支持Py3.12的最低稳定版[^4]ade >> pip install scipy==1.11.4 # SciPy 1.11.4+ 支持Py3.12 >> pip install Cython==3.0.6rs\zhuxinyu> Requirement already satisfied: numpy==1.26.0 in c:\users\zhuxinyu\pmdarima_312_env\lib\site-packages (1.26.0) Requirement already satisfied: scipy==1.11.4 in c:\users\zhuxinyu\pmdarima_312_env\lib\site-packages (1.11.4) Requirement already satisfied: numpy<1.28.0,>=1.21.6 in c:\users\zhuxinyu\pmdarima_312_env\lib\site-packages (from scipy==1.11.4) (1.26.0) Requirement already satisfied: Cython==3.0.6 in c:\users\zhuxinyu\pmdarima_312_env\lib\site-packages (3.0.6) (pmdarima_312_env) PS C:\Users\zhuxinyu> pip install --no-binary pmdarima pmdarima Collecting pmdarima Using cached pmdarima-2.0.4.tar.gz (630 kB) Installing build dependencies ... done Getting requirements to build wheel ... done Preparing metadata (pyproject.toml) ... done Collecting joblib>=0.11 (from pmdarima) Using cached joblib-1.5.1-py3-none-any.whl.metadata (5.6 kB) Requirement already satisfied: Cython!=0.29.18,!=0.29.31,>=0.29 in c:\users\zhuxinyu\pmdarima_312_env\lib\site-packages (from pmdarima) (3.0.6) Requirement already satisfied: numpy>=1.21.2 in c:\users\zhuxinyu\pmdarima_312_env\lib\site-packages (from pmdarima) (1.26.0) Collecting pandas>=0.19 (from pmdarima) Using cached pandas-2.3.1-cp312-cp312-win_amd64.whl.metadata (19 kB) Collecting scikit-learn>=0.22 (from pmdarima) Using cached scikit_learn-1.7.1-cp312-cp312-win_amd64.whl.metadata (11 kB) Requirement already satisfied: scipy>=1.3.2 in c:\users\zhuxinyu\pmdarima_312_env\lib\site-packages (from pmdarima) (1.11.4) Collecting statsmodels>=0.13.2 (from pmdarima) Using cached statsmodels-0.14.5-cp312-cp312-win_amd64.whl.metadata (9.8 kB) Collecting urllib3 (from pmdarima) Using cached urllib3-2.5.0-py3-none-any.whl.metadata (6.5 kB) Collecting setuptools!=50.0.0,>=38.6.0 (from pmdarima) Using cached setuptools-80.9.0-py3-none-any.whl.metadata (6.6 kB) Collecting packaging>=17.1 (from pmdarima) Using cached packaging-25.0-py3-none-any.whl.metadata (3.3 kB) Collecting python-dateutil>=2.8.2 (from pandas>=0.19->pmdarima) Using cached python_dateutil-2.9.0.post0-py2.py3-none-any.whl.metadata (8.4 kB) Collecting pytz>=2020.1 (from pandas>=0.19->pmdarima) Using cached pytz-2025.2-py2.py3-none-any.whl.metadata (22 kB) Collecting tzdata>=2022.7 (from pandas>=0.19->pmdarima) Using cached tzdata-2025.2-py2.py3-none-any.whl.metadata (1.4 kB) Collecting six>=1.5 (from python-dateutil>=2.8.2->pandas>=0.19->pmdarima) Using cached six-1.17.0-py2.py3-none-any.whl.metadata (1.7 kB) Collecting threadpoolctl>=3.1.0 (from scikit-learn>=0.22->pmdarima) Using cached threadpoolctl-3.6.0-py3-none-any.whl.metadata (13 kB) Collecting patsy>=0.5.6 (from statsmodels>=0.13.2->pmdarima) Using cached patsy-1.0.1-py2.py3-none-any.whl.metadata (3.3 kB) Using cached joblib-1.5.1-py3-none-any.whl (307 kB) Using cached packaging-25.0-py3-none-any.whl (66 kB) Using cached pandas-2.3.1-cp312-cp312-win_amd64.whl (11.0 MB) Using cached python_dateutil-2.9.0.post0-py2.py3-none-any.whl (229 kB) Using cached pytz-2025.2-py2.py3-none-any.whl (509 kB) Using cached scikit_learn-1.7.1-cp312-cp312-win_amd64.whl (8.7 MB) Using cached setuptools-80.9.0-py3-none-any.whl (1.2 MB) Using cached six-1.17.0-py2.py3-none-any.whl (11 kB) Using cached statsmodels-0.14.5-cp312-cp312-win_amd64.whl (9.6 MB) Using cached patsy-1.0.1-py2.py3-none-any.whl (232 kB) Using cached threadpoolctl-3.6.0-py3-none-any.whl (18 kB) Using cached tzdata-2025.2-py2.py3-none-any.whl (347 kB) Using cached urllib3-2.5.0-py3-none-any.whl (129 kB) Building wheels for collected packages: pmdarima Building wheel for pmdarima (pyproject.toml) ... error error: subprocess-exited-with-error × Building wheel for pmdarima (pyproject.toml) did not run successfully. │ exit code: 1 ╰─> [476 lines of output] Partial import of pmdarima during the build process. C:\Users\zhuxinyu\AppData\Local\Temp\pip-build-env-ki1mh8q_\overlay\Lib\site-packages\setuptools\_distutils\dist.py:289: UserWarning: Unknown distribution option: 'configuration' warnings.warn(msg) C:\Users\zhuxinyu\AppData\Local\Temp\pip-build-env-ki1mh8q_\overlay\Lib\site-packages\setuptools\dist.py:599: SetuptoolsDeprecationWarning: Invalid dash-separated key 'description-file' in 'metadata' (setup.cfg), please use the underscore name 'description_file' instead. !! ******************************************************************************** Usage of dash-separated 'description-file' will not be supported in future versions. Please use the underscore name 'description_file' instead. (Affected: pmdarima). By 2026-Mar-03, you need to update your project and remove deprecated calls or your builds will no longer be supported. See https://setuptools.pypa.io/en/latest/userguide/declarative_config.html for details. ******************************************************************************** !! opt = self._enforce_underscore(opt, section) Requirements: ['joblib>=0.11\nCython>=0.29,!=0.29.18,!=0.29.31\nnumpy>=1.21.2\npandas>=0.19\nscikit-learn>=0.22\nscipy>=1.3.2\nstatsmodels>=0.13.2\nurllib3\nsetuptools>=38.6.0,!=50.0.0\npackaging>=17.1 # Bundled with setuptools, but want to be explicit\n'] Adding extra setuptools args Setting up with setuptools running bdist_wheel running build running build_py creating build\lib.win-amd64-cpython-312\pmdarima copying pmdarima\base.py -> build\lib.win-amd64-cpython-312\pmdarima copying pmdarima\context_managers.py -> build\lib.win-amd64-cpython-312\pmdarima copying pmdarima\decorators.py -> build\lib.win-amd64-cpython-312\pmdarima copying pmdarima\metrics.py -> build\lib.win-amd64-cpython-312\pmdarima copying pmdarima\pipeline.py -> build\lib.win-amd64-cpython-312\pmdarima copying pmdarima\setup.py -> build\lib.win-amd64-cpython-312\pmdarima copying pmdarima\warnings.py -> build\lib.win-amd64-cpython-312\pmdarima copying pmdarima\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima creating build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\approx.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\arima.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\auto.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\seasonality.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\setup.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\stationarity.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\utils.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\_auto_solvers.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\_context.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\_doc.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\_validation.py -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\arima\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\arima creating build\lib.win-amd64-cpython-312\pmdarima\compat copying pmdarima\compat\matplotlib.py -> build\lib.win-amd64-cpython-312\pmdarima\compat copying pmdarima\compat\numpy.py -> build\lib.win-amd64-cpython-312\pmdarima\compat copying pmdarima\compat\pandas.py -> build\lib.win-amd64-cpython-312\pmdarima\compat copying pmdarima\compat\pytest.py -> build\lib.win-amd64-cpython-312\pmdarima\compat copying pmdarima\compat\sklearn.py -> build\lib.win-amd64-cpython-312\pmdarima\compat copying pmdarima\compat\statsmodels.py -> build\lib.win-amd64-cpython-312\pmdarima\compat copying pmdarima\compat\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\compat creating build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\airpassengers.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\ausbeer.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\austres.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\gasoline.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\heartrate.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\lynx.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\setup.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\stocks.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\sunspots.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\taylor.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\wineind.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\woolyrnq.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\_base.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets copying pmdarima\datasets\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets creating build\lib.win-amd64-cpython-312\pmdarima\model_selection copying pmdarima\model_selection\_split.py -> build\lib.win-amd64-cpython-312\pmdarima\model_selection copying pmdarima\model_selection\_validation.py -> build\lib.win-amd64-cpython-312\pmdarima\model_selection copying pmdarima\model_selection\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\model_selection creating build\lib.win-amd64-cpython-312\pmdarima\preprocessing copying pmdarima\preprocessing\base.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing copying pmdarima\preprocessing\setup.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing copying pmdarima\preprocessing\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing creating build\lib.win-amd64-cpython-312\pmdarima\tests copying pmdarima\tests\test_context_managers.py -> build\lib.win-amd64-cpython-312\pmdarima\tests copying pmdarima\tests\test_estimators.py -> build\lib.win-amd64-cpython-312\pmdarima\tests copying pmdarima\tests\test_metrics.py -> build\lib.win-amd64-cpython-312\pmdarima\tests copying pmdarima\tests\test_pipeline.py -> build\lib.win-amd64-cpython-312\pmdarima\tests copying pmdarima\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\tests creating build\lib.win-amd64-cpython-312\pmdarima\utils copying pmdarima\utils\array.py -> build\lib.win-amd64-cpython-312\pmdarima\utils copying pmdarima\utils\metaestimators.py -> build\lib.win-amd64-cpython-312\pmdarima\utils copying pmdarima\utils\setup.py -> build\lib.win-amd64-cpython-312\pmdarima\utils copying pmdarima\utils\visualization.py -> build\lib.win-amd64-cpython-312\pmdarima\utils copying pmdarima\utils\wrapped.py -> build\lib.win-amd64-cpython-312\pmdarima\utils copying pmdarima\utils\_show_versions.py -> build\lib.win-amd64-cpython-312\pmdarima\utils copying pmdarima\utils\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\utils creating build\lib.win-amd64-cpython-312\pmdarima\_build_utils copying pmdarima\_build_utils\pre_build_helpers.py -> build\lib.win-amd64-cpython-312\pmdarima\_build_utils copying pmdarima\_build_utils\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\_build_utils creating build\lib.win-amd64-cpython-312\pmdarima\__check_build copying pmdarima\__check_build\setup.py -> build\lib.win-amd64-cpython-312\pmdarima\__check_build copying pmdarima\__check_build\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\__check_build creating build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_approx.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_arima.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_arima_diagnostics.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_auto.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_auto_solvers.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_context.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_c_arima.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_seasonality.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_stationarity.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_utils.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\test_validation.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests copying pmdarima\arima\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests creating build\lib.win-amd64-cpython-312\pmdarima\compat\tests copying pmdarima\compat\tests\test_sklearn.py -> build\lib.win-amd64-cpython-312\pmdarima\compat\tests copying pmdarima\compat\tests\test_statsmodels.py -> build\lib.win-amd64-cpython-312\pmdarima\compat\tests copying pmdarima\compat\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\compat\tests creating build\lib.win-amd64-cpython-312\pmdarima\datasets\tests copying pmdarima\datasets\tests\test_load_datasets.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets\tests copying pmdarima\datasets\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\datasets\tests creating build\lib.win-amd64-cpython-312\pmdarima\model_selection\tests copying pmdarima\model_selection\tests\test_split.py -> build\lib.win-amd64-cpython-312\pmdarima\model_selection\tests copying pmdarima\model_selection\tests\test_validation.py -> build\lib.win-amd64-cpython-312\pmdarima\model_selection\tests copying pmdarima\model_selection\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\model_selection\tests creating build\lib.win-amd64-cpython-312\pmdarima\preprocessing\endog copying pmdarima\preprocessing\endog\base.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\endog copying pmdarima\preprocessing\endog\boxcox.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\endog copying pmdarima\preprocessing\endog\log.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\endog copying pmdarima\preprocessing\endog\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\endog creating build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog copying pmdarima\preprocessing\exog\base.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog copying pmdarima\preprocessing\exog\dates.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog copying pmdarima\preprocessing\exog\fourier.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog copying pmdarima\preprocessing\exog\setup.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog copying pmdarima\preprocessing\exog\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog creating build\lib.win-amd64-cpython-312\pmdarima\preprocessing\tests copying pmdarima\preprocessing\tests\test_base.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\tests copying pmdarima\preprocessing\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\tests creating build\lib.win-amd64-cpython-312\pmdarima\preprocessing\endog\tests copying pmdarima\preprocessing\endog\tests\test_base.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\endog\tests copying pmdarima\preprocessing\endog\tests\test_boxcox.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\endog\tests copying pmdarima\preprocessing\endog\tests\test_log.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\endog\tests copying pmdarima\preprocessing\endog\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\endog\tests creating build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog\tests copying pmdarima\preprocessing\exog\tests\test_base.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog\tests copying pmdarima\preprocessing\exog\tests\test_dates.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog\tests copying pmdarima\preprocessing\exog\tests\test_fourier.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog\tests copying pmdarima\preprocessing\exog\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog\tests creating build\lib.win-amd64-cpython-312\pmdarima\utils\tests copying pmdarima\utils\tests\test_array.py -> build\lib.win-amd64-cpython-312\pmdarima\utils\tests copying pmdarima\utils\tests\test_meta.py -> build\lib.win-amd64-cpython-312\pmdarima\utils\tests copying pmdarima\utils\tests\test_show_versions.py -> build\lib.win-amd64-cpython-312\pmdarima\utils\tests copying pmdarima\utils\tests\test_vis.py -> build\lib.win-amd64-cpython-312\pmdarima\utils\tests copying pmdarima\utils\tests\test_wrapped.py -> build\lib.win-amd64-cpython-312\pmdarima\utils\tests copying pmdarima\utils\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\utils\tests creating build\lib.win-amd64-cpython-312\pmdarima\_build_utils\tests copying pmdarima\_build_utils\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\_build_utils\tests creating build\lib.win-amd64-cpython-312\pmdarima\__check_build\tests copying pmdarima\__check_build\tests\test_check_build.py -> build\lib.win-amd64-cpython-312\pmdarima\__check_build\tests copying pmdarima\__check_build\tests\__init__.py -> build\lib.win-amd64-cpython-312\pmdarima\__check_build\tests running egg_info writing pmdarima.egg-info\PKG-INFO writing dependency_links to pmdarima.egg-info\dependency_links.txt writing requirements to pmdarima.egg-info\requires.txt writing top-level names to pmdarima.egg-info\top_level.txt reading manifest file 'pmdarima.egg-info\SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no previously-included files matching '__pycache__' found anywhere in distribution adding license file 'LICENSE' writing manifest file 'pmdarima.egg-info\SOURCES.txt' C:\Users\zhuxinyu\AppData\Local\Temp\pip-build-env-ki1mh8q_\overlay\Lib\site-packages\setuptools\command\build_py.py:212: _Warning: Package 'pmdarima.__check_build' is absent from the `packages` configuration. !! ******************************************************************************** ############################ # Package would be ignored # ############################ Python recognizes 'pmdarima.__check_build' as an importable package[^1], but it is absent from setuptools' `packages` configuration. This leads to an ambiguous overall configuration. If you want to distribute this package, please make sure that 'pmdarima.__check_build' is explicitly added to the `packages` configuration field. Alternatively, you can also rely on setuptools' discovery methods (for example by using `find_namespace_packages(...)`/`find_namespace:` instead of `find_packages(...)`/`find:`). You can read more about "package discovery" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html If you don't want 'pmdarima.__check_build' to be distributed and are already explicitly excluding 'pmdarima.__check_build' via `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`, you can try to use `exclude_package_data`, or `include-package-data=False` in combination with a more fine grained `package-data` configuration. You can read more about "package data files" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/datafiles.html [^1]: For Python, any directory (with suitable naming) can be imported, even if it does not contain any `.py` files. On the other hand, currently there is no concept of package data directory, all directories are treated like packages. ******************************************************************************** !! check.warn(importable) C:\Users\zhuxinyu\AppData\Local\Temp\pip-build-env-ki1mh8q_\overlay\Lib\site-packages\setuptools\command\build_py.py:212: _Warning: Package 'pmdarima.arima' is absent from the `packages` configuration. !! ******************************************************************************** ############################ # Package would be ignored # ############################ Python recognizes 'pmdarima.arima' as an importable package[^1], but it is absent from setuptools' `packages` configuration. This leads to an ambiguous overall configuration. If you want to distribute this package, please make sure that 'pmdarima.arima' is explicitly added to the `packages` configuration field. Alternatively, you can also rely on setuptools' discovery methods (for example by using `find_namespace_packages(...)`/`find_namespace:` instead of `find_packages(...)`/`find:`). You can read more about "package discovery" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html If you don't want 'pmdarima.arima' to be distributed and are already explicitly excluding 'pmdarima.arima' via `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`, you can try to use `exclude_package_data`, or `include-package-data=False` in combination with a more fine grained `package-data` configuration. You can read more about "package data files" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/datafiles.html [^1]: For Python, any directory (with suitable naming) can be imported, even if it does not contain any `.py` files. On the other hand, currently there is no concept of package data directory, all directories are treated like packages. ******************************************************************************** !! check.warn(importable) C:\Users\zhuxinyu\AppData\Local\Temp\pip-build-env-ki1mh8q_\overlay\Lib\site-packages\setuptools\command\build_py.py:212: _Warning: Package 'pmdarima.preprocessing.exog' is absent from the `packages` configuration. !! ******************************************************************************** ############################ # Package would be ignored # ############################ Python recognizes 'pmdarima.preprocessing.exog' as an importable package[^1], but it is absent from setuptools' `packages` configuration. This leads to an ambiguous overall configuration. If you want to distribute this package, please make sure that 'pmdarima.preprocessing.exog' is explicitly added to the `packages` configuration field. Alternatively, you can also rely on setuptools' discovery methods (for example by using `find_namespace_packages(...)`/`find_namespace:` instead of `find_packages(...)`/`find:`). You can read more about "package discovery" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html If you don't want 'pmdarima.preprocessing.exog' to be distributed and are already explicitly excluding 'pmdarima.preprocessing.exog' via `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`, you can try to use `exclude_package_data`, or `include-package-data=False` in combination with a more fine grained `package-data` configuration. You can read more about "package data files" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/datafiles.html [^1]: For Python, any directory (with suitable naming) can be imported, even if it does not contain any `.py` files. On the other hand, currently there is no concept of package data directory, all directories are treated like packages. ******************************************************************************** !! check.warn(importable) C:\Users\zhuxinyu\AppData\Local\Temp\pip-build-env-ki1mh8q_\overlay\Lib\site-packages\setuptools\command\build_py.py:212: _Warning: Package 'pmdarima.utils' is absent from the `packages` configuration. !! ******************************************************************************** ############################ # Package would be ignored # ############################ Python recognizes 'pmdarima.utils' as an importable package[^1], but it is absent from setuptools' `packages` configuration. This leads to an ambiguous overall configuration. If you want to distribute this package, please make sure that 'pmdarima.utils' is explicitly added to the `packages` configuration field. Alternatively, you can also rely on setuptools' discovery methods (for example by using `find_namespace_packages(...)`/`find_namespace:` instead of `find_packages(...)`/`find:`). You can read more about "package discovery" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html If you don't want 'pmdarima.utils' to be distributed and are already explicitly excluding 'pmdarima.utils' via `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`, you can try to use `exclude_package_data`, or `include-package-data=False` in combination with a more fine grained `package-data` configuration. You can read more about "package data files" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/datafiles.html [^1]: For Python, any directory (with suitable naming) can be imported, even if it does not contain any `.py` files. On the other hand, currently there is no concept of package data directory, all directories are treated like packages. ******************************************************************************** !! check.warn(importable) C:\Users\zhuxinyu\AppData\Local\Temp\pip-build-env-ki1mh8q_\overlay\Lib\site-packages\setuptools\command\build_py.py:212: _Warning: Package 'pmdarima.__pycache__' is absent from the `packages` configuration. !! ******************************************************************************** ############################ # Package would be ignored # ############################ Python recognizes 'pmdarima.__pycache__' as an importable package[^1], but it is absent from setuptools' `packages` configuration. This leads to an ambiguous overall configuration. If you want to distribute this package, please make sure that 'pmdarima.__pycache__' is explicitly added to the `packages` configuration field. Alternatively, you can also rely on setuptools' discovery methods (for example by using `find_namespace_packages(...)`/`find_namespace:` instead of `find_packages(...)`/`find:`). You can read more about "package discovery" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html If you don't want 'pmdarima.__pycache__' to be distributed and are already explicitly excluding 'pmdarima.__pycache__' via `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`, you can try to use `exclude_package_data`, or `include-package-data=False` in combination with a more fine grained `package-data` configuration. You can read more about "package data files" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/datafiles.html [^1]: For Python, any directory (with suitable naming) can be imported, even if it does not contain any `.py` files. On the other hand, currently there is no concept of package data directory, all directories are treated like packages. ******************************************************************************** !! check.warn(importable) C:\Users\zhuxinyu\AppData\Local\Temp\pip-build-env-ki1mh8q_\overlay\Lib\site-packages\setuptools\command\build_py.py:212: _Warning: Package 'pmdarima.arima.tests.data' is absent from the `packages` configuration. !! ******************************************************************************** ############################ # Package would be ignored # ############################ Python recognizes 'pmdarima.arima.tests.data' as an importable package[^1], but it is absent from setuptools' `packages` configuration. This leads to an ambiguous overall configuration. If you want to distribute this package, please make sure that 'pmdarima.arima.tests.data' is explicitly added to the `packages` configuration field. Alternatively, you can also rely on setuptools' discovery methods (for example by using `find_namespace_packages(...)`/`find_namespace:` instead of `find_packages(...)`/`find:`). You can read more about "package discovery" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html If you don't want 'pmdarima.arima.tests.data' to be distributed and are already explicitly excluding 'pmdarima.arima.tests.data' via `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`, you can try to use `exclude_package_data`, or `include-package-data=False` in combination with a more fine grained `package-data` configuration. You can read more about "package data files" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/datafiles.html [^1]: For Python, any directory (with suitable naming) can be imported, even if it does not contain any `.py` files. On the other hand, currently there is no concept of package data directory, all directories are treated like packages. ******************************************************************************** !! check.warn(importable) C:\Users\zhuxinyu\AppData\Local\Temp\pip-build-env-ki1mh8q_\overlay\Lib\site-packages\setuptools\command\build_py.py:212: _Warning: Package 'pmdarima.datasets.data' is absent from the `packages` configuration. !! ******************************************************************************** ############################ # Package would be ignored # ############################ Python recognizes 'pmdarima.datasets.data' as an importable package[^1], but it is absent from setuptools' `packages` configuration. This leads to an ambiguous overall configuration. If you want to distribute this package, please make sure that 'pmdarima.datasets.data' is explicitly added to the `packages` configuration field. Alternatively, you can also rely on setuptools' discovery methods (for example by using `find_namespace_packages(...)`/`find_namespace:` instead of `find_packages(...)`/`find:`). You can read more about "package discovery" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/package_discovery.html If you don't want 'pmdarima.datasets.data' to be distributed and are already explicitly excluding 'pmdarima.datasets.data' via `find_namespace_packages(...)/find_namespace` or `find_packages(...)/find`, you can try to use `exclude_package_data`, or `include-package-data=False` in combination with a more fine grained `package-data` configuration. You can read more about "package data files" on setuptools documentation page: - https://setuptools.pypa.io/en/latest/userguide/datafiles.html [^1]: For Python, any directory (with suitable naming) can be imported, even if it does not contain any `.py` files. On the other hand, currently there is no concept of package data directory, all directories are treated like packages. ******************************************************************************** !! check.warn(importable) copying pmdarima\VERSION -> build\lib.win-amd64-cpython-312\pmdarima copying pmdarima\__check_build\_check_build.pyx -> build\lib.win-amd64-cpython-312\pmdarima\__check_build copying pmdarima\arima\_arima.pyx -> build\lib.win-amd64-cpython-312\pmdarima\arima copying pmdarima\preprocessing\exog\_fourier.pyx -> build\lib.win-amd64-cpython-312\pmdarima\preprocessing\exog copying pmdarima\utils\_array.pyx -> build\lib.win-amd64-cpython-312\pmdarima\utils creating build\lib.win-amd64-cpython-312\pmdarima\__pycache__ copying pmdarima\__pycache__\__init__.cpython-312.pyc -> build\lib.win-amd64-cpython-312\pmdarima\__pycache__ copying pmdarima\__pycache__\__init__.cpython-37.pyc -> build\lib.win-amd64-cpython-312\pmdarima\__pycache__ copying pmdarima\arima\_arima_fast_helpers.h -> build\lib.win-amd64-cpython-312\pmdarima\arima creating build\lib.win-amd64-cpython-312\pmdarima\datasets\data copying pmdarima\datasets\data\dated.tar.gz -> build\lib.win-amd64-cpython-312\pmdarima\datasets\data copying pmdarima\datasets\data\msft.tar.gz -> build\lib.win-amd64-cpython-312\pmdarima\datasets\data copying pmdarima\datasets\data\sunspots.txt.gz -> build\lib.win-amd64-cpython-312\pmdarima\datasets\data creating build\lib.win-amd64-cpython-312\pmdarima\arima\tests\data copying pmdarima\arima\tests\data\issue_191.csv -> build\lib.win-amd64-cpython-312\pmdarima\arima\tests\data running build_ext Compiling pmdarima/arima/_arima.pyx because it changed. [1/1] Cythonizing pmdarima/arima/_arima.pyx building 'pmdarima.arima._arima' extension error: Microsoft Visual C++ 14.0 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. ERROR: Failed building wheel for pmdarima Failed to build pmdarima error: failed-wheel-build-for-install × Failed to build installable wheels for some pyproject.toml based projects ╰─> pmdarima
08-04
36085 WARNING: lib not found: c10.dll dependency of D:\python\lib\site-packages\torchvision\_C.pyd 36099 WARNING: lib not found: torch_cpu.dll dependency of D:\python\lib\site-packages\torchvision\_C.pyd 36113 WARNING: lib not found: c10_cuda.dll dependency of D:\python\lib\site-packages\torchvision\_C.pyd 36127 WARNING: lib not found: torch_cuda_cpp.dll dependency of D:\python\lib\site-packages\torchvision\_C.pyd 36146 WARNING: lib not found: torch_python.dll dependency of D:\python\lib\site-packages\torch\_C_flatbuffer.cp37-win_amd64.pyd 36287 WARNING: lib not found: torch_python.dll dependency of D:\python\lib\site-packages\torch\_C.cp37-win_amd64.pyd 37214 WARNING: lib not found: api-ms-win-security-systemfunctions-l1-1-0.dll dependency of D:\python\lib\site-packages\torchvision\cudart64_110.dll 326321 INFO: Looking for eggs 326578 INFO: Using Python library D:\python\python37.dll 326578 INFO: Found binding redirects: [] 326631 INFO: Warnings written to D:\python-zuoye\pythonProject_001\build\main\warn-main.txt 327409 INFO: Graph cross-reference written to D:\python-zuoye\pythonProject_001\build\main\xref-main.html 327899 INFO: checking PYZ 327900 INFO: Building PYZ because PYZ-00.toc is non existent 327901 INFO: Building PYZ (ZlibArchive) D:\python-zuoye\pythonProject_001\build\main\PYZ-00.pyz 334452 INFO: Building PYZ (ZlibArchive) D:\python-zuoye\pythonProject_001\build\main\PYZ-00.pyz completed successfully. 334974 INFO: checking PKG 334974 INFO: Building PKG because PKG-00.toc is non existent 334975 INFO: Building PKG (CArchive) main.pkg
06-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

von Neumann

您的赞赏是我创作最大的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值