在 numpy 数组上应用 onehotencoder
applying onehotencoder on numpy array
我在 numpy 数组上应用 OneHotEncoder。
这是代码
print X.shape, test_data.shape #gives 4100, 15) (410, 15)
onehotencoder_1 = OneHotEncoder(categorical_features = [0, 3, 4, 5, 6, 8, 9, 11, 12])
X = onehotencoder_1.fit_transform(X).toarray()
onehotencoder_2 = OneHotEncoder(categorical_features = [0, 3, 4, 5, 6, 8, 9, 11, 12])
test_data = onehotencoder_2.fit_transform(test_data).toarray()
print X.shape, test_data.shape #gives (4100, 46) (410, 43)
其中 X
和 test_data
都是 <type 'numpy.ndarray'>
X
是我的训练集,而 test_data
我的测试集。
怎么会没有。 X
和 test_data
的列数不同。在应用 onehotencoder 后,它们应该是 46 或 43。
我正在对特定属性应用 OnehotEncoder,因为它们在 X
和 test_data
中都是分类性质的
有人能指出这里有什么问题吗?
不要在 test_data
上使用新的 OneHotEncoder,使用第一个,并且只在 transform()
上使用。这样做:
test_data = onehotencoder_1.transform(test_data).toarray()
切勿对测试数据使用 fit()
(或 fit_transform()
)。
列数不同是完全可能的,因为测试数据可能不包含训练数据中存在的某些类别。因此,当您使用新的 OneHotEncoder 并对其调用 fit()
(或 fit_transform()
)时,它只会了解 test_data
中存在的类别。所以列之间会有差异。
我在 numpy 数组上应用 OneHotEncoder。
这是代码
print X.shape, test_data.shape #gives 4100, 15) (410, 15)
onehotencoder_1 = OneHotEncoder(categorical_features = [0, 3, 4, 5, 6, 8, 9, 11, 12])
X = onehotencoder_1.fit_transform(X).toarray()
onehotencoder_2 = OneHotEncoder(categorical_features = [0, 3, 4, 5, 6, 8, 9, 11, 12])
test_data = onehotencoder_2.fit_transform(test_data).toarray()
print X.shape, test_data.shape #gives (4100, 46) (410, 43)
其中 X
和 test_data
都是 <type 'numpy.ndarray'>
X
是我的训练集,而 test_data
我的测试集。
怎么会没有。 X
和 test_data
的列数不同。在应用 onehotencoder 后,它们应该是 46 或 43。
我正在对特定属性应用 OnehotEncoder,因为它们在 X
和 test_data
有人能指出这里有什么问题吗?
不要在 test_data
上使用新的 OneHotEncoder,使用第一个,并且只在 transform()
上使用。这样做:
test_data = onehotencoder_1.transform(test_data).toarray()
切勿对测试数据使用 fit()
(或 fit_transform()
)。
列数不同是完全可能的,因为测试数据可能不包含训练数据中存在的某些类别。因此,当您使用新的 OneHotEncoder 并对其调用 fit()
(或 fit_transform()
)时,它只会了解 test_data
中存在的类别。所以列之间会有差异。