【问题标题】:how to add the following feature to a tfidf matrix?如何将以下特征添加到 tfidf 矩阵?
【发布时间】:2017-05-11 08:34:21
【问题描述】:

您好,我有一个名为 list_cluster 的列表,如下所示:

list_cluster=["hello,this","this is a test","the car is red",...]

我正在使用 TfidfVectorizer 生成模型如下:

from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
with open('vectorizerTFIDF.pickle', 'rb') as infile:
    tdf = pickle.load(infile)
tfidf2 = tdf.transform(list_cluster)

然后我想在这个名为 tfidf2 的矩阵中添加新功能,我有一个列表如下:

dates=['010000000000', '001000000000', '001000000000', '000000000001', '001000000000', '000000000010',...]

这个列表和list_cluster一样长,表示日期有12个位置,1的地方是一年中对应的月份,

例如'010000000000'代表二月,

为了将其用作功能,我首先尝试了:

import numpy as np
dates=np.array(listMonth)
dates=np.transpose(dates)

获取一个 numpy 数组,然后转置它以将其与第一个矩阵 tfidf2 连接

print("shape tfidf2: "+str(tfidf2.shape),"shape dates: "+str(dates.shape))

为了连接我的向量和矩阵,我尝试了:

tfidf2=np.hstack((tfidf2,dates[:,None]))

但是这是输出:

shape tfidf2: (11159, 1927) shape dates: (11159,)
Traceback (most recent call last):
  File "Main.py", line 230, in <module>
    tfidf2=np.hstack((tfidf2,dates[:,None]))
  File "/usr/local/lib/python3.5/dist-packages/numpy/core/shape_base.py", line 278, in hstack
    return _nx.concatenate(arrs, 0)
ValueError: all the input arrays must have same number of dimensions

形状看起来不错,但我不确定是什么失败了,我想感谢支持将此功能连接到我的 tfidf2 矩阵,提前感谢您的关注,

【问题讨论】:

  • dtypes 是什么?如果dates 是1d,那么transpose 什么也不做。但是[:,None] 应该给它正确的二维形状。
  • @hpaulj,感谢您的支持,是的,日期是 1d,如何将其转换为 1,11159 的矩阵,然后与我的矩阵连接?
  • (11159,1)hstack 的正确形状(与axis=1 连接)。这就是为什么我要询问 dtypes 以查看是否有其他关于数组的问题(尽管错误说明了什么)。
  • @hpaulj,感谢您的帮助,好的,我认为存在 dtypes 问题,因为日期是由字符串组成的数组,我需要找到一种方法将其转换为数字数组,

标签: numpy scikit-learn


【解决方案1】:

您需要将所有字符串转换为 sklearn 的数字。一种方法是使用 sklearn 预处理模块中的 LabelBinarizer 类。这会为原始列中的每个唯一值创建一个新的二进制列。

如果日期的行数与tfidf2 相同,那么我认为这会起作用。

# create tfidf2
tfidf2 = tdf.transform(list_cluster)

#create dates
dates=['010000000000', '001000000000', '001000000000', '000000000001', '001000000000', '000000000010',...]

# binarize dates
lb = LabelBinarizer()
b_dates = lb.fit_transform(dates)

new_tfidf = np.concatenate((tfidf2, b_dates), axis=1)

【讨论】:

    猜你喜欢
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    相关资源
    最近更新 更多