python - 如何在python中将Word2Vec向量提供给分类器?
问题描述
我在 python 中的代码用于多标签分类;对一堆推文使用 TF-IDF 矢量化器。我只是把代码的相应部分放在下面。我的词汇是 14182 个单词的词典,而 train_array.shape 是 (6838,14182)。train_labels.shape 也是 (6838, 11):
#Vectorizing
vector_maker = TfidfVectorizer(stop_words= set(stopwords.words('english')), vocabulary= vocab) #Vectorizer
train_array = vector_maker.fit_transform(train_tweets).toarray() #Making vector for train tweets
test_array = vector_maker.fit_transform(test_tweets).toarray() #Making vector for test tweets
clf = tree.DecisionTreeClassifier()
clf.fit(train_array,train_labels)
predicted= clf.predict(test_array)
print("Accuracy = ",accuracy_score(test_gold_labels,predicted))
代码运行良好。现在我想使用 Word2Vec 作为矢量化器。我将代码更改为:
#Vectorizing
vector_maker = Word2Vec(vocab, size=50, window=5, min_count=1, workers=8) #Vectorizer
train_array = vector_maker.train(train_tweets, total_examples=vector_maker.corpus_count, epochs=15) #Making vector for train tweets
test_array = vector_maker.train(test_tweets, total_examples=vector_maker.corpus_count, epochs=15) #Making vector for test tweets
clf = tree.DecisionTreeClassifier()
clf.fit(train_array,train_labels)
predicted= clf.predict(test_array)
print("Accuracy = ",accuracy_score(test_gold_labels,predicted))
然后我得到这个错误:
ValueError Traceback (most recent call last)
<ipython-input-8-3977a56bf1df> in <module>
71 #clf = RandomForestClassifier()
72 clf = tree.DecisionTreeClassifier()
---> 73 clf.fit(train_array,train_labels)
74 predicted= clf.predict(test_array)
75 print("Accuracy = ",accuracy_score(test_gold_labels,predicted))
~\Anaconda3\lib\site-packages\sklearn\tree\tree.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
814 sample_weight=sample_weight,
815 check_input=check_input,
--> 816 X_idx_sorted=X_idx_sorted)
817 return self
818
~\Anaconda3\lib\site-packages\sklearn\tree\tree.py in fit(self, X, y, sample_weight, check_input, X_idx_sorted)
128 random_state = check_random_state(self.random_state)
129 if check_input:
--> 130 X = check_array(X, dtype=DTYPE, accept_sparse="csc")
131 y = check_array(y, ensure_2d=False, dtype=None)
132 if issparse(X):
~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
519 "Reshape your data either using array.reshape(-1, 1) if "
520 "your data has a single feature or array.reshape(1, -1) "
--> 521 "if it contains a single sample.".format(array))
522
523 # in the future np.flexible dtypes will be handled like object dtypes
ValueError: Expected 2D array, got 1D array instead:
array=[1249397. 9119055.].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
然后我发现 train_array 不是数组。我的意思是我发现要获得训练有素的 Word2Vec 向量,您应该使用 vector_maker.wv.vectors。但首先我尝试了这个来查看向量维度:
print(vector_maker.wv.vectors.shape)
但我得到 (30, 50)。我不应该得到(6838,50)吗?或者是什么?实际上我不太了解 Word2Vec 的工作原理。我读了很多,但没有得到那么多。你们能告诉我应该怎么做才能使用创建的向量进行分类吗?
解决方案
不要重新使用.fit()
您TfidfVectorizer
的测试数据:它会更改单词索引和权重以匹配测试数据。相反,适合训练数据,然后在测试数据上使用相同的训练数据拟合模型,以反映您仅根据没有它所学的内容来分析测试数据的事实,并且兼容
您的代码没有Word2Vec
正确使用 gensim 类:
什么是“词汇”?(该
Word2Vec
课程需要一个可迭代的已标记文本的训练语料库,或者根本不需要,以便您可以手动执行后续步骤。它不需要任何被描述为 a 的东西vocab
,而且您还没有展示什么vocab
是,如果您确实在Word2Vec()
实例化中提供了语料库,那么您就不会调用train()
该模型。).
train()
不返回对应于每个文本或每个单词的数组:只是一些关于训练的摘要数字。您必须稍后向模型询问您需要的每个学习的词向量。而且,词向量不是多词文本的摘要(除非您将它们平均在一起)。目前尚不清楚您是否已根据需要将文本预先标记为单词列表
Word2Vec
。如果您传递的是原始字符串,而不是词标记,则模型将学习每个字符的无意义向量。如果您的文本中只有 30 个唯一字符,则可以解释model.wv.vectors.shape
:(30, 50)
您已经创建了 30 个每个 50 维的词向量。
你的代码远远不够工作,最好的办法是阅读一些功能性Word2Vec
文档教程,了解使用它的正确方法,然后再尝试将其嵌入到更大的scikit-learn
训练管道中。例如,参见早期版本 gensim 中的 OK 介绍笔记本:
推荐阅读
- html - 我必须在不同的 div 中创建一个网页并从(例如 mytestdata.com)加载数据。数组产品中有多个数据
- sql - 从 SQL Server 中删除同一个人、不同 ID 的多个实例
- javascript - 还有哪些其他选项可以在不构建服务器的情况下存储两个单独的用户数据?
- laravel - Laravel:未找到 apiResouce 路由问题
- android - Android gradle 插件和 android sdk 构建工具
- kotlin - Kotlin 数据类:如果我在编译时不知道其名称,如何设置属性?
- excel - 复制前提示用户确认覆盖数据
- javascript - DataTable - 无效的 Json 响应
- python - 在对一个时间序列数据进行 LSTM 模型训练后初始化状态
- c# - 不会破坏应用程序的 C# 异常处理