AttributeError: 'function' object has no attribute 'predict'. Keras

AttributeError: 'function' object has no attribute 'predict'. Keras

我正在研究 RL 问题,我创建了一个 class 来初始化模型和其他参数。代码如下:

class Agent:
    def __init__(self, state_size, is_eval=False, model_name=""):
        self.state_size = state_size
        self.action_size = 20 # measurement, CNOT, bit-flip
        self.memory = deque(maxlen=1000)
        self.inventory = []
        self.model_name = model_name
        self.is_eval = is_eval
        self.done = False

        self.gamma = 0.95
        self.epsilon = 1.0
        self.epsilon_min = 0.01
        self.epsilon_decay = 0.995


    def model(self):
        model = Sequential()
        model.add(Dense(units=16, input_dim=self.state_size, activation="relu"))
        model.add(Dense(units=32, activation="relu"))
        model.add(Dense(units=8, activation="relu"))
        model.add(Dense(self.action_size, activation="softmax"))
        model.compile(loss="categorical_crossentropy", optimizer=Adam(lr=0.003))
        return model

    def act(self, state):
        options = self.model.predict(state)
        return np.argmax(options[0]), options

我只想 运行 它只进行一次迭代,因此我创建了一个对象并传递了一个长度为 16 的向量,如下所示:

agent = Agent(density.flatten().shape)
state = density.flatten()
action, probs = agent.act(state)

但是,我收到以下错误:

AttributeError                       Traceback (most recent call last) <ipython-input-14-4f0ff0c40f49> in <module>
----> 1 action, probs = agent.act(state)

<ipython-input-10-562aaf040521> in act(self, state)
     39 #             return random.randrange(self.action_size)
     40 #         model = self.model()
---> 41         options = self.model.predict(state)
     42         return np.argmax(options[0]), options
     43 

AttributeError: 'function' object has no attribute 'predict'

有什么问题吗?我也检查了一些其他人的代码,比如this,我认为我的也很相似。

告诉我。

编辑:

我将 Dense 中的参数从 input_dim 更改为 input_shape,将 self.model.predict(state) 更改为 self.model().predict(state)

现在,当我 运行 一个形状为 (16,1) 的输入数据的 NN 时,我得到以下错误:

ValueError: Error when checking input: expected dense_1_input to have 3 dimensions, but got array with shape (16, 1)

当我 运行 它的形状为 (1,16) 时,我得到以下错误:

ValueError: Error when checking input: expected dense_1_input to have 3 dimensions, but got array with shape (1, 16)

遇到这种情况怎么办?

在最后一个代码块中,

def act(self, state):
        options = self.model.predict(state)
        return np.argmax(options[0]), options

self.model 是一个返回模型的函数,它应该是 self.model().predict(state)

我用了np.reshape。所以在这种情况下,我做了

density_test = np.reshape(density.flatten(), (1,1,16))

网络给出了输出。