AttributeError:“函数”对象没有属性“预测”。凯拉斯

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

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:检查输入时出错:预期density_1_input具有   3维,但数组的形状为(16,1)

当我以形状(1,16)运行它时,出现以下错误:

  

ValueError:检查输入时出错:预期density_1_input具有   3维,但形状为(1,16)

在这种情况下我该怎么办?

levisor 回答:AttributeError:“函数”对象没有属性“预测”。凯拉斯

在最后一个代码块中,

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))

,网络给出了输出。

本文链接:https://www.f2er.com/3166648.html

大家都在问