microsoftml.rx_logistic_regression:逻辑回归

使用情况

microsoftml.rx_logistic_regression(formula: str,
    data: [revoscalepy.datasource.RxDataSource.RxDataSource,
    pandas.core.frame.DataFrame], method: ['binary',
    'multiClass'] = 'binary', l2_weight: float = 1,
    l1_weight: float = 1, opt_tol: float = 1e-07,
    memory_size: int = 20, init_wts_diameter: float = 0,
    max_iterations: int = 2147483647,
    show_training_stats: bool = False, sgd_init_tol: float = 0,
    train_threads: int = None, dense_optimizer: bool = False,
    normalize: ['No', 'Warn', 'Auto', 'Yes'] = 'Auto',
    ml_transforms: list = None, ml_transform_vars: list = None,
    row_selection: str = None, transforms: dict = None,
    transform_objects: dict = None, transform_function: str = None,
    transform_variables: list = None,
    transform_packages: list = None,
    transform_environment: dict = None, blocks_per_read: int = None,
    report_progress: int = None, verbose: int = 1,
    ensemble: microsoftml.modules.ensemble.EnsembleControl = None,
    compute_context: revoscalepy.computecontext.RxComputeContext.RxComputeContext = None)

说明

机器学习逻辑回归

详细信息

逻辑回归是一种分类方法,用于根据分类因变量与具有逻辑分布的一个或多个自变量的关系来预测其值。 如果因变量仅有两个可能的值(成功/失败),则逻辑回归是二元的。 如果因变量有两个以上的可能值(血型给定诊断测试结果),则逻辑回归是多元的。

用于 rx_logistic_regression 的优化技术是有限内存 Broyden-Fletcher-Goldfarb-Shanno (L-BFGS)。 L-BFGS 和常规 BFGS 算法均使用拟牛顿法来估算方程(牛顿法使用该方程计算步长)中需要大量计算的黑塞矩阵。 但是 L-BFGS 近似法仅使用有限的内存来计算下一个步长方向,因此它特别适用于关于大量变量的问题。 memory_size 参数指定要存储以用于计算下一个步长的过去位置和梯度的数量。

该学习器可以使用弹性网络正则化:L1 (lasso) 和 L2 (ridge) 正则化的线性组合。 正则化是一种方法,可以通过施加约束来提供信息以补充数据,并通过惩罚具有极端系数值的模型来防止过度拟合,从而更容易地处理不适定问题。 这可以通过在偏差-方差权衡中选择最佳复杂度来提高学习模型的泛化能力。 正则化的工作原理是将与系数值相关联的处罚添加到假设的错误。 具有极端系数值的准确模型受到的处罚相较而言更大,而值更保守的不准确的模型受到的处罚相较而言更小。 L1 和 L2 正则化的效果和用途均不同,但在某些方面是互补的。

  • l1_weight:在处理高维数据时可应用于稀疏模型。 它使不太重要的小权重关联特征趋近于 0。

  • l2_weight:适用于不稀疏的数据。 它使大权重趋近于 0。

在正则化中加入 ridge 惩罚可以克服某些套索限制。 它可以提高其预测准确性,例如,当预测器数大于示例大小时。 如果 x = l1_weighty = l2_weight,则 ax + by = c 定义正则化术语的线性跨度。 x 和 y 的默认值均为 1。 主动正则化将重要变量排除在模型之外,可能会影响预测能力。 因此,选择正则化参数的最优值对逻辑回归模型的性能非常重要。

参数

公式

microsoftml 目前不支持 revoscalepy.rx_formula 交互术语和 F() 中描述的公式。

data

指定 .xdf 文件或数据帧对象的数据源对象或字符串。

method

指定逻辑回归类型的字符串:"binary" 用于默认二元分类逻辑回归,而 "multiClass" 用于多元逻辑回归。

l2_weight

L2 正则化权重。 其值必须大于或等于 0,并且默认值设置为 1

l1_weight

L1 正则化权重。 其值必须大于或等于 0,并且默认值设置为 1

opt_tol

优化器收敛的阈值。 如果迭代间的改进小于阈值,则算法将停止并返回当前模型。 值越小,收敛速度越慢,但准确性越高。 默认值是 1e-07

memory_size

L-BFGS 的内存大小,用于指定存储以用于计算下一个步长的过去位置和梯度的数量。 此优化参数限制用于计算下一个步长的幅度和方向的内存量。 指定的内存越少,训练越快,但准确性越低。 必须大于或等于 1,并且默认值为 20

max_iterations

设置最大迭代次数。 在此步长数之后,即使算法没有达到收敛标准,它也会停止。

show_training_stats

如果要显示训练数据和训练模型的统计信息,请指定为 True;否则指定为 False。 默认值是 False。 有关模型统计信息的其他信息,请参阅 summary.ml_model()

sgd_init_tol

如果要使用随机梯度下降 (SGD) 来查找初始参数,请设置为大于 0 的数字。 非零值集指定 SGD 用于确定收敛的容差。 默认值为 0,用于指定不使用 SGD。

init_wts_diameter

设置初始权重直径,该直径指定为初始权重采用的值范围。 这些权重在此范围内随机初始化。 例如,如果将直径指定为 d,则权重在 -d/2d/2 之间均匀分布。 默认值为 0,它指定将所有权重都初始化为 0

train_threads

用于训练模型的线程数。 该参数应设置为计算机上的内核数。 请注意,L-BFGS 多线程尝试将数据集加载到内存中。 如果出现内存不足问题,请将 train_threads 设置为 1 以关闭多线程。 如果为“None”,则要使用的线程数在内部确定。 默认值为“None”。

dense_optimizer

如果设置为 True,则强制内部优化向量的致密化。 如果设置为 False,则可让逻辑回归优化器使用它认为合适的稀疏或密集内部状态。 如果将 denseOptimizer 设置为 True,则要求内部优化器使用密集内部状态,这可能有助于减轻垃圾回收器的负载,以应对一些较大的问题。

规范化

指定使用的自动规范化类型:

  • "Auto":如果需要规范化,则会自动执行。 这是默认选项。

  • "No":不执行任何规范化。

  • "Yes":执行规范化。

  • "Warn":如果需要规范化,则会显示一条警告消息,但不执行规范化。

规范化将不同的数据范围重新缩放为标准规模。 特征缩放可确保数据点之间的距离成比例,使各种优化方法(如梯度下降)的收敛速度更快。 如果执行规范化,则使用 MaxMin 规范化程序。 它对区间 [a, b] 中的值进行规范化,其中 -1 <= a <= 00 <= b <= 1 并且 b - a = 1。 此规范化程序通过将 0 映射到 0 来保持稀疏度。

ml_transforms

指定在训练前要对数据执行的 MicrosoftML 转换列表;如果不需要执行任何转换,则指定为“None”。 有关支持的转换,请参阅 featurize_textcategoricalcategorical_hash。 这些转换在任何指定的 Python 转换之后执行。 默认值为“None”。

ml_transform_vars

指定要在 ml_transforms 中使用的变量名称的字符向量;如果不使用任何变量名称,则指定为“None”。 默认值为“None”。

row_selection

不受支持。 使用数据集中的逻辑变量名称(带引号)或通过使用数据集中的变量的逻辑表达式指定模型要使用的数据集中的行(观察值)。 例如:

  • row_selection = "old" 将仅使用变量值 oldTrue 的观察值。

  • row_selection = (age > 20) & (age < 65) & (log(income) > 10) 仅使用 age 变量值介于 20 和 65 之间且 income 变量的 log 值大于 10 的观察值。

在处理任何数据转换之后执行行选择(请参阅参数 transformstransform_function)。 与所有表达式一样,row_selection 可以使用 expression 函数在函数调用之外定义。

转换

不受支持。 表示第一轮变量转换的窗体表达式。 与所有表达式一样,可以使用 expression 函数在函数调用之外定义 transforms(或 row_selection)。

transform_objects

不受支持。 一个命名列表,其中包含可由 transformstransform_functionrow_selection 引用的对象。

transform_function

变量转换函数。

transform_variables

转换函数所需的输入数据集变量的字符向量。

transform_packages

不受支持。 一个字符向量,用于指定将提供和预加载以在变量转换函数中使用的其他 Python 包(除 RxOptions.get_option("transform_packages") 中指定的包以外)。 例如,在 revoscalepy 函数中通过其 transformstransform_function 参数显式定义的那些包,或者通过其 formularow_selection 参数隐式定义的包。 参数 transform_packages 也可能为 None,表示未预加载 RxOptions.get_option("transform_packages") 以外的包。

transform_environment

不受支持。 用户定义环境,充当内部开发并用于变量数据转换的所有环境的父级。 如果为 transform_environment = None,则改用具有父级 revoscalepy.baseenv 的新“哈希”环境。

blocks_per_read

为从数据源读取的每个数据块指定要读取的块数。

report_progress

一个整数值,指定行处理进度的报告级别:

  • 0:不报告进度。

  • 1:打印并更新已处理的行数。

  • 2:报告已处理的行数和计时。

  • 3:报告已处理的行数和所有计时。

verbose

一个整数值,指定需要的输出量。 如果为 0,则计算期间不会打印详细输出。 从 14 的整数值表示提供的信息量逐步增加。

compute_context

设置执行计算的上下文,使用有效的 revoscalepy.RxComputeContext 指定。 目前支持本地和 revoscalepy.RxInSqlServer 计算上下文。

ensemble

控制用于集成的参数。

返回

具有已训练模型的 LogisticRegression 对象。

备注

该算法尝试在 train_threads > 1(多线程)时将整个数据集加载到内存中。

请参阅

rx_predict

参考

维基百科:L-BFGS

维基百科:逻辑回归

L1 正则化对数线性模型的可缩放训练

测试运行 - 机器学习的 L1 和 L2 正则化

二元分类示例

'''
Binary Classification.
'''
import numpy
import pandas
from microsoftml import rx_logistic_regression, rx_predict
from revoscalepy.etl.RxDataStep import rx_data_step
from microsoftml.datasets.datasets import get_dataset

infert = get_dataset("infert")


import sklearn
if sklearn.__version__ < "0.18":
    from sklearn.cross_validation import train_test_split
else:
    from sklearn.model_selection import train_test_split

infertdf = infert.as_df()
infertdf["isCase"] = infertdf.case == 1
data_train, data_test, y_train, y_test = train_test_split(infertdf, infertdf.isCase)

model = rx_logistic_regression(
    formula=" isCase ~ age + parity + education + spontaneous + induced ",
    data=data_train)

print(model.coef_)
    
# RuntimeError: The type (RxTextData) for file is not supported.
score_ds = rx_predict(model, data=data_test,
                     extra_vars_to_write=["isCase", "Score"])
                     
# Print the first five rows
print(rx_data_step(score_ds, number_rows_read=5))

输出:

Automatically adding a MinMax normalization transform, use 'norm=Warn' or 'norm=No' to turn this behavior off.
Beginning processing data.
Rows Read: 186, Read Time: 0, Transform Time: 0
Beginning processing data.
Beginning processing data.
Rows Read: 186, Read Time: 0.001, Transform Time: 0
Beginning processing data.
Beginning processing data.
Rows Read: 186, Read Time: 0, Transform Time: 0
Beginning processing data.
LBFGS multi-threading will attempt to load dataset into memory. In case of out-of-memory issues, turn off multi-threading by setting trainThreads to 1.
Beginning optimization
num vars: 6
improvement criterion: Mean Improvement
L1 regularization selected 5 of 6 weights.
Not training a calibrator because it is not needed.
Elapsed time: 00:00:00.0646405
Elapsed time: 00:00:00.0083991
OrderedDict([('(Bias)', -1.2366217374801636), ('spontaneous', 1.9391206502914429), ('induced', 0.7497404217720032), ('parity', -0.31517016887664795), ('age', -3.162723260174971e-06)])
Beginning processing data.
Rows Read: 62, Read Time: 0, Transform Time: 0
Beginning processing data.
Elapsed time: 00:00:00.0287290
Finished writing 62 rows.
Writing completed.
Rows Read: 5, Total Rows Processed: 5, Total Chunk Time: 0.001 seconds 
  isCase PredictedLabel     Score  Probability
0  False          False -1.341681     0.207234
1   True           True  0.597440     0.645070
2  False           True  0.544912     0.632954
3  False          False -1.289152     0.215996
4  False          False -1.019339     0.265156

多类分类示例

'''
MultiClass Classification
'''
import numpy
import pandas
from microsoftml import rx_logistic_regression, rx_predict
from revoscalepy.etl.RxDataStep import rx_data_step
from microsoftml.datasets.datasets import get_dataset

iris = get_dataset("iris")

import sklearn
if sklearn.__version__ < "0.18":
    from sklearn.cross_validation import train_test_split
else:
    from sklearn.model_selection import train_test_split

irisdf = iris.as_df()
irisdf["Species"] = irisdf["Species"].astype("category")
data_train, data_test, y_train, y_test = train_test_split(irisdf, irisdf.Species)

model = rx_logistic_regression(
    formula="  Species ~ Sepal_Length + Sepal_Width + Petal_Length + Petal_Width ",
    method="multiClass",
    data=data_train)

print(model.coef_)
    
# RuntimeError: The type (RxTextData) for file is not supported.
score_ds = rx_predict(model, data=data_test,
                     extra_vars_to_write=["Species", "Score"])
                     
# Print the first five rows
print(rx_data_step(score_ds, number_rows_read=5))

输出:

Automatically adding a MinMax normalization transform, use 'norm=Warn' or 'norm=No' to turn this behavior off.
Beginning processing data.
Rows Read: 112, Read Time: 0, Transform Time: 0
Beginning processing data.
Beginning processing data.
Rows Read: 112, Read Time: 0, Transform Time: 0
Beginning processing data.
Beginning processing data.
Rows Read: 112, Read Time: 0, Transform Time: 0
Beginning processing data.
LBFGS multi-threading will attempt to load dataset into memory. In case of out-of-memory issues, turn off multi-threading by setting trainThreads to 1.
Beginning optimization
num vars: 15
improvement criterion: Mean Improvement
L1 regularization selected 9 of 15 weights.
Not training a calibrator because it is not needed.
Elapsed time: 00:00:00.0493224
Elapsed time: 00:00:00.0080558
OrderedDict([('setosa+(Bias)', 2.074636697769165), ('versicolor+(Bias)', 0.4899507164955139), ('virginica+(Bias)', -2.564580202102661), ('setosa+Petal_Width', -2.8389241695404053), ('setosa+Petal_Length', -2.4824044704437256), ('setosa+Sepal_Width', 0.274869441986084), ('versicolor+Sepal_Width', -0.2645561397075653), ('virginica+Petal_Width', 2.6924400329589844), ('virginica+Petal_Length', 1.5976412296295166)])
Beginning processing data.
Rows Read: 38, Read Time: 0, Transform Time: 0
Beginning processing data.
Elapsed time: 00:00:00.0331861
Finished writing 38 rows.
Writing completed.
Rows Read: 5, Total Rows Processed: 5, Total Chunk Time: 0.001 seconds 
      Species   Score.0   Score.1   Score.2
0   virginica  0.044230  0.364927  0.590843
1      setosa  0.767412  0.210586  0.022002
2      setosa  0.756523  0.221933  0.021543
3      setosa  0.767652  0.211191  0.021157
4  versicolor  0.116369  0.498615  0.385016