成功解决报错:cell2location导入报错 cannot import name ‘parse_use_gpu_arg

from scvi.model._utils import parse_use_gpu_arg ImportError: cannot import name 'parse_use_gpu_arg' from 'scvi.model._utils'

Cell2location采用贝叶斯层次框架。首先使用外部单细胞RNA测序数据作为参考数据,估计细胞类型特异性基因表达特征。然后,通过负二项分布(negative binomial regression)对观察到的空间表达计数矩阵建模,其中均值参数取决于参考细胞类型的特征,过度分散参数使用指数-伽马复合先验建模,旨在使大多数基因具有低过度分散。基因特异性技术灵敏度和基因-位置特异性的加性偏移被包括在均值参数的一部分,每个都使用单独的层次伽马先验进行建模。Cell2location进一步使用层次伽马先验对细胞类型特征的回归权重进行建模,并将回归权重分解为多个潜在组的贡献,这可以解释为具有共享细胞类型丰度特征的斑点,旨在跨具有相似细胞组成的位置借用强度。最后,cell2location采用变分贝叶斯推断来近似后验分布,并相应地生成参数估计。总的来说,Cell2location提供了一种可靠的途径来处理模型中的不确定因素,可以解释细胞类型丰度的线性依存关系。相比于其他的联合分析工具,Cell2location体现了更高的运算效率。

报错

(cell2loc) C:\Users\Administrator>python Python 3.9.19 (main, May 6 2024, 20:12:36) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information.

import cell2location Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\ProgramData\Anaconda3\envs\cell2loc\lib\site-packages\cell2location_init_.py", line 9, in <module> from . import models File "D:\ProgramData\Anaconda3\envs\cell2loc\lib\site-packages\cell2location\models_init_.py", line 1, in <module> from ._cell2location_model import Cell2location File "D:\ProgramData\Anaconda3\envs\cell2loc\lib\site-packages\cell2location\models_cell2location_model.py", line 29, in <module> from cell2location.models.base._pyro_base_loc_module import Cell2locationBaseModule File "D:\ProgramData\Anaconda3\envs\cell2loc\lib\site-packages\cell2location\models\base_pyro_base_loc_module.py", line 6, in <module> from ._pyro_mixin import AutoGuideMixinModule, init_to_value File "D:\ProgramData\Anaconda3\envs\cell2loc\lib\site-packages\cell2location\models\base_pyro_mixin.py", line 20, in <module> from scvi.model._utils import parse_use_gpu_arg ImportError: cannot import name 'parse_use_gpu_arg' from 'scvi.model._utils' (D:\ProgramData\Anaconda3\envs\cell2loc\lib\site-packages\scvi\model_utils.py)

安装cell2location
mamba remove -n cell2loc_env --all
export PYTHONNOUSERSITE="literallyanyletters"
mamba create -y -n cell2loc_env python=3.9
mamba activate cell2loc_env
pip3 install cell2location

无奈之下 找到scvi-tools github网站https://github.com/scverse/scvi-tools/blob/1.0.4/scvi/model/_utils.py,从上一个版本的scvi-tools 1.0.4中找到parse_use_gpu_arg

函数并增加到中D:/ProgramData/Anaconda3/envs/cell2loc/Lib/site-packages/scvi\model/_utils.py文件中,

即可成功import cell2location包

添加的函数是:

def parse_use_gpu_arg(
    use_gpu: Optional[Union[str, int, bool]] = None,
    return_device=True,
):
    """Parses the use_gpu arg in codebase.

    Returned gpus are is compatible with PytorchLightning's gpus arg.
    If return_device is True, will also return the device.

    Parameters
    ----------
    use_gpu
        Use default GPU if available (if None or True), or index of GPU to use (if int),
        or name of GPU (if str, e.g., `'cuda:0'`), or use CPU (if False).
    return_device
        If True, will return the torch.device of use_gpu.

    Returns
    -------
    Arguments for lightning trainer, including the accelerator (str), devices
    (int or sequence of int), and optionally the torch device.
    """
    # Support Apple silicon
    cuda_available = torch.cuda.is_available()
    # If using an older version of torch.
    try:
        mps_available = torch.backends.mps.is_available()
    except AttributeError:
        mps_available = False
    gpu_available = cuda_available
    lightning_devices = None
    if (use_gpu is None and not gpu_available) or (use_gpu is False):
        accelerator = "cpu"
        device = torch.device("cpu")
        lightning_devices = "auto"
    elif (use_gpu is None and gpu_available) or (use_gpu is True):
        current = torch.cuda.current_device() if cuda_available else "mps"
        if current != "mps":
            lightning_devices = [current]
            accelerator = "gpu"
        else:
            accelerator = "mps"
            lightning_devices = 1
        device = torch.device(current)
    # Also captures bool case
    elif isinstance(use_gpu, int):
        device = torch.device(use_gpu) if not mps_available else torch.device("mps")
        accelerator = "gpu" if not mps_available else "mps"
        lightning_devices = [use_gpu] if not mps_available else 1
    elif isinstance(use_gpu, str):
        device = torch.device(use_gpu)
        accelerator = "gpu"
        # changes "cuda:0" to "0,"
        lightning_devices = [int(use_gpu.split(":")[-1])]
    else:
        raise ValueError("use_gpu argument not understood.")

    if return_device:
        return accelerator, lightning_devices, device
    else:
        return accelerator, lightning_devices


 

再次运行

成功解决报错

注意Cell2location运行非常慢,建议使用GPU进行加速!

二. Cell2location代码实现
Step0.环境部署

github在https://github.com/BayraktarLab/cell2location#Installation

官方教程在:https://cell2location.readthedocs.io/en/latest/

可以使用Conda安装Cell2location:

conda create -y -n cell2loc python=3.9

conda activate cell2loc
pip install cell2location[tutorials]

如果需要衔接Jupyter notebook使用的话,需要在cell2loc这个环境里安装一下几个插件,然后就能在Jupyter notebook里选择cell2loc这个环境:

mamba install -y nb_conda_kernels ipykernel
python -m ipykernel install --user --name cell2loc --display-name cell2loc
Step1.加载示例数据及预处理
import scanpy as sc
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

import cell2location

from matplotlib import rcParams
rcParams['pdf.fonttype'] = 42 # enables correct plotting of text for PDFs

 

注意:cell2location需要count原始数据作为input数据,不能用标准化后的。参考:https://github.com/BayraktarLab/cell2location/issues/249

  • 8
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
很抱歉,我之前提到的 `MarkovRegression` 在 statsmodels 包的 tsa.regime_switching 模块中并不存在。如果你希望使用状态转换模型进行非线性协整检验,可以尝试其他方法。 一个常用的非线性协整检验方法是基于门限自回归模型(Threshold Autoregressive Model, TAR)。以下是一个示例代码,用于检验中国CPI、美国CPI和美元兑人民币汇率之间的非线性协整关系: ```python import numpy as np import pandas as pd from arch.unitroot import TAR from statsmodels.tsa.api import VAR import matplotlib.pyplot as plt # 读取数据 data = pd.read_csv('data.csv', parse_dates=['Date'], index_col='Date') # 创建VAR模型 model = VAR(data) # 模型拟合 results = model.fit(maxlags=2, ic='aic') # 可根据需要调整滞后阶数和信息准则 # 提取残差序列 residuals = results.resid # 计算门限自回归模型 tar = TAR(residuals, threshold=0, lags=1) # 通过调整阈值来控制非线性程度 # 模型拟合 tar_results = tar.fit() # 门限协整检验 cointegration = tar_results.is_cointegrated if cointegration: print("存在非线性协整关系") else: print("不存在非线性协整关系") # 可视化结果 plt.plot(tar_results.resid, label='Residuals') plt.axhline(y=0, color='r', linestyle='--', label='Threshold') plt.legend() plt.show() ``` 请注意,上述代码中的"data.csv"是一个包含中国CPI、美国CPI和美元兑人民币汇率的数据文件。你需要根据自己的数据集进行适当的调整。 希望这个示例能帮助你进行非线性协整关系的检验,并可视化结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

皮肤小白生

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值