python中的非线性特征变换

Luk*_*kas 3 python regression numpy machine-learning pandas

为了将线性回归模型拟合到某些给定的训练数据 X 和标签 y,我想通过给定特征的非线性变换来扩充我的训练数据 X。假设我们有特征 x 1、 x 2和 x 3。我们想使用额外的转换功能:

x 4 = x 1 2 , x 5 = x 2 2和 x 6 = x 3 2

x 7 = exp(x 1 ), x 8 = exp(x 2 ) 和 x 9 = exp(x 3 )

x 10 = cos(x 1 ), x 11 = cos(x 2 ) 和 x 12 = cos(x 3 )

我尝试了以下方法,但这导致模型在均方根误差作为评估标准方面表现非常差:

import pandas as pd
import numpy as np
from sklearn import linear_model
#import the training data and extract the features and labels from it
DATAPATH = 'train.csv'
data = pd.read_csv(DATAPATH)
features = data.drop(['Id', 'y'], axis=1)
labels = data[['y']]

features['x6'] = features['x1']**2
features['x7'] = features['x2']**2
features['x8'] = features['x3']**2


features['x9'] = np.exp(features['x1'])
features['x10'] = np.exp(features['x2'])
features['x11'] = np.exp(features['x3'])


features['x12'] = np.cos(features['x1'])
features['x13'] = np.cos(features['x2'])
features['x14'] = np.cos(features['x3'])

regr = linear_model.LinearRegression()

regr.fit(features, labels)
Run Code Online (Sandbox Code Playgroud)

我对机器学习很陌生,肯定有更好的选择来进行这些非线性特征转换,我很高兴为您提供帮助。

干杯卢卡斯

FBr*_*esi 5

作为最初的评论,我认为有更好的方法来转换所有列。一种选择是:

# Define list of transformation
trans = [lambda a: a, np.square, np.exp, np.cos]

# Apply and concatenate transformations
features = pd.concat([t(features) for t in trans], axis=1)

# Rename column names
features.columns = [f'x{i}' for i in range(1, len(list(features))+1)]
Run Code Online (Sandbox Code Playgroud)

关于模型的性能,正如@warped 在评论中所说,通常的做法是缩放所有数据。根据您的数据分布,您可以使用不同类型的缩放器(关于它的讨论standard 与 minmax scaler)。

由于您使用的是非线性变换,即使您的初始数据可能是正态分布的,在变换后它们也会失去这种特性。因此最好使用MinMaxScaler.

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler()
scaler.fit(features.to_numpy())
scaled_features = scaler.transform(features.to_numpy())
Run Code Online (Sandbox Code Playgroud)

现在每一列的scaled_features范围都是从 0 到 1。

请注意,如果在使用诸如 之类的东西之前应用 scaler train_test_split,则会发生数据泄漏,这对模型也不利。