繁体   English   中英

如何在 keras 功能 api 上指定 GRU model 的输入形状?

[英]How to specify the Input shape for GRU model on keras functional api?

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

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

维度变为以下内容:(3,178136,416) 其中 3 是连续 model 的时间步数,178136 是特征,416 是样本数。

我无法为 Keras function api 指定我正在尝试训练的 model 的输入形状。 下面是我写的代码:

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)

有人可以帮我解决这个问题吗? 我已经阅读了所有文档,但似乎无法找到如何指定样本数来消除此错误 go

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

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)

Output: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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM