ValueError:检查目标时出错:预期density_49具有形状(9,3),但数组形状为(5,1)

时间:2019-10-04 23:01:31

标签: keras output lstm

您好一段时间以来一直在尝试让我的代码工作。每次我运行LSTM网络时。我得到错误。我尝试过重塑输出数组,添加平坦层并重塑输入数组。似乎没有任何作用。请帮忙。

正在生成数据集...

  File "doodle.py", line 42, in main
    exclude_regex_users(name_entries)
  File "doodle.py", line 32, in exclude_regex_users
    for name in name_entries:
ValueError: I/O operation on closed file.

此部分用于建模和运行LSTM网络 导入必要的库。

#This generates a dataset to test the LSTM network
from random import seed, sample, randint
from random import sample
def genDataMatrix(n):
    labels = ['bpsk', 'qpsk', 'gmsk', 'qam', 'cpm']
    arr_data = []
    arr_labels = []
    for i in range (1, n):
        a = []
        for i in range (1, 10):
            a.append(randint(0, 100))
        arr_data.append(a)
        arr_labels.append(labels[randint(0,4)])
    #print(arr_labels)
    return arr_data, arr_labels   

她是我的LSTM班级:

#Imports necessary libraries for the neural network code
import tensorflow as tf
import keras
from keras.layers.core import Dense, Activation, Dropout
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding, Flatten, LSTM
from keras import optimizers
#LSTM Class

接下来,我将标签设置为一键编码。 (请注意,这仍然在NN_LSTM类下)

class NN_LSTM: 
    def __init__ (self):
        """"""
    #This function splits the array into three sperate arrays
    def genTrainTest(self, arr):
         sep = int(arr.shape[0]/5)
         return np.split(arr, [sep*3, sep*4], axis = 0)

LSTM网络的主要功能。我认为问题出在这里:

#This code converts the text category labels to binary arrays via one hot encoding
def oneHotEncode(self, data):
    #Code from
    #https://machinelearningmastery.com/how-to-one-hot-encode-sequence-data-in-python/
    from numpy import array
    from numpy import argmax
    from sklearn.preprocessing import LabelEncoder
    from sklearn.preprocessing import OneHotEncoder
    # define example
    #data = ['cold', 'cold', 'warm', 'cold', 'hot', 'hot', 'warm', 'cold', 'warm', 'hot']
    values = array(data)
    #print(values)
    # integer encode
    label_encoder = LabelEncoder()
    integer_encoded = label_encoder.fit_transform(values)
    #print(integer_encoded)
    # binary encode
    onehot_encoder = OneHotEncoder(sparse=False)
    integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
    onehot_encoded = onehot_encoder.fit_transform(integer_encoded)
    #print(onehot_encoded)
    # invert first example
    inverted = label_encoder.inverse_transform([argmax(onehot_encoded[0, :])])
    #print("Text Value: ", inverted)
    return onehot_encoded

最后,在代码末尾,我运行信息:

def runLSTM_NN(self, x, y):
    """"""
    #Encondes labels as binary vectors for processing by the neural network
    y = self.oneHotEncode(y)

    #seperate train, test, and validation data
    train_x, test_x, validate_x = self.genTrainTest(np.array(x))
    train_y, test_y, validate_y = self.genTrainTest(np.array(y))

    #train_y_bin = keras.utils.to_categorical(train_y, 10) 

    train_x = np.asarray(train_x)
    train_y = np.asarray(train_y)
    test_x = np.asarray(test_x)
    test_y = np.asarray(test_y)
    validate_x = np.asarray(validate_x)
    validate_y = np.asarray(validate_y)

    train_x_reshape = train_x.reshape(train_x.shape[0], train_x.shape[1], 1)
    train_y_reshape = train_y.reshape(train_y.shape[0], train_y.shape[1], 1)

    model = Sequential()
    model.add(LSTM(1, return_sequences=True, input_shape=(train_x.shape[1], 1)))
    model.add(Dropout(0.2))
    #model.add(Flatten())
    #Add the layer for the output information. 
    #The first number refers  to the number of neurons or output catogories. 
    model.add(Dense(3, activation='softmax'))
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    print(model.summary())
    model.fit(train_x_reshape, train_y_reshape, epochs=3, batch_size=64, verbose = 0)
    model.fit()        
    """"""

0 个答案:

没有答案