Scikit-Learn one在训练/测试分割之前或之后进行热编码



我正在寻找使用scikit-learn构建模型的两个场景,我无法弄清楚为什么其中一个返回的结果与另一个完全不同。这两种情况(据我所知)的唯一不同之处在于,在一种情况下,我一次(在整个数据上)对所有分类变量进行one-hot编码,然后在训练和测试之间进行分割。在第二种情况下,我在训练和测试之间进行分割,然后基于训练数据对两组数据进行一次热编码。

后一种情况在技术上更好地判断过程的泛化误差,但这种情况返回的归一化基尼系数与第一种情况相比有很大不同(而且很糟糕——基本上没有模型)。我知道第一种情况下,基尼系数(~0.33)符合基于该数据建立的模型。

为什么第二种情况返回如此不同的gini?数据集包含数值变量和分类变量的混合。

方法1(一次性编码整个数据然后拆分)返回:Validation Sample Score: 0.3454355044 (normalized gini).

from sklearn.cross_validation import StratifiedKFold, KFold, ShuffleSplit,train_test_split, PredefinedSplit
from sklearn.ensemble import RandomForestRegressor , ExtraTreesRegressor, GradientBoostingRegressor
from sklearn.linear_model import LogisticRegression
import numpy as np
import pandas as pd
from sklearn.feature_extraction import DictVectorizer as DV
from sklearn import metrics
from sklearn.preprocessing import StandardScaler
from sklearn.grid_search import GridSearchCV,RandomizedSearchCV
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor
from scipy.stats import randint, uniform
from sklearn.metrics import mean_squared_error
from sklearn.datasets import load_boston
def gini(solution, submission):
    df = zip(solution, submission, range(len(solution)))
    df = sorted(df, key=lambda x: (x[1],-x[2]), reverse=True)
    rand = [float(i+1)/float(len(df)) for i in range(len(df))]
    totalPos = float(sum([x[0] for x in df]))
    cumPosFound = [df[0][0]]
    for i in range(1,len(df)):
        cumPosFound.append(cumPosFound[len(cumPosFound)-1] + df[i][0])
    Lorentz = [float(x)/totalPos for x in cumPosFound]
    Gini = [Lorentz[i]-rand[i] for i in range(len(df))]
    return sum(Gini)
def normalized_gini(solution, submission):
    normalized_gini = gini(solution, submission)/gini(solution, solution)
    return normalized_gini
# Normalized Gini Scorer
gini_scorer = metrics.make_scorer(normalized_gini, greater_is_better = True)

if __name__ == '__main__':
    dat=pd.read_table('/home/jma/Desktop/Data/Kaggle/liberty/train.csv',sep=",")
    y=dat[['Hazard']].values.ravel()
    dat=dat.drop(['Hazard','Id'],axis=1)

    folds=train_test_split(range(len(y)),test_size=0.30, random_state=15) #30% test
    #First one hot and make a pandas df
    dat_dict=dat.T.to_dict().values()
    vectorizer = DV( sparse = False )
    vectorizer.fit( dat_dict )
    dat= vectorizer.transform( dat_dict )
    dat=pd.DataFrame(dat)

    train_X=dat.iloc[folds[0],:]
    train_y=y[folds[0]]
    test_X=dat.iloc[folds[1],:]
    test_y=y[folds[1]]

    rf=RandomForestRegressor(n_estimators=1000, n_jobs=1, random_state=15)
    rf.fit(train_X,train_y)
    y_submission=rf.predict(test_X)
    print("Validation Sample Score: {:.10f} (normalized gini).".format(normalized_gini(test_y,y_submission)))

方法2(首先拆分,然后单热编码)返回:Validation Sample Score: 0.0055124452 (normalized gini).

from sklearn.cross_validation import StratifiedKFold, KFold, ShuffleSplit,train_test_split, PredefinedSplit
from sklearn.ensemble import RandomForestRegressor , ExtraTreesRegressor, GradientBoostingRegressor
from sklearn.linear_model import LogisticRegression
import numpy as np
import pandas as pd
from sklearn.feature_extraction import DictVectorizer as DV
from sklearn import metrics
from sklearn.preprocessing import StandardScaler
from sklearn.grid_search import GridSearchCV,RandomizedSearchCV
from sklearn.ensemble import RandomForestRegressor, ExtraTreesRegressor
from scipy.stats import randint, uniform
from sklearn.metrics import mean_squared_error
from sklearn.datasets import load_boston
def gini(solution, submission):
    df = zip(solution, submission, range(len(solution)))
    df = sorted(df, key=lambda x: (x[1],-x[2]), reverse=True)
    rand = [float(i+1)/float(len(df)) for i in range(len(df))]
    totalPos = float(sum([x[0] for x in df]))
    cumPosFound = [df[0][0]]
    for i in range(1,len(df)):
        cumPosFound.append(cumPosFound[len(cumPosFound)-1] + df[i][0])
    Lorentz = [float(x)/totalPos for x in cumPosFound]
    Gini = [Lorentz[i]-rand[i] for i in range(len(df))]
    return sum(Gini)
def normalized_gini(solution, submission):
    normalized_gini = gini(solution, submission)/gini(solution, solution)
    return normalized_gini
# Normalized Gini Scorer
gini_scorer = metrics.make_scorer(normalized_gini, greater_is_better = True)

if __name__ == '__main__':
    dat=pd.read_table('/home/jma/Desktop/Data/Kaggle/liberty/train.csv',sep=",")
    y=dat[['Hazard']].values.ravel()
    dat=dat.drop(['Hazard','Id'],axis=1)

    folds=train_test_split(range(len(y)),test_size=0.3, random_state=15) #30% test
    #first split
    train_X=dat.iloc[folds[0],:]
    train_y=y[folds[0]]
    test_X=dat.iloc[folds[1],:]
    test_y=y[folds[1]]
    #One hot encode the training X and transform the test X
    dat_dict=train_X.T.to_dict().values()
    vectorizer = DV( sparse = False )
    vectorizer.fit( dat_dict )
    train_X= vectorizer.transform( dat_dict )
    train_X=pd.DataFrame(train_X)
    dat_dict=test_X.T.to_dict().values()
    test_X= vectorizer.transform( dat_dict )
    test_X=pd.DataFrame(test_X)

    rf=RandomForestRegressor(n_estimators=1000, n_jobs=1, random_state=15)
    rf.fit(train_X,train_y)
    y_submission=rf.predict(test_X)
    print("Validation Sample Score: {:.10f} (normalized gini).".format(normalized_gini(test_y,y_submission)))

虽然前面的注释正确地建议最好首先映射整个特征空间,但在您的情况下,Train和Test都包含所有列中的所有特征值。

如果比较两个版本之间的vectorizer.vocabulary_,它们完全相同,因此映射没有差异。因此,它不可能引起问题。

方法2失败的原因是因为当您执行此命令时,您的dat_dict通过原始索引重新排序

dat_dict=train_X.T.to_dict().values()

换句话说,train_X在这行代码中有一个打乱的索引。当您将其转换为dict时,dict顺序将重新排序为原始索引的数字顺序。这将导致您的训练和测试数据与y完全不相关。

方法1没有这个问题,因为您在映射之后打乱了数据。

您可以通过在方法2中分配dat_dict时都添加.reset_index()来解决这个问题,例如

dat_dict=train_X.reset_index(drop=True).T.to_dict().values()

这确保在转换为dict时保持数据顺序。

当我添加这段代码时,我得到以下结果:
-方法一:验证样本得分:0.3454355044(归一化基尼系数)
-方法二:验证样本得分:0.3438430991(归一化基尼系数)

我不能让你的代码运行,但我的猜测是,在测试数据集中要么

  • 您没有看到某些分类变量的所有级别,因此,如果您仅在此数据上计算虚拟变量,则实际上会有不同的列。
  • 否则,也许你有相同的列,但他们在不同的顺序?

相关内容

  • 没有找到相关文章

最新更新