python-3.x - Keras 模型适合 ValueError 预期 input_1 比我的数组大小大一个数字

标签 python-3.x machine-learning keras deep-learning

我正在尝试创建一个自动编码器神经网络来使用 Keras TensorFlow 查找异常值,我的数据是每行一个单词的文本列表,如下: https://pastebin.com/hEvm6qWg它有 139 行。

当我将模型与数据相匹配时,出现错误:

ValueError: Error when checking input: expected input_1 to have shape (139,) but got array with shape (140,)

但是我不知道为什么它会将其识别为140形状数组,我的整个代码如下:

from keras import Input, Model
from keras.layers import Dense
from keras.preprocessing.text import Tokenizer

with open('drawables.txt', 'r') as arquivo:
    dados = arquivo.read().splitlines()

tokenizer = Tokenizer(filters='')
tokenizer.fit_on_texts(dados)

x_dados = tokenizer.texts_to_matrix(dados, mode="freq")

tamanho = len(tokenizer.word_index)

x = Input(shape=(tamanho,))

# Encoder
hidden_1 = Dense(tamanho, activation='relu')(x)
h = Dense(tamanho, activation='relu')(hidden_1)

# Decoder
hidden_2 = Dense(tamanho, activation='relu')(h)
r = Dense(tamanho, activation='sigmoid')(hidden_2)

autoencoder = Model(input=x, output=r)

autoencoder.compile(optimizer='adam', loss='mse')

autoencoder.fit(x_dados, epochs=5, shuffle=False)

我完全迷失了,我什至无法判断我的自动编码器网络方法是否正确,我做错了什么?

最佳答案

Tokenizer 中的

word_index 从 1 开始,而不是从零开始

示例:

tokenizer = Tokenizer(filters='')
tokenizer.fit_on_texts(["this a cat", "this is a dog"])
print (tokenizer.word_index)

输出:

{'this': 1, 'a': 2, 'cat': 3, 'is': 4, 'dog': 5}

索引从 1 开始,而不是从 0 开始。因此,当我们使用这些索引创建词频矩阵时

x_dados = tokenizer.texts_to_matrix(["this a cat", "this is a dog"], mode="freq")

x_dados 的形状将为 2x6,因为 numpy 数组从 0 开始索引。

所以没有:x_dados = 1+len(tokenizer.word_index)中的列

因此要修复您的代码更改

tamanho = len(tokenizer.word_index)

tamanho = len(tokenizer.word_index) + 1

工作示例:

dados = ["this is a  cat", "that is a dog and a cat"]*100
tokenizer = Tokenizer(filters='')
tokenizer.fit_on_texts(dados)

x_dados = tokenizer.texts_to_matrix(dados, mode="freq")
tamanho = len(tokenizer.word_index)+1
x = Input(shape=(tamanho,))

# Encoder
hidden_1 = Dense(tamanho, activation='relu')(x)
h = Dense(tamanho, activation='relu')(hidden_1)

# Decoder
hidden_2 = Dense(tamanho, activation='relu')(h)
r = Dense(tamanho, activation='sigmoid')(hidden_2)

autoencoder = Model(input=x, output=r)
print (autoencoder.summary())

autoencoder.compile(optimizer='adam', loss='mse')
autoencoder.fit(x_dados, x_dados, epochs=5, shuffle=False)

关于python-3.x - Keras 模型适合 ValueError 预期 input_1 比我的数组大小大一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55424734/

相关文章:

python - 如何将扩展 ascii 与 bs4 url​​ 一起使用

python-3.x - 在没有 Tensorflow Serving 的情况下在 GCP 中部署 Tensorflow 模型

ios - Swift 无法读取 csv

Tensorflow:尝试恢复 pb 文件中的模型时出错

python - 模型中的 Keras 层命名不遵守 TF name_scope 前缀

python-3.x - 如何从 Python Dict 创建 Protobuf Struct?

machine-learning - "Combine"语料库中单类文档的 TF-IDF 分数

python - keras:model.predict和model.predict_proba有什么区别

python - 如何使用TensorBoard write_grads函数?

python-telegram-bot错误 'CallbackContext'对象没有属性 'message'