python-3.x - 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)
我完全迷路了,我什至不知道我对自动编码器网络的方法是否正确,我做错了什么?
解决方案
word_index
从Tokenizer
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 开始。所以当我们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)
推荐阅读
- html - 无法在导航栏中向右浮动我的输入区域 - 为什么?
- javascript - 警报消息关闭按钮
- python-3.x - AttributeError:“连接”对象没有属性“setdefault”|| self.__connection_settings.setdefault("charset", "utf8")
- javascript - 预填充 WTForms 字段的当前值以对其进行编辑
- python-requests - 如何使用 RESTCONF 在路由器 Cisco-IOS-XE 中激活 OSPF?
- python - 参数 on_delete 的多个值
- sql - 错误:SQL 语句嵌套太深。在 SQL Server 中编译存储过程时
- typescript - TypeScript:提供可选参数的优雅方式?
- python - 无法让 tkinter 网格按我的意愿布局我的 GUI
- python - python 2.7:@ (g/s)etter def 派生类失败