MinMaxScaler 返回的值大于一

数据挖掘 Python 逻辑回归 特征缩放 正常化 数值
2022-02-23 04:16:45

基本上,我一直在寻找 sklearn 的归一化函数部分,这对以后的逻辑回归很有用。

因为我有负值,所以我选择了 MinMaxScaler 和:feature_range=(0, 1)作为参数。

x = MinMaxScaler(feature_range=(0, 1)).fit_transform(x)

然后使用sm.Logit我得到的培训师和错误,

import statsmodels.api as sm
logit_model=sm.Logit(train_data_numeric_final,target)
result=logit_model.fit()
print(result.summary())

ValueError: endog must be in the unit interval.

我认为我的值超出了 (0,1) 范围,就是这种情况:

np.unique(np.less_equal(train_data_numeric_final.values, 1))

array([False,  True])

怎么会?那么我该如何进行。

1个回答

我不确定你为什么MinMaxScaler不工作,但这里有一个函数可以将你的数据扩展到所需的范围:

def rescale(data, new_min=0, new_max=1):
    """Rescale the data to be within the range [new_min, new_max]"""
    return (data - data.min()) / (data.max() - data.min()) * (new_max - new_min) + new_min

查看 的文档MinMaxScaler,似乎我上面的功能与他们的方法相同。

您可以将您的代码稍微分解一下,以便在自己的行上明确计算每个步骤。这可能有助于找到问题的根源。我试了一下,得到了预期的结果:

In [1]: import numpy as np

In [2]: from sklearn.preprocessing import MinMaxScaler

In [3]: x = np.random.randint(0, 10, (10, 10)).astype(np.float)

In [4]: x                                    # generate random data in range [0, 9]
Out[4]: 
array([[ 1.,  4.,  5.,  4.,  6.,  1.,  8.,  1.,  8.,  9.],
       [ 3.,  1.,  4.,  4.,  6.,  2.,  5.,  1.,  0.,  8.],
       [ 2.,  0.,  6.,  1.,  5.,  2.,  5.,  8.,  8.,  4.],
       [ 8.,  9.,  2.,  8.,  5.,  6.,  0.,  5.,  0.,  5.],
       [ 1.,  3.,  2.,  2.,  3.,  2.,  4.,  1.,  7.,  5.],
       [ 7.,  0.,  8.,  8.,  3.,  6.,  6.,  6.,  4.,  3.],
       [ 4.,  3.,  4.,  4.,  7.,  6.,  4.,  5.,  6.,  7.],
       [ 9.,  0.,  8.,  9.,  7.,  1.,  2.,  2.,  4.,  6.],
       [ 7.,  4.,  2.,  8.,  6.,  5.,  2.,  9.,  9.,  9.],
       [ 7.,  6.,  9.,  2.,  9.,  0.,  1.,  5.,  7.,  3.]])


In [5]: scaler = MinMaxScaler()              # defaults to range [0, 1]

In [6]: scaler.fit(x)                        # compute the scaling factors
Out[6]: MinMaxScaler(copy=True, feature_range=(0, 1))

In [7]: scaled_data = scaler.transform(x)    # scale the data

In [8]: scaled_data.shape                    # still the same shape
Out[8]: (10, 10)

In [9]: scaled_data.min()                    # min and max are 0 and 1 as expected
Out[9]: 0.0

In [10]: scaled_data.max()
Out[10]: 1.0