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 Traceback(最近一次调用last)in()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,epochs,verbose,callbacks,validation_split,validation_data,shuffle,class_weight ,sample_weight,initial_epoch,steps_per_epoch,validation_steps,** kwargs)948 sample_weight = sample_weight,949 class_weight = class_weight, - > 950 batch_size = batch_size)951#准备验证数据 . 952 do_validation = False〜\ Anaconda3 \ lib \ site-packages \ keras \ engine \ training.py in _standardize_user_data(self,x,y,sample_weight,class_weight,check_array_lengths,batch_size)747 feed_input_shapes,748 check_batch_axis = False,#Do not强制执行批量大小 . - > 749 exception_prefix ='input')750 751如果y不是None:〜\ Anaconda3 \ lib \ site-packages \ keras \ engine \ training_utils.py in standardize_input_data(data,names,shapes,check_batch_axis,exception_prefix)125' :期望'names [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)
1 回答
在代码中是重塑数据的问题 . 用于重塑cf 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整除 . 通常TimeDistributed
图层用于实现一对多和多对多配置, cf https://github.com/keras-team/keras/issues/1029以下代码正在运行,重新整形是针对1个样本(batch_size),3个步骤,11个特征完成的: