Python 当我想要在keras中拟合模型时,列出索引超出范围错误

Python 当我想要在keras中拟合模型时,列出索引超出范围错误,python,keras,deep-learning,reinforcement-learning,keras-layer,Python,Keras,Deep Learning,Reinforcement Learning,Keras Layer,这是我用keras编写的代码 import keras from keras import layers from keras import Sequential from keras.layers import Dense, Flatten import numpy as np from keras.engine.topology import Input from keras.engine.training import Model class _Model: def __init__

这是我用keras编写的代码

import keras
from keras import layers
from keras import Sequential
from keras.layers import Dense, Flatten
import numpy as np
from keras.engine.topology import Input
from keras.engine.training import Model

class _Model:
  def __init__(self,state,n_dims, n_action):
    self.n_action=n_action
    self.n_dims=n_dims
    self.state=state
    self.model=self.build_model()
  def build_model(self):
    inx=model=Input((10,16))
    model=Flatten()(model)
    model=Dense(512, activation=None)(model)
    model=Dense(512, activation=None)(model)
    p_model=Dense(self.n_action, activation='sigmoid')(model)
    v_model=Dense(1, activation='tanh')(model)
    _model=Model(inx,[p_model,v_model])
    losses = ['categorical_crossentropy', 'mean_squared_error']
    _model.compile(loss=losses, optimizer='adam')
    print(_model.summary())
    return _model
  def predict(self,state):
    return self.model.predict(state)
  def train(self, state, action_probability, leaf_value):
    batch_size=11
    state=np.array(state)
    action_probability=np.array(action_probability)
    leaf_value=np.array(leaf_value)
    self.model.fit(state, [action_probability, leaf_value],batch_size=batch_size,verbose=1)
    loss=self.model.evaluate(state, [action_probability, leaf_value],batch_size=batch_size,verbose=0)
    return loss[0]

state=[ 4321432141243124,
        1423123424143213,
        4321432143213421,
        4321431241324323,
        1243121234214334,
        4123123421342314,
        4321432434212412,
        4121432121121343,
        4123413412412321,
        4123413412413431,
]
m=_Model(state,16,4)
m.train(state,[0.1,0.5,0.4,0.7],0.4)
此实现适用于alphago zero。我正在尝试实现有两个输出的模型。这两个值(P,v),P是行动概率,v是获胜概率。 有什么问题吗?这个代码有什么问题? 错误显示列表超出了索引,但我不知道是哪个列表。我应该更改输入形状吗

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-9-c5b4b76d5be5> in <module>()
     48 ]
     49 m=_Model(state,16,4)
---> 50 m.train(state,[0.1,0.5,0.4,0.7],0.4)

6 frames
<ipython-input-9-c5b4b76d5be5> in train(self, state, action_probability, leaf_value)
     32     action_probability=np.array(action_probability)
     33     leaf_value=np.array(leaf_value)
---> 34     self.model.fit(state, [action_probability, leaf_value],batch_size=batch_size,verbose=1)
     35     loss=self.model.evaluate(state, [action_probability, leaf_value],batch_size=batch_size,verbose=0)
     36     return loss[0]

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in _method_wrapper(self, *args, **kwargs)
    106   def _method_wrapper(self, *args, **kwargs):
    107     if not self._in_multi_worker_mode():  # pylint: disable=protected-access
--> 108       return method(self, *args, **kwargs)
    109 
    110     # Running inside `run_distribute_coordinator` already.

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1061           use_multiprocessing=use_multiprocessing,
   1062           model=self,
-> 1063           steps_per_execution=self._steps_per_execution)
   1064 
   1065       # Container that configures and calls `tf.keras.Callback`s.

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/data_adapter.py in __init__(self, x, y, sample_weight, batch_size, steps_per_epoch, initial_epoch, epochs, shuffle, class_weight, max_queue_size, workers, use_multiprocessing, model, steps_per_execution)
   1115         use_multiprocessing=use_multiprocessing,
   1116         distribution_strategy=ds_context.get_strategy(),
-> 1117         model=model)
   1118 
   1119     strategy = ds_context.get_strategy()

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/data_adapter.py in __init__(self, x, y, sample_weights, sample_weight_modes, batch_size, epochs, steps, shuffle, **kwargs)
    273     inputs = pack_x_y_sample_weight(x, y, sample_weights)
    274 
--> 275     num_samples = set(int(i.shape[0]) for i in nest.flatten(inputs))
    276     if len(num_samples) > 1:
    277       msg = "Data cardinality is ambiguous:\n"

/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/data_adapter.py in <genexpr>(.0)
    273     inputs = pack_x_y_sample_weight(x, y, sample_weights)
    274 
--> 275     num_samples = set(int(i.shape[0]) for i in nest.flatten(inputs))
    276     if len(num_samples) > 1:
    277       msg = "Data cardinality is ambiguous:\n"

/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/tensor_shape.py in __getitem__(self, key)
    885       else:
    886         if self._v2_behavior:
--> 887           return self._dims[key].value
    888         else:
    889           return self._dims[key]

IndexError: list index out of range
---------------------------------------------------------------------------
索引器回溯(最后一次最近调用)
在()
48 ]
49 m=_模型(州,16,4)
--->50米列车(状态[0.1,0.5,0.4,0.7],0.4)
6帧
列车内(自身、状态、行动概率、叶值)
32动作概率=np.数组(动作概率)
33叶值=np.数组(叶值)
--->34 self.model.fit(状态[动作概率,叶值],批次大小=批次大小,详细度=1)
35损失=自我。模型。评估(状态[行动概率,叶值],批次大小=批次大小,详细程度=0)
36退货损失[0]
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in_method_包装(self,*args,**kwargs)
106定义方法包装(self,*args,**kwargs):
107如果不是self._处于_multi_worker_模式():#pylint:disable=受保护的访问
-->108返回方法(self、*args、**kwargs)
109
110#已经在“运行分配协调器”内部运行了。
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/training.py in fit(self、x、y、批大小、历元、冗余、回调、验证拆分、验证数据、无序、类权重、样本权重、初始历元、每历元的步长、验证步骤、验证批量大小、验证队列频率、最大大小、工作人员、使用多处理)
1061使用多处理=使用多处理,
1062型号=自我,
->1063步每执行=自。_步每执行)
1064
1065#配置和调用`tf.keras.Callback`的容器。
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/data\u adapter.py in\uuuuuu init\uuuuuuuuu(self,x,y,sample\u weight,batch\u size,steps\u per\u epoch,initial\u epoch,epoch,shuffle,class\u weight,max\u queue\u size,worker,use\u多处理,model,steps\u per\u执行)
1115使用多处理=使用多处理,
1116 distribution_strategy=ds_context.get_strategy(),
->1117型号=型号)
1118
1119 strategy=ds_context.get_strategy()
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/data\u adapter.py in\uuuuuuuu init\uuuuuuuuuuuu(self、x、y、样本权重、样本权重、模式、批量大小、年代、步骤、洗牌、**kwargs)
273输入=包装x y样品重量(x,y,样品重量)
274
-->275 num_samples=set(int(i.shape[0]),用于嵌套中的i.flatte(输入))
276如果len(num_样本)>1:
277 msg=“数据基数不明确:\n”
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/data_adapter.py in(.0)
273输入=包装x y样品重量(x,y,样品重量)
274
-->275 num_samples=set(int(i.shape[0]),用于嵌套中的i.flatte(输入))
276如果len(num_样本)>1:
277 msg=“数据基数不明确:\n”
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/tensor\u shape.py in\uuuuuuuu getitem\uuuuuu(self,key)
885其他:
886如果自我行为:
-->887返回self.\u dims[key].值
888其他:
889返回自我。\u变暗[键]
索引器:列表索引超出范围

您正在为keras拟合方法提供1D数组,keras需要至少2D的所有输入和输出。试试这个


state=np.array(state)
state=np.reformate(state,(-1,state.shape[0]))
动作概率=np.数组(动作概率)
动作概率=np.重塑(动作概率,(-1,动作概率.shape[0]))
叶值=np.数组(叶值)
叶_值=np.重塑(叶_值,(-1,叶_值.shape[0]))

欢迎来到SO!请添加错误消息,包括对您的问题的回溯。我在model.fit之前附加了错误消息Use this