- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在此数据样本上运行 w2v
Statement Label
Says the Annies List political group supports third-trimester abortions on demand. FALSE
When did the decline of coal start? It started when natural gas took off that started to begin in (President George W.) Bushs administration. TRUE
"Hillary Clinton agrees with John McCain ""by voting to give George Bush the benefit of the doubt on Iran.""" TRUE
Health care reform legislation is likely to mandate free sex change surgeries. FALSE
The economic turnaround started at the end of my term. TRUE
The Chicago Bears have had more starting quarterbacks in the last 10 years than the total number of tenured (UW) faculty fired during the last two decades. TRUE
Jim Dunnam has not lived in the district he represents for years now. FALSE
使用此 GitHub 文件夹 (FeatureSelection.py) 中提供的代码:
https://github.com/nishitpatel01/Fake_News_Detection
我想在我的朴素贝叶斯模型中包含 word2vec 特征。首先我考虑了 X 和 y 并使用了 train_test_split:
X = df['Statement']
y = df['Label']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=40)
dataset = pd.concat([X_train, y_train], axis=1)
这是我目前使用的代码:
#Using Word2Vec
with open("glove.6B.50d.txt", "rb") as lines:
w2v = {line.split()[0]: np.array(map(float, line.split()[1:]))
for line in lines}
training_sentences = DataPrep.train_news['Statement']
model = gensim.models.Word2Vec(training_sentences, size=100) # x be tokenized text
w2v = dict(zip(model.wv.index2word, model.wv.syn0))
class MeanEmbeddingVectorizer(object):
def __init__(self, word2vec):
self.word2vec = word2vec
# if a text is empty we should return a vector of zeros
# with the same dimensionality as all the other vectors
self.dim = len(word2vec.itervalues().next())
def fit(self, X, y): # what are X and y?
return self
def transform(self, X): # should it be training_sentences?
return np.array([
np.mean([self.word2vec[w] for w in words if w in self.word2vec]
or [np.zeros(self.dim)], axis=0)
for words in X
])
"""
class TfidfEmbeddingVectorizer(object):
def __init__(self, word2vec):
self.word2vec = word2vec
self.word2weight = None
self.dim = len(word2vec.itervalues().next())
def fit(self, X, y):
tfidf = TfidfVectorizer(analyzer=lambda x: x)
tfidf.fit(X)
# if a word was never seen - it must be at least as infrequent
# as any of the known words - so the default idf is the max of
# known idf's
max_idf = max(tfidf.idf_)
self.word2weight = defaultdict(
lambda: max_idf,
[(w, tfidf.idf_[i]) for w, i in tfidf.vocabulary_.items()])
return self
def transform(self, X):
return np.array([
np.mean([self.word2vec[w] * self.word2weight[w]
for w in words if w in self.word2vec] or
[np.zeros(self.dim)], axis=0)
for words in X
])
"""
在 classifier.py 中,我正在运行
nb_pipeline = Pipeline([
('NBCV',FeaturesSelection.w2v),
('nb_clf',MultinomialNB())])
但是这不起作用,我收到此错误:
TypeError Traceback (most recent call last)
<ipython-input-14-07045943a69c> in <module>
2 nb_pipeline = Pipeline([
3 ('NBCV',FeaturesSelection.w2v),
----> 4 ('nb_clf',MultinomialNB())])
/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py in inner_f(*args, **kwargs)
71 FutureWarning)
72 kwargs.update({k: arg for k, arg in zip(sig.parameters, args)})
---> 73 return f(**kwargs)
74 return inner_f
75
/anaconda3/lib/python3.7/site-packages/sklearn/pipeline.py in __init__(self, steps, memory, verbose)
112 self.memory = memory
113 self.verbose = verbose
--> 114 self._validate_steps()
115
116 def get_params(self, deep=True):
/anaconda3/lib/python3.7/site-packages/sklearn/pipeline.py in _validate_steps(self)
160 "transformers and implement fit and transform "
161 "or be the string 'passthrough' "
--> 162 "'%s' (type %s) doesn't" % (t, type(t)))
163
164 # We allow last estimator to be None as an identity transformation
TypeError: All intermediate steps should be transformers and implement fit and transform or be the string 'passthrough' '{' ': array([-0.17019527, 0.32363772, -0.0770281 , -0.0278154 , -0.05182227, ....
我正在使用该文件夹中的所有程序,因此如果您使用它们,代码可以重现。
如果您能向我解释如何修复它以及需要对代码进行哪些其他更改,那就太好了。我的目标是将模型(朴素贝叶斯、随机森林等)与 BoW、TF-IDF 和 Word2Vec 进行比较。
更新:
在下面的回答(来自 Ismail)之后,我更新了代码如下:
class MeanEmbeddingVectorizer(object):
def __init__(self, word2vec, size=100):
self.word2vec = word2vec
self.dim = size
和
#building Linear SVM classfier
svm_pipeline = Pipeline([
('svmCV',FeaturesSelection_W2V.MeanEmbeddingVectorizer(FeaturesSelection_W2V.w2v)),
('svm_clf',svm.LinearSVC())
])
svm_pipeline.fit(DataPrep.train_news['Statement'], DataPrep.train_news['Label'])
predicted_svm = svm_pipeline.predict(DataPrep.test_news['Statement'])
np.mean(predicted_svm == DataPrep.test_news['Label'])
但是,我仍然遇到错误。
最佳答案
第 1 步。MultinomialNB FeaturesSelection.w2v
是一个 dict
,它没有 fit
或 fit_transform
函数.此外,MultinomialNB
需要非负值,因此它不起作用。所以我决定添加一个预处理阶段来规范化负值。
from sklearn.preprocessing import MinMaxScaler
nb_pipeline = Pipeline([
('NBCV',MeanEmbeddingVectorizer(FeatureSelection.w2v)),
('nb_norm', MinMaxScaler()),
('nb_clf',MultinomialNB())
])
...而不是
nb_pipeline = Pipeline([
('NBCV',FeatureSelection.w2v),
('nb_clf',MultinomialNB())
])
第 2 步。我在 word2vec.itervalues().next()
上遇到错误。因此,我决定使用与 Word2Vec
大小相同的预定义值更改维度形状。
class MeanEmbeddingVectorizer(object):
def __init__(self, word2vec, size=100):
self.word2vec = word2vec
self.dim = size
...而不是
class MeanEmbeddingVectorizer(object):
def __init__(self, word2vec):
self.word2vec = word2vec
self.dim = len(word2vec.itervalues().next())
关于python - 在 scikit-learn 管道中使用 Word2Vec,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65163881/
我正在使用 Assets 管道来管理我的 Grails 3.0 应用程序的前端资源。但是,似乎没有创建 CoffeeScript 文件的源映射。有什么办法可以启用它吗? 我的 build.gradle
我有一个我想要的管道: 提供一些资源, 运行一些测试, 拆资源。 我希望第 3 步中的拆卸任务运行 不管 测试是否通过或失败,在第 2 步。据我所知 runAfter如果前一个任务成功,则只运行一个任
如果我运行以下命令: Measure-Command -Expression {gci -Path C:\ -Recurse -ea SilentlyContinue | where Extensio
我知道管道是一个特殊字符,我需要使用: Scanner input = new Scanner(System.in); String line = input.next
我再次遇到同样的问题,我有我的默认处理方式,但它一直困扰着我。 有没有更好的办法? 所以基本上我有一个运行的管道,在管道内做一些事情,并想从管道内返回一个键/值对。 我希望整个管道返回一个类型为 ps
我有三个环境:dev、hml 和 qa。 在我的管道中,根据分支,阶段有一个条件来检查它是否会运行: - stage: Project_Deploy_DEV condition: eq(varia
我有 Jenkins Jenkins ver. 2.82 正在运行并想在创建新作业时使用 Pipeline 功能。但我没有看到这个列为选项。我只能在自由式项目、maven 项目、外部项目和多配置之间进
在对上一个问题 (haskell-data-hashset-from-unordered-container-performance-for-large-sets) 进行一些观察时,我偶然发现了一个奇
我正在寻找有关如何使用管道将标准输出作为其他命令的参数传递的见解。 例如,考虑这种情况: ls | grep Hello grep 的结构遵循以下模式:grep SearchTerm PathOfFi
有没有办法不因声明性管道步骤而失败,而是显示警告?目前我正在通过添加 || exit 0 来规避它到 sh 命令行的末尾,所以它总是可以正常退出。 当前示例: sh 'vendor/bin/phpcs
我们正在从旧的 Jenkins 设置迁移到所有计划都是声明性 jenkinsfile 管道的新服务器……但是,通过使用管道,我们无法再手动清除工作区。我如何设置 Jenkins 以允许 手动点播清理工
我在 Python 中阅读了有关 Pipelines 和 GridSearchCV 的以下示例: http://www.davidsbatista.net/blog/2017/04/01/docume
我有一个这样的管道脚本: node('linux'){ stage('Setup'){ echo "Build Stage" } stage('Build'){ echo
我正在使用 bitbucket 管道进行培训 这是我的 bitbucket-pipelines.yml: image: php:7.2.9 pipelines: default:
我正在编写一个程序,其中输入文件被拆分为多个文件(Shamir 的 secret 共享方案)。 这是我想象的管道: 来源:使用 Conduit.Binary.sourceFile 从输入中读取 导管:
我创建了一个管道,它有一个应该只在开发分支上执行的阶段。该阶段还需要用户输入。即使我在不同的分支上,为什么它会卡在这些步骤的用户输入上?当我提供输入时,它们会被正确跳过。 stage('Deplo
我正在尝试学习管道功能(%>%)。 当试图从这行代码转换到另一行时,它不起作用。 ---- R代码--原版----- set.seed(1014) replicate(6,sample(1:8))
在 Jenkins Pipeline 中,如何将工件从以前的构建复制到当前构建? 即使之前的构建失败,我也想这样做。 最佳答案 Stuart Rowe 还在 Pipeline Authoring Si
我正在尝试使用 执行已定义的作业构建 使用 Jenkins 管道的方法。 这是一个简单的例子: build('jenkins-test-project-build', param1 : 'some-
当我使用 where 过滤器通过管道命令排除对象时,它没有给我正确的输出。 PS C:\Users\Administrator> $proall = Get-ADComputer -filter *
我是一名优秀的程序员,十分优秀!