Python Scikit学习:使用文本和数字变量对数据集进行预测

时间:2018-10-20 11:38:10

标签: python scikit-learn

我有一个项目数据集,我想使用Python和scikit-learn预测其结果(成功/失败)。数据集包含多种数据类型:项目标题,项目描述等是文本列。另一方面,项目成本是一个数字字段。

我想使用TF-IDF转换文本列,我可以将其用作模型的输入。这是我的代码:

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
tfidf_transformer = TfidfTransformer()
X_train['Project Title'] = tfidf_transformer.fit_transform(X_train['Project Title'])

但是我得到了错误:

TypeError: no supported conversion for types: (dtype('O'),)

您知道为什么会显示此错误吗?

编辑:下面的示例数据

Project Title   Project Essay   Project Short Description   Project Need Statement  Project Cost    Project Type ID Project Subject Category Tree ID    Project Subject Subcategory Tree ID Project Resource Category ID    Project Grade Level Category ID Project Current Status ID
Stand Up to Bullying: Together We Can!  Did you know that 1-7 students in grades K-12 ...   Did you know that 1-7 students in grades K-12 ...   My students need 25 copies of "Bullying in Sch...   361.80  0   0   0   0   0   0

1 个答案:

答案 0 :(得分:1)

问题是您使用TfidfTransformer将计数矩阵转换为归一化的tf或tf-idf表示形式,而不是TfidfVectorizer将原始文档的集合转换为TF-IDF功能矩阵< / p>

from sklearn.feature_extraction.text import TfidfVectorizer
X = pd.DataFrame({'Project Title': ['hello stackoverflow', 'text column', 'scikit learn', 'machine learning projects']})
vect = TfidfVectorizer(ngram_range=(1, 2))
tfidf = vect.fit_transform(X['Project Title'])
X_tfidf = pd.DataFrame(matrix.todense(), columns=vect.get_feature_names())