gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 09:43:45 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com