python - SKlearn Tfidfvectorizer 与 Keras : expected dense_input_1 to have shape

标签 python scikit-learn keras

我正在尝试将 SKLearn Tfidfvectorizer 与 Keras 结合使用,但我遇到了以下错误: 异常:检查模型输入时出错:预期 dense_input_1 具有形状 (None, 126) 但得到形状为 (700, 116) 的数组

我知道它与矩阵的形状有关,但我不知道如何解决它。

vectorizer = TfidfVectorizer(analyzer=self.identity, use_idf=True, max_features=2000)

#a list of sentences
x_train_vec = vectorizer.fit_transform(x_train).toarray()
x_test_vec = vectorizer.fit_transform(self.x_test[i]).toarray()

#labels
y_train = np_utils.to_categorical(y_train, self.nb_classes)
y_test = np_utils.to_categorical(y_test, self.nb_classes)

#get model
model = self.build_model(x_train_vec.shape[1])
model.fit(x_train_vec, y_train, nb_epoch=self.n_epochs, batch_size=self.batch_size, shuffle='batch', verbose=1, validation_data=(x_test_vec, y_test), )

构建模型:

def build_model(self, nb_features):
    print("Building model...")

    model = Sequential()
    model.add(Dense(input_dim = nb_features, output_dim = self.hidden_units_1))
    model.add(Activation('relu'))

最佳答案

当你向量化你的测试集时,你需要调用 transform 而不是 fit_transform:

x_train_vec = vectorizer.fit_transform(x_train).toarray()
x_test_vec = vectorizer.transform(self.x_test[i]).toarray()

关于python - SKlearn Tfidfvectorizer 与 Keras : expected dense_input_1 to have shape,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41723247/

相关文章:

scikit-learn - 找到分类的重要特征

python - GridSearchCV 在任何 n_jobs 的窗口上卡住

python - 用户认证 : prepare vs get_current_user in tornado

python - 检查空值列表

python - 当Python中簇数为2时,我的图没有显示结果

python - Keras:如何连接两个 CNN?

neural-network - 在使用批量训练后使用 Keras LSTM 预测单个示例

python - 无法从 'Sequence' 导入名称 'keras.utils'

python - 无法安装适用于 linux/python 的 azure sdk

python - Windows 上的 PyGObject