python - 朴素贝叶斯拟合方法重塑数组
问题描述
我正在尝试通过连接词向量来创建句子嵌入。这是我编写的代码:
a=np.zeros(100, dtype=float)
try:
a=embedding_dict[ line[0] ] ## get first word embedding;
except KeyError:
print ( "Error")
for k in range(1,len(line)):
try:
b=np.zeros(100, dtype=float)
b=embedding_dict[ line[k] ]
a=np.concatenate([a,b])
except KeyError:
print ( "Error")
length=len(a)
if length > 1500:
#Reduce Size
print("Reduction of SIze")
result_arr = a[:1500]
# result_arr = truncated_arr[None, :]
else:
#Padd
print("padding")
result_arr=np.pad(a, (0, 1500 - len(a)%1500), 'constant')
print( " result_arr.shape before ",result_arr.shape )
# test = result_arr.reshape(1, -1)
# print( " result_arr.shape before ",test.shape )
sentence_Vectors.append(result_arr)
我正在使用朴素贝叶斯进行分类:
nb = MultinomialNB()
nb.fit(X_train, y_train)
y_pred = nb.predict(X_val)
print('naive bayes using sentence embedding accuracy%s' % accuracy_score(y_pred, y_val))
nb.fit
并在方法中给出错误
Traceback (most recent call last):
File "ConcatEmbedding.py", line 121, in <module>
nb.fit(X_train, y_train)
File "/usr/local/lib/python2.7/site-packages/sklearn/naive_bayes.py", line 585, in fit
X, y = check_X_y(X, y, 'csr')
File "/usr/local/lib/python2.7/site-packages/sklearn/utils/validation.py", line 756, in check_X_y
estimator=estimator)
File "/usr/local/lib/python2.7/site-packages/sklearn/utils/validation.py", line 552, in check_array
"if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
我已经尝试过重塑(1,-1)
和审查这篇文章,但没有用。
解决方案
x.reshape(-1,1)
不是x.reshape(1,-1)
。您想要 100 个具有 1 个特征的样本,而不是 1 个具有 100 个特征的样本。
import numpy as np
from sklearn.naive_bayes import MultinomialNB
x = np.random.random(100)
y = np.random.randint(0,2,size=100)
x = x.reshape(-1,1)
print(x.shape)
nb = MultinomialNB()
nb.fit(x, y)
nb.predict(x)
推荐阅读
- javascript - 有没有办法使用 JavaScript 访问子类中的超类变量?
- c# - ASP.NET MVC 删除行 jquery 数据表
- jhipster - 根据权威更改 Jhipster 登陆页面
- python - 每学期学费计划
- python - 通过函数将自定义列添加到 DataFrame
- php - 如何从 db 中选择表,其中 id = 另一个页面中表单的 id?
- python - pandas groupby 具有像行列式这样的子组操作?
- php - 我正在尝试将数组转换为 XML,但未能 100% 正确
- android - 如何调试Android App以授予特权权限?
- php - foreach 仅针对数组中的第一项运行函数(`sendThis`)