如何使用scikit-learn加载和处理.txt文件?

假设我在桌面上有一个文件夹,里面有不同的.txt文件。它们看起来像这样。

文件1:

('this', 'is'), ('a', 'very'),....., ('large', '.txt'), ('file', 'with'), ('lots', 'of'), ('words', 'like'), ('this', 'i'), ('would', 'like'), ('to', 'create'), ('a', 'matrix'),'LABEL_1'

文件N:

('this', 'is'), ('a', 'another'),....., ('large', '.txt'), ('file', 'with'), ('lots', 'of'), ('words', 'like'), ('this', 'i'), ('would', 'like'), ('to', 'create'), ('a', 'matrix'),'LABEL_N'

根据文档,scikit-learn提供了load_files,我可以使用哈希技巧进行向量化,如下所示:

from sklearn.feature_extraction.text import FeatureHasherfrom sklearn.svm import SVCtraining_data = [[('string1', 'string2'), ('string3', 'string4'),                  ('string5', 'string6'), 'POS'],                 [('string1', 'string2'), ('string3', 'string4'), 'NEG']]feature_hasher_vect = FeatureHasher(input_type ='string')X = feature_hasher_vect.transform(((' '.join(x) for x in sample)                                        for sample in training_data))print X.toarray()

输出:

[[ 0.  0.  0. ...,  0.  0.  0.] [ 0.  0.  0. ...,  0.  0.  0.]]

我如何对整个.txt文件夹进行向量化(应用上述相同过程)使用load_files()或其他任何方法?


回答:

我不熟悉scikit-learn,它可能有更好的方法,但如果你展示的文件格式是正确的,你可以使用以下相对简单的函数来实现你描述的操作:

import astimport globimport osdef my_load_files(folder, pattern):    pathname = os.path.join(folder, pattern)    for filename in glob.glob(pathname):        with open(filename) as file:            yield ast.literal_eval(file.read())text_folder = 'C:/Users/username/Desktop/Samples'print [[' '.join(x) for x in sample]                        for sample in my_load_files(text_folder, 'File_*')]

注意: 由于每个文件末尾都有一个标签(和你的training_data一样),你可能想使用以下替代方法,这样可以将标签排除在传递给feature_hasher_vect.transform()方法的内容之外:

print [[' '.join(x) for x in sample[:-1]]                        for sample in my_load_files(text_folder, 'File_*')]

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注