在 Julia 中定义冲突模块

Defining Conflicting Modules in Julia

我是 Julia 的新手(使用 MATLAB)。我正在获取一些数据集,清理它并使用 ScikitLearn 中提供的工具对分类变量进行编码,然后 运行 干净数据的 XGBoost。

但是,我无法使用经过训练的 XGBoost 模型进行预测,因为 ScitkitLearn 和 XGBoost 都有一个名为 predict 的函数。参考下面的错误信息:

WARNING: both ScikitLearn and XGBoost export "predict"; uses of it in module Main must be qualified ERROR: LoadError: UndefVarError: predict not defined

问题是我无法将 XGBoost 的 predict 函数定义为 XGBoost.predict,因为这不起作用,而且它似乎是我所知道的唯一解决方案。

此外,我无法找到或理解如何在不加载预测函数的情况下仅从 ScikitLearn 加载特定模块。例如,格式 import MLDataUtils.splitobs 适用于大多数软件包,但 ScikitLearn.preprocessing 无效。

这是您问题的 MWE(两个模块 export 同名):

module A
    export f
    f() = println("f from A")
end
module B
    export f
    f() = println("f from B")
end

现在,考虑一下您 using 同时 AB 的情况,并尝试调用 f:

julia> using .A, .B

julia> f()
WARNING: both B and A export "f"; uses of it in module Main must be qualified
ERROR: UndefVarError: f not defined

失败的原因是 Julia 不明白 f 的意思;是 A.f 还是 B.f?您可以通过明确消除对 f:

的任何调用的歧义来解决此问题
julia> using .A, .B

julia> A.f()
f from A

julia> B.f()
f from B

如果您希望能够仅通过名称 (f) 调用其中一个函数,那么您(用户)必须选择 f 应指向的内容。您可以通过将其显式定义为导入语句的一部分来执行此操作:

julia> using .A, .B

julia> using .B: f # explicitly choosing f to be B.f

julia> f() # no error
f from B

julia> A.f()
f from A

julia> B.f()
f from B

另一种选择是在您的命名空间中明确定义您自己的名称f

julia> using .A, .B

julia> const f = B.f # defining a new name in this namespace pointing to B.f
f (generic function with 1 method)

julia> f() # no error
f from B

julia> A.f()
f from A

julia> B.f()
f from B