我正在处理一个机器学习问题,我的数据集中有大量的邮政编码(约8000个唯一值)。因此,我决定将这些值哈希到一个较小的特征空间,而不是使用像OHE这样的方法。
我遇到的问题是我的哈希中只有很小百分比(20%)的唯一行,这意味着在我看来,有很多重复或碰撞。尽管我将哈希表中的特征增加到约200个,但我从未得到超过20%的唯一值。这对我来说没有意义,因为随着哈希中列数的增加,应该有更多的唯一组合可能出现。
我使用以下代码来对邮政编码进行哈希,并基于最后数组中的唯一值计算碰撞:
from sklearn.feature_extraction import FeatureHasherD = pd.unique(Daten["PLZ"])print("Zipcode Data:", D,"\nZipcode Shape:", D.shape)h = FeatureHasher(n_features=2**5, input_type="string")f = h.transform(D)f = f.toarray()print("Feature Array:\n",f ,"\nFeature Shape:", f.shape)unq = np.unique(f, axis=0)print("Unique values:\n",unq,"\nUnique Shape:",unq.shape)print("Percentage of unique values in hash array:",unq.shape[0]/f.shape[0]*100)
我得到的输出是:
Zipcode Data: ['86916' '01445' '37671' ... '82387' '83565' '83550'] Zipcode Shape: (8158,)Feature Array: [[ 2. 1. 0. ... 0. 0. 0.] [ 0. -1. 0. ... 0. 0. 0.] [ 1. 0. 0. ... 0. 0. 0.] ... [ 0. 0. 0. ... 0. 0. 0.] [ 1. 0. 0. ... 0. 0. 0.] [ 0. -1. 0. ... 0. 0. 0.]] Feature Shape: (8158, 32)Unique values: [[ 0. -3. 0. ... 0. 0. 0.] [ 0. -2. 0. ... 0. 0. 0.] [ 0. -2. 0. ... 0. 0. 0.] ... [ 4. 0. 0. ... 0. 0. 0.] [ 4. 0. 0. ... 0. 0. 0.] [ 4. 0. 0. ... 0. 0. 0.]] Unique Shape: (1707, 32)Percentage of unique values in hash array: 20.9242461387595
任何帮助和见解都将不胜感激。
回答:
转换后的数据中最开始的2
应该是一个线索。我想你还会发现许多列都是零的。
根据文档,
每个样本必须是可迭代的…
所以哈希器将邮政编码'86916'
视为元素8
、6
、9
、1
、6
的集合,你只会得到十个非零列(第一列可能是6
,因为它出现了两次,如开头所述)。你可以通过将输入重塑为二维来纠正这个问题。