首页 > 解决方案 > Keras 模型适合 ValueError 预期 input_1 比我的数组大小大一个数字

问题描述

我正在尝试创建一个自动编码器神经网络以使用 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)

我完全迷路了,我什至不知道我对自动编码器网络的方法是否正确,我做错了什么?

标签: python-3.xmachine-learningkerasdeep-learning

解决方案


word_indexTokenizer1 开始,而不是从零开始

例子:

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 开始。所以当我们term frequency使用这些索引创建矩阵时

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)

推荐阅读