加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Keras LSTM的“无效的y形状”w / return_sequences =

发布时间:2020-12-20 13:16:55 所属栏目:Python 来源:网络整理
导读:我有一个我试图分类的序列,使用带有return_sequences = True的Keras LSTM.我有’数据’和’标签’数据集,它们都是相同的形状 – 按位置排列的二维矩阵和按时间间隔排列的列(单元格值是我的’信号’特征).因此RNN w / return_sequences = True似乎是一种直观
我有一个我试图分类的序列,使用带有return_sequences = True的Keras LSTM.我有’数据’和’标签’数据集,它们都是相同的形状 – 按位置排列的二维矩阵和按时间间隔排列的列(单元格值是我的’信号’特征).因此RNN w / return_sequences = True似乎是一种直观的方法.

在将我的数据(X)和标签(Y)重塑为形状(行,列,1)的3D张量后,我调用model.fit(X,Y)但得到以下错误:

ValueError(‘Invalid shape for y’)

它指出了类KerasClassifier()的fit方法的代码,该方法检查len(y.shape)== 2.

好的,也许我应该将我的2D’X’重塑为3D Tensor of shape(行,1),但是将我的标签留作2D用于sklearn界面?但是当我尝试时,我得到另一个Keras错误:

ValueError: Error when checking model target: expected lstm_17 to have
3 dimensions,but got array with shape (500,2880)

…那么如何使Sklearn风格的Keras RNN返回序列呢? Keras的不同部分似乎要求我的目标是2D和3D.或者(更有可能)我误解了一些东西.


这是一个可重现的代码示例:

from keras.layers import LSTM
from keras.wrappers.scikit_learn import KerasClassifier

# Raw Data/Targets    
X = np.array([1,2,3,4,5,6,7,8,9,10,11,12]).reshape(3,4)
Y = np.array([1,1,1]).reshape(3,4)

# Convert X to 3D tensor per Keras doc for recurrent layers
X = X.reshape(X.shape[0],X.shape[1],1)

# .fit() at bottom will throw an error whether or not this line is used to reshape Y
to reshape Y
Y = Y.reshape(Y.shape[0],Y.shape[1],1)


# Define function to return compiled Keras Model (to pass to Sklearn API)
def keras_rnn(timesteps,num_features):
    '''Function to return compiled Keras Classifier to pass to sklearn wrapper'''

    model = Sequential()
    model.add(LSTM(8,return_sequences=True,input_shape=(timesteps,num_features)))
    model.add(LSTM(1,activation = 'sigmoid'))

    model.compile(optimizer = 'RMSprop',loss = 'categorical_crossentropy')
    return model

# Convert compiled Keras model to Scikit-learn-style classifier (compatible w/ sklearn model-tuning methods)
rnn_sklearn = KerasClassifier(build_fn=keras_rnn,timesteps=4,num_features=1) 

# Fit RNN Model to Data,Target                            
rnn_sklearn.fit(X,Y)

ValueError: Invalid shape for y

解决方法

此代码适用于Keras 2.0.2:

import numpy as np
from keras.models import Sequential
from keras.layers import LSTM,Flatten
from keras.wrappers.scikit_learn import KerasClassifier

# Raw Data/Targets    
X = np.array([1,1)

# .fit() at bottom will throw an error whether or not this line is used to reshape Y to reshape Y
Y = Y.reshape(Y.shape[0],loss = 'binary_crossentropy')
    return model

# Convert compiled Keras model to Scikit-learn-style classifier (compatible w/ sklearn model-tuning methods)
rnn_sklearn = KerasClassifier(build_fn=keras_rnn,Y)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读