【问题标题】:How to specify the Input shape for GRU model on keras functional api?如何在 keras 功能 api 上指定 GRU 模型的输入形状?
【发布时间】:2021-11-19 20:16:23
【问题描述】:

我有一个二维矩阵,其中特征是列,样本是行(178136 个特征和 416 个样本)。我转置了这个矩阵,然后通过使用以下代码创建一个包含 3 个该矩阵的重复副本的 NumPy 数组,将该矩阵转换为 3d。

matrix = matrix.transpose()
dataset = np.array([matrix,matrix,matrix])

维度如下:(3,178136,416) 其中 3 是顺序模型的时间步数,178136 是特征,416 是样本数。

我无法为我要训练的模型指定 Keras 函数 api 的输入形状。 下面是我写的代码:

import numpy as np
import tensorflow
from tensorflow import keras
from tensorflow.keras import layers

inputdata = np.load('filepath')
outputdata = np.load('filepath')
# loads data from .npy files
input_size = 178136
# The input size is the number of genes in the dataset.
output_size = 155551
# The output size is the number of protein coding genes in the dataset.

inputs = keras.Input(shape=(3,input_size))
# This is the input layer of the neural network.

x = layers.GRU(input_size, return_sequences=True)(inputs)
# This is the first hidden layer of the GRU neural network.

x = layers.GRU(input_size, return_sequences=True)(x)
# This is the second hidden layer of the GRU neural network.

outputs = layers.Dense(output_size)(x)
# This is the output layer of the GRU neural network.

model = keras.Model(inputs=inputs, outputs=outputs, name="GRU_for_GRE_Modeling")
# This code specifies the input and output layers of the neural network.

model.compile(optimizer=keras.optimizers.Adam(), loss="categorical_crossentropy",metrics = ['accuracy'])
# This code specifies the optimizer, loss, and evaluation metrics for the neural network.
print('model compiled')
csv_logger = tensorflow.keras.callbacks.CSVLogger('evaluation_metrics.csv', separator=",", append=False)
history = model.fit(inputdata, outputdata, batch_size=1, epochs=1000000, callbacks=csv_logger, validation_split=.25)

# This code actually trains the neural network and saves the evaluation metrics.

model.save('filepath')

# This code saves the trained neural network to a specified path.

这是我在尝试运行此代码时不断收到的错误:

    history = model.fit(inputdata, outputdata, batch_size=1, epochs=1000000, callbacks=csv_logger, validation_split=.25)
  File "/data/Libs/tensorflow/1.12.2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 1536, in fit
    validation_split=validation_split)
  File "/data/Libs/tensorflow/1.12.2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 992, in _standardize_user_data
    class_weight, batch_size)
  File "/data/Libs/tensorflow/1.12.2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 1117, in _standardize_weights
    exception_prefix='input')
  File "/data/Libs/tensorflow/1.12.2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_utils.py", line 332, in standardize_input_data
    ' but got array with shape ' + str(data_shape))
ValueError: Error when checking input: expected input_1 to have shape (3, 178136) but got array with shape (178136, 416)

有人可以帮我解决这个问题吗? 我浏览了所有文档,但似乎找不到如何指定样本数量以使此错误消失

【问题讨论】:

    标签: python numpy tensorflow keras deep-learning


    【解决方案1】:

    我试图复制您的问题,但它按预期工作

    import numpy as np
    import tensorflow
    from tensorflow import keras
    from tensorflow.keras import layers
    
    
    #inputdata = np.load('filepath')
    #outputdata = np.load('filepath')
    # loads data from .npy files
    input_size = 100
    # The input size is the number of genes in the dataset.
    output_size = 80
    # The output size is the number of protein coding genes in the dataset.
    
    
        inputs = keras.Input(shape=(3,input_size))
        # This is the input layer of the neural network.
        
        x = layers.GRU(input_size, return_sequences=True)(inputs)
        
        x = layers.GRU(input_size, return_sequences=True)(x)
        
        
        outputs = layers.Dense(output_size)(x)
        # This is the output layer of the GRU neural network.
        
        model = keras.Model(inputs=inputs, outputs=outputs, name="GRU_for_GRE_Modeling")
        # This code specifies the input and output layers of the neural network.
        
        model.compile(optimizer=keras.optimizers.Adam(), loss="categorical_crossentropy",metrics = ['accuracy'])
        # This code specifies the optimizer, loss, and evaluation metrics for the neural network.
        print('model compiled')
        model.summary()
        #csv_logger = tensorflow.keras.callbacks.CSVLogger('evaluation_metrics.csv', separator=",", append=False)
        #history = model.fit(inputdata, outputdata, batch_size=1, epochs=1000000, callbacks=csv_logger, validation_split=.25)
    

    输出:model.summary 显示正确的输入形状

    model compiled
    Model: "GRU_for_GRE_Modeling"
    _________________________________________________________________
    Layer (type)                 Output Shape              Param #   
    =================================================================
    input_7 (InputLayer)         [(None, 3, 100)]          0         
    _________________________________________________________________
    gru_10 (GRU)                 (None, 3, 100)            60600     
    _________________________________________________________________
    gru_11 (GRU)                 (None, 3, 100)            60600     
    _________________________________________________________________
    dense_2 (Dense)              (None, 3, 80)             8080      
    =================================================================
    Total params: 129,280
    Trainable params: 129,280
    Non-trainable params: 0
    

    【讨论】:

      猜你喜欢
      • 2016-11-09
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2018-01-08
      • 2019-01-26
      • 2019-12-12
      • 2019-05-07
      相关资源
      最近更新 更多