将 float 转换为 int 不会丢失原始值的信息

Convert float to int not loosing information of original values

我需要将 float 转换为 int。但是,我不想在转换时丢失任何信息。我考虑的值(来自在建模构建中使用 y 的数据框列)如下:

-1.0    
 0.0     
 9.0      
-0.5  
 1.5
 1.5    
 ...

如果我直接将它们转换为 int,我可能会得到 -0.5 作为 0 或 -1,所以我会丢失一些信息。

我需要将上面的值转换为 int,因为我需要传递它们以适应模型 model.fit(X, y)。任何可以让我在 fit 函数中传递这些值的格式(上面的列是指 y 列)?

代码:

from sklearn.preprocessing import MinMaxScaler

le = preprocessing.LabelEncoder()
X = df[['Col1','Col2']].apply(le.fit_transform)
X_transformed=np.concatenate(((X[['Col1']]),(X[['Col2']])), axis=1)

y=df['Label'].values

scaler=MinMaxScaler()
X_scaled=scaler.fit_transform(X_transformed)

model_LS = LabelSpreading(kernel='knn', 
                          gamma=70,          
                          alpha=0.5, 
                          max_iter=30,
                          tol=0.001,
                          n_jobs=-1, 
                         )


LS=model_LS.fit(X_scaled, y)

数据:

Col1         Col2     Label
Cust1        Cust2     1.0
Cust1        Cust4     1.0
Cust4        Cust5     -1.5
Cust12       Cust6     9.0

我得到 运行 上面代码的错误是:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-174-14429cc07d75> in <module>
      2 
----> 3 LS=model_LS.fit(X_scaled, y)

~/opt/anaconda3/lib/python3.8/site-packages/sklearn/semi_supervised/_label_propagation.py in fit(self, X, y)
    228         X, y = self._validate_data(X, y)
    229         self.X_ = X
--> 230         check_classification_targets(y)
    231 
    232         # actual graph construction (implementations should override this)

~/opt/anaconda3/lib/python3.8/site-packages/sklearn/utils/multiclass.py in check_classification_targets(y)
    181     if y_type not in ['binary', 'multiclass', 'multiclass-multioutput',
    182                       'multilabel-indicator', 'multilabel-sequences']:
--> 183         raise ValueError("Unknown label type: %r" % y_type)
    184 
    185 

ValueError: Unknown label type: 'continuous'

我认为你需要:

from sklearn.preprocessing import LabelEncoder
df = pd.DataFrame(data={'y':[-1.0, 0.0 , 9.0, -0.5, 1.5 , 1.5]})

le = LabelEncoder()
le.fit(df['y'])
df['y'] = le.transform(df['y'])
print(df)

OUTPUT

   y
0  0
1  2
2  4
3  1
4  3
5  3

您可以将您的值相乘以删除小数部分:

df = pd.DataFrame({'Label': [1.0, -1.3, 0.75, 9.0, 7.8236]})
decimals = df['Label'].astype(str).str.split('.').str[1].str.len().max()

df['y'] = df['Label'].mul(float(f"1e{decimals}")).astype(int)
print(df)

# Output:
    Label      y
0  1.0000  10000
1 -1.3000 -13000
2  0.7500   7500
3  9.0000  90000
4  7.8236  78236