所以有一个约定来做到这一点。以示例显示比解释要容易得多。
假设你从你的网站分析应用程序收集,组描述每个访问者网站指标:
性/性别
采集通道
论坛参与度
acco UNT型
每个这些是分类变量(又名因子)而不是连续的变量(例如,总会话时间或帐户年龄)。
# column headers of raw data--all fields are categorical ('factors')
col_headers = ['sex', 'acquisition_channel', 'forum_participation_level', 'account_type']
# a single data row represents one user
row1 = ['M', 'organic_search', 'moderator', 'premium_subscriber']
# expand data matrix width-wise by adding new fields (columns) for each factor level:
input_fields = [ 'male', 'female', 'new', 'trusted', 'active_participant', 'moderator',
'direct_typein', 'organic_search', 'affiliate', 'premium_subscriber',
'regular_subscriber', 'unregistered_user' ]
# now, original 'row1' above, becomes (for input to ML algorithm, etc.)
warehoused_row1 = [1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0]
对于我来说,这种转换技术似乎比将每个变量保持为单个列更明智。例如,如果你使用后者,那么你必须将三种类型的采集通道与它们的数字表示进行协调 - 即,如果自然搜索是“1”,那么应该是加法器2和direct_typein 3,反之亦然?
这种表示的另一个重要优点是,尽管宽度扩展,它仍然是数据的紧凑表示。 (在列扩展是实质的情况下 - 即一个字段是用户状态,这可能意味着1列变为50,稀疏矩阵表示显然是个好主意。)
对于这种类型的工作,我使用数值计算库NumPy和SciPy。
从Python交互式提示:
>>> # create two data rows, representing two unique visitors to a Web site:
>>> row1 = NP.array([0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0])
>>> row2 = NP.array([1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0])
>>> row1.dtype
dtype('int64')
>>> row1.itemsize
8
>>> # these two data arrays can be converted from int/float to boolean, substantially
>>> # reducing their size w/ concomitant performance improvement
>>> row1 = NP.array(row1, dtype=bool)
>>> row2 = NP.array(row2, dtype=bool)
>>> row1.dtype
dtype('bool')
>>> row1.itemsize # compare with row1.itemsize = 8, above
1
>>> # element-wise comparison of two data vectors (two users) is straightforward:
>>> row1 == row2 # element-wise comparison
array([False, False, False, False, True, True, False, True, True, False], dtype=bool)
>>> NP.sum(row1==row2)
5
对于基于相似性的计算(例如k-最近邻),有用于由称为Tanimoto系数分类变量的扩展数据矢量特定指标。对于特定表示我在这里使用的,功能应该是这样的:
def tanimoto_bool(A, B) :
AuB = NP.sum(A==B)
numer = AuB
denom = len(A) + len(B) - AuB
return numer/float(denom)
>>> tanimoto_bool(row1, row2)
0.25