from random import randint
from random import seed
import math
import numpy as np
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense,TimeDistributed,RepeatVector
seed(1)
def ele():
X,y = [],[]
for i in range(1):
l1=[]
for _ in range(2):
l1.append(randint(1,10))
X.append(l1)
y.append(sum(l1))
for i in range(1):
X = str(X[0][0])+'+'+str(X[0][1])
y = str(y[0])
char_to_int = dict((c, i) for i, c in enumerate(alphabet))
Xenc,yenc = [],[]
for pattern in X:
integer_encoded = [char_to_int[char] for char in pattern]
Xenc.append(integer_encoded[0])
for pattern in y:
integer_encoded = [char_to_int[char] for char in pattern]
yenc.append(integer_encoded[0])
k,k1 = [],[]
for i in range(1):
for j in Xenc:
vec = np.zeros(11)
vec[j] = 1
k.append(vec)
for j in yenc:
vec1 = np.zeros(11)
vec1[j] = 1
k1.append(vec1)
k = np.array(k)
k1 = np.array(k1)
return k,k1
alphabet = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+']
model = Sequential()
model.add(LSTM(100, input_shape=(n_in_seq_length,11)))
model.add(RepeatVector(2))
model.add(LSTM(50, return_sequences=True))
model.add(TimeDistributed(Dense(n_chars, activation='softmax')))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
for i in range(1):
X,y = ele()
#X = np.reshape(X, (4,1,11))
model.fit(X, y, epochs=1, batch_size=10)
我收到此错误:
ValueError跟踪(最近的呼叫 最后)在() 53 X,y = ele() 54 #X = np.reshape(X,(4,1,11)) ---> 55 model.fit(X,y,epochs = 1,batch_size = 10)
〜\ Anaconda3 \ lib \ site-packages \ keras \ engine \ training.py in fit(self,x, y,batch_size,epoch,冗长,回调,validation_split, validate_data,随机播放,class_weight,sample_weight,initial_epoch, steps_per_epoch,validation_steps,** kwargs) 948 sample_weight = sample_weight, 第949章 -> 950 batch_size =批量大小) 951#准备验证数据。 952 do_validation = False
〜\ Anaconda3 \ lib \ site-packages \ keras \ engine \ training.py在 _standardize_user_data(自身,x,y,sample_weight,class_weight,check_array_lengths,batch_size) 第747章 748 check_batch_axis = False,#不强制执行批量大小。 -> 749 exception_prefix ='输入') 750 751,如果y不为None:
〜\ Anaconda3 \ lib \ site-packages \ keras \ engine \ training_utils.py在 standardize_input_data(数据,名称,形状,check_batch_axis, exception_prefix) 125':期望的'+名称[i] +'具有'+ 126 str(len(shape))+'尺寸,但得到数组' -> 127'具有形状'+ str(data_shape)) 128如果不是check_batch_axis: 129 data_shape = data_shape [1:]
ValueError:检查输入时出错:预期lstm_42_input具有 3维,但数组的形状为(4,11)
答案 0 :(得分:1)
是重塑数据的问题。用于重塑Error when checking model input: expected lstm_1_input to have 3 dimensions, but got array with shape (339732, 29)和https://github.com/keras-team/keras/issues/5214。在python数组中,[
和]
的数目表示数组的维数
TimeDistributed
层在您的代码中至少需要两个 个时间步,在timestep=3
下面的代码中使用,因为33不能被2整除。通常,{ {1}}层用于实现一对多和一对多配置,请参见https://github.com/keras-team/keras/issues/1029
以下代码有效,对 1个样本(batch_size),3个时间步长,11个功能进行了重塑:
TimeDistributed