Python 如何使用特征哈希器转换非数值离散数据,以便将其传递给支持向量机?

Python 如何使用特征哈希器转换非数值离散数据,以便将其传递给支持向量机?,python,numpy,machine-learning,scikit-learn,feature-extraction,Python,Numpy,Machine Learning,Scikit Learn,Feature Extraction,我正在尝试使用UCI机器学习库中的CRX数据集。此特定数据集包含一些非连续变量的特征。因此,我需要将它们转换为数值,然后才能将它们传递给SVM 我最初考虑使用one hot解码器,该解码器获取整数值并将其转换为矩阵(例如,如果一个功能有三个可能的值,“红色”“蓝色”和“绿色”,这将转换为三个二进制功能:1,0,0表示“红色”,“0,1,0表示“蓝色”,0,0,1表示“绿色”。这非常适合我的需要,但它只能处理整数功能除外 def get_crx_data(debug=False): wi

我正在尝试使用UCI机器学习库中的CRX数据集。此特定数据集包含一些非连续变量的特征。因此,我需要将它们转换为数值,然后才能将它们传递给SVM

我最初考虑使用one hot解码器,该解码器获取整数值并将其转换为矩阵(例如,如果一个功能有三个可能的值,“红色”“蓝色”和“绿色”,这将转换为三个二进制功能:1,0,0表示“红色”,“0,1,0表示“蓝色”,0,0,1表示“绿色”。这非常适合我的需要,但它只能处理整数功能除外

def get_crx_data(debug=False):

    with open("/Volumes/LocalDataHD/jt306/crx.data", "rU") as infile:
        features_array = []
        reader = csv.reader(infile,dialect=csv.excel_tab)
        for row in reader:
            features_array.append(str(row).translate(None,"[]'").split(","))
        features_array = np.array(features_array)
        print features_array.shape
        print features_array[0]
        labels_array = features_array[:,15]
        features_array = features_array[:,:15]
        print features_array.shape
        print labels_array.shape


        print("FeatureHasher on frequency dicts")

        hasher = FeatureHasher(n_features=44)
        X = hasher.fit_transform(line for line in features_array)

        print X.shape



get_crx_data()
这是回报

Reading CRX data from disk
Traceback (most recent call last):
  File"/Volumes/LocalDataHD/PycharmProjects/FeatureSelectionPython278/Crx2.py", line 38, in <module>

get_crx_data()
  File "/Volumes/LocalDataHD/PycharmProjects/FeatureSelectionPython278/Crx2.py", line 32, in get_crx_data

X = hasher.fit_transform(line for line in features_array)

File "/Volumes/LocalDataHD/anaconda/lib/python2.7/site-packages/sklearn/base.py", line 426, in fit_transform
    return self.fit(X, **fit_params).transform(X)

File "/Volumes/LocalDataHD/anaconda/lib/python2.7/site-packages/sklearn/feature_extraction/hashing.py", line 129, in transform
    _hashing.transform(raw_X, self.n_features, self.dtype)

File "_hashing.pyx", line 44, in sklearn.feature_extraction._hashing.transform (sklearn/feature_extraction/_hashing.c:1649)

File "/Volumes/LocalDataHD/anaconda/lib/python2.7/site-packages/sklearn/feature_extraction/hashing.py", line 125, in <genexpr>
    raw_X = (_iteritems(d) for d in raw_X)

File "/Volumes/LocalDataHD/anaconda/lib/python2.7/site-packages/sklearn/feature_extraction/hashing.py", line 15, in _iteritems
    return d.iteritems() if hasattr(d, "iteritems") else d.items()

AttributeError: 'numpy.ndarray' object has no attribute 'items'

(690, 16)
['0' ' 30.83' ' 0' ' u' ' g' ' w' ' v' ' 1.25' ' 1' ' 1' ' 1' ' 0' ' g'
 ' 202' ' 0' ' +']
(690, 15)
(690,)
FeatureHasher on frequency dicts

Process finished with exit code 1


How can I use feature hashing (or an alternative method) to convert this data from classes (some of which are strings, others are discrete numerical values) into data which can be handled by an SVM? I have also looked into using one-hot coding, but that only takes integers as input.
从磁盘读取CRX数据
回溯(最近一次呼叫最后一次):
文件“/Volumes/LocalDataHD/PycharmProjects/FeatureSelectionPython278/Crx2.py”,第38行,在
获取_crx_数据()
文件“/Volumes/LocalDataHD/PycharmProjects/FeatureSelectionPython278/Crx2.py”,第32行,在get\u crx\u数据中
X=hasher.fit_变换(特征数组中的行对行)
文件“/Volumes/LocalDataHD/anaconda/lib/python2.7/site packages/sklearn/base.py”,第426行,在fit_转换中
返回self.fit(X,**fit_参数).transform(X)
文件“/Volumes/LocalDataHD/anaconda/lib/python2.7/site packages/sklearn/feature_extraction/hashing.py”,第129行,在转换中
_hashing.transform(原始X、self.n\u特性、self.dtype)
文件“\u hashing.pyx”,第44行,在sklearn.feature\u extraction.\u hashing.transform(sklearn/feature\u extraction/\u hashing.c:1649)中
文件“/Volumes/LocalDataHD/anaconda/lib/python2.7/site packages/sklearn/feature_extraction/hashing.py”,第125行,在
原始X=(\u iteritems(d)表示原始X中的d)
文件“/Volumes/LocalDataHD/anaconda/lib/python2.7/site packages/sklearn/feature\u extraction/hashing.py”,第15行,在iteritems中
如果hasattr(d,“iteritems”)或d.items()返回d.iteritems()
AttributeError:'numpy.ndarray'对象没有属性'items'
(690, 16)
[0''30.83''0''u''g''w''v''1.25''1''1''0''g'
' 202' ' 0' ' +']
(690, 15)
(690,)
基于频率dicts的特征哈希器
进程已完成,退出代码为1
我如何使用特征散列(或替代方法)将这些数据从类(其中一些是字符串,另一些是离散数值)转换为可由支持向量机处理的数据?我还研究了使用一种热编码,但只将整数作为输入。

问题在于
FeatureHasher
对象希望每一行输入都有一个特定的结构,或者实际上是三种不同结构中的一种。第一种可能是一个包含
feature\u name:value
对的字典。第二种是
列表(feature\u name,value)
元组。第三个是
特征名称的平面列表。在前两种情况下,特征名称映射到矩阵中的列,给定的值存储在每行的这些列中。在最后一种情况下,列表中是否存在特征被隐式理解为
True
False
value.以下是一些简单、具体的例子:

>>> hasher = sklearn.feature_extraction.FeatureHasher(n_features=10,
...                                                   non_negative=True,
...                                                   input_type='dict')
>>> X_new = hasher.fit_transform([{'a':1, 'b':2}, {'a':0, 'c':5}])
>>> X_new.toarray()
array([[ 1.,  2.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  5.,  0.,  0.]])
这说明了默认模式——
FeatureHasher
如果您没有像在原始代码中那样传递
input\u type
,将期望什么。正如您所看到的,期望的输入是一个字典列表,每个输入样本或数据行对应一个。每个字典包含任意数量的功能名称,映射到相应的值划船

输出,
X\u new
包含数组的稀疏表示;调用
toarray()
将以普通
numpy
数组的形式返回数据的新副本

如果要传递成对的元组,请传递
input\u type='pairs'
。然后可以执行以下操作:

>>> hasher = sklearn.feature_extraction.FeatureHasher(n_features=10,
...                                                   non_negative=True,
...                                                   input_type='pair')
>>> X_new = hasher.fit_transform([[('a', 1), ('b', 2)], [('a', 0), ('c', 5)]])
>>> X_new.toarray()
array([[ 1.,  2.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  5.,  0.,  0.]])
最后,如果只有布尔值,则根本不必显式传递值--
FeatureHasher
将简单地假设如果存在特征名称,则其值为
True
(此处表示为浮点值
1.0


不幸的是,您的数据似乎不符合这些格式中的任何一种。但是,修改您必须的内容以适应
'dict'
'pair'
格式应该不会太难。如果您需要帮助,请告诉我;如果是这样,请详细说明您尝试转换的数据格式。

您可以吗aste完整堆栈跟踪?这样我们就可以知道哪些行导致了错误。完成。感谢您的查找。感谢提示。完成,并添加了更多信息。乍一看,它不应该是简单的
X=hasher.fit\u transform(features\u array)
>>> hasher = sklearn.feature_extraction.FeatureHasher(n_features=10,
...                                                   non_negative=True,
...                                                   input_type='string')
>>> X_new = hasher.fit_transform([['a', 'b'], ['a', 'c']])
>>> X_new.toarray()
array([[ 1.,  1.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.],
       [ 1.,  0.,  0.,  0.,  0.,  0.,  0.,  1.,  0.,  0.]])