【问题标题】:Keras Sequential model input shapeKeras 序列模型输入形状
【发布时间】:2019-12-12 04:49:27
【问题描述】:

我想训练一个基于 numpy 数组的神经网络,该数组有 4 个条目作为 X 数据,另一个数组有一个条目作为 y 数据。

X_train = [x1, x2, x3, x4]
y_train = [y1]

我想到了一件相当简单的事情,但我无法让输入形状工作。我还发现关于输入形状如何工作的信息非常少:你必须只指定 X 数据吗? y 数据呢?

我已经尝试设置 input_dim = 4,因为这是第一个合乎逻辑的事情,但我得到了以下错误: Error when checking input: expected dense_1_input to have shape (4,) but got array with shape (1,)

然后我尝试设置 input_dim = (4, 1),因为我认为 y 数据导致了该问题。但我又收到一条错误消息: Error when checking input: expected dense_1_input to have 3 dimensions, but got array with shape (4, 1)

代码如下:

# importing the packages
import gym
import numpy as np
from collections import deque

from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
from keras.wrappers.scikit_learn import KerasRegressor

from joblib import Parallel

# creating the environment
env = gym.make('CartPole-v1')

#defining global variables
lr=0.0001
decay=0.001
batch_size=None

# creating a deep learning model with keras
def model():
    model = Sequential()

    model.add(Dense(64, input_dim=4, activation='relu'))
    model.add(Dense(32, activation='relu'))
    model.add(Dense(16, activation='relu'))

    model.add(Dense(1, activation='sigmoid'))

    model.compile(Adam(lr=lr, decay=decay), loss='mse')
    model.summary()
    return model

# running the game
for i_episodes in range(200):
    env.reset()
    for i in range(100):
        env.render()
        action = env.action_space.sample()
        observation, reward, done, info = env.step(action)

        # observation = ndarray float64
        # reward = float
        # done = bool
        # action = int
        # info = empty

        observation = np.asarray(observation)
        reward = np.asarray(reward)
        action = np.asarray(action)

        # print(observation.dtype, reward.dtype, action.dtype)
        # print(observation.shape, action.shape)

        estimator = KerasRegressor(build_fn=model, epochs=30, batch_size=3, verbose=1)
        estimator.fit(observation, action)

        if done:
            break
env.close()

如果有人能解释输入形状的工作原理,将不胜感激。

【问题讨论】:

    标签: python keras


    【解决方案1】:

    兄弟!对于第二个错误,请使用此代码。现在它对我来说运行良好。

    X=[]
    y=[]
    
    # creating the environment
    env = gym.make('CartPole-v1')
    
    #defining global variables
    lr=0.0001
    decay=0.001
    batch_size=None
    
    # creating a deep learning model with keras
    def model():
        model = Sequential()
    
        model.add(Dense(64, input_dim=4, activation='relu'))
        model.add(Dense(32, activation='relu'))
        model.add(Dense(16, activation='relu'))
    
        model.add(Dense(1, activation='sigmoid'))
    
        model.compile(Adam(lr=lr, decay=decay), loss='mse')
        model.summary()
        return model
    
    # running the game
    for i_episodes in range(200):
        env.reset()
        for i in range(100):
            #env.render()
            action = env.action_space.sample()
            observation, reward, done, info = env.step(action)
    
    
            observation = np.asarray(observation)
            reward = np.asarray(reward)
            action = np.asarray(action)
    
            X.append( observation)
            y.append(action)
    
    
            if done:
                break
    env.close()
    
    
    X=np.asarray(X)
    y=np.asarray(y)
    estimator = KerasRegressor(build_fn=model, epochs=30, batch_size=3, verbose=1)
    estimator.fit(X, y)
    

    【讨论】:

    • @Guille 发布了一个同样有效的答案 - 我尝试了你的答案,现在这种方法也适用于我。感谢您的回答 - 他们真的很有帮助。
    • yaa 这是两种不同的方法 :) 我很高兴您的问题得到解决。有一个美好的一天兄弟。请为适合您的答案投票:)
    【解决方案2】:

    试试这段代码。当您要使用神经网络解决任何回归问题时,您必须指定输入维度。因此,在输入维度中,您必须将要提供给网络的列数传递给您。

      def baseline_model():  
        model = Sequential()
    
        model.add(Dense(64, input_dim=4, activation='relu'))
        model.add(Dense(32, activation='relu'))
        model.add(Dense(16, activation='relu'))
    
        model.add(Dense(1, activation='sigmoid'))
    
        model.compile(Adam(lr=lr, decay=decay), loss='mse')
        model.summary()
        return model
    

    现在您必须将其包装在 keras 回归器类中,以便 keras 知道这是您要解决的回归问题。

    estimator = KerasRegressor(build_fn=baseline_model, epochs=30, batch_size=3, verbose=1)
    

    如果您需要更多关于如何使用 keras 解决回归问题的信息,而不是查看下面的我的笔记本,您将从中获得帮助。

    在调用 Fit 函数之前也要使用这一行

    (observation=observation.reshape(1,4))
    

    链接:Solve Regression problem with Keras Neural Network

    【讨论】:

    • 实际上,当我调用 estimator.fit(X, y) 时也会出现同样的错误。
    • 请看下面的笔记本!我已经为你附上了那个笔记本!
    • 这就是全部代码。这个想法基本上是训练一个神经网络来预测平衡车的最佳动作。
    • 您在哪个数据集上工作?我会尝试在 Kaggle 上做同样的事情并调试以找出错误。
    • 实际上,它不是数据集——或者它是在运行时生成的。 Gym 是一个 Python 游戏库,您可以在其中实现强化学习算法。 for 循环启动游戏并遍历它。数据在 `observation, reward, done, info = env.step(action)` 生成,然后转换成 numpy 数组。
    【解决方案3】:

    输入形状总是期望批量大小作为第一维。

    例如,在您的情况下,以下图层不需要形状为 (4,) 的数组

    Dense(64, input_dim=4, activation='relu')
    

    这个密集层的输入形状是一个形状为 (n, 4) 的张量,其中 n 是批量大小。

    要将您的observation 传递给模型,您首先需要按如下方式扩展其尺寸:​​

    observation = np.asarray(observation)
    observation = np.expand_dims(observation, axis=0) # From shape (4,) to (1, 4)
    estimator.fit(observation, action)
    

    您的代码应如下所示。

    # creating a deep learning model with keras
    def build_model():
        model = Sequential()
    
        model.add(Dense(64, input_dim=4, activation='relu'))
        model.add(Dense(32, activation='relu'))
        model.add(Dense(16, activation='relu'))
    
        model.add(Dense(1, activation='sigmoid'))
    
        model.compile(Adam(lr=lr, decay=decay), loss='mse')
        model.summary()
        return model
    
    model = build_model()
    
    # running the game
    for i_episodes in range(200):
        env.reset()
        for i in range(100):
            env.render()
            action = env.action_space.sample()
            observation, reward, done, info = env.step(action)
    
            # observation = ndarray float64
            # reward = float
            # done = bool
            # action = int
            # info = empty
    
            observation = np.asarray(observation)
            reward = np.asarray(reward)
            action = np.asarray(action)
    
            model.fit(np.expand_dims(observation, axis=0), np.expand_dims(action, axis=0))
    
    

    如果你正在学习 DQN,请查看article

    【讨论】:

    • 我尝试了类似的方法,将观察结果重塑为 (-1, 4) 但这不起作用。当我尝试扩大暗淡时,我也得到一个错误:Error when checking target: expected dense_4 to have 2 dimensions, but got array with shape ()
    • 您需要执行相同的操作。另外,您为什么要使用估算器?我可以看到您将批量大小设置为 30,但您只提供了 1 个观察实例。检查编辑的答案
    • 完美!完美运行。估计器是由@SohaibAnwaar 建议的,实际上因为这是一个回归任务,所以是有道理的。但我对深度学习还很陌生,所以 - 是的 ;)
    • 顺便说一句很棒的文章
    猜你喜欢
    • 2017-12-24
    • 2019-01-26
    • 2020-09-26
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    • 2016-11-09
    • 2018-03-16
    • 2021-05-24
    相关资源
    最近更新 更多