我正在尝试创建一个具有特定值的记录数组。但是,我注意到无法正确设置记录数组的值。记录数组具有三个字段:“startstate”(一个标量)、“action”(一个 4x1 数组)和“transition”(一个 4x2 数组)。“startstate”可以很容易地设置。然而,对于其他两个字段,当我尝试使用另一个数组设置它们的值时,似乎只能正确设置第一个元素。下面的代码说明了这个问题
import numpy as np
NUM_STATES = 4
NUM_ACTIONS = 2
NUM_OBS = 2
strategy_id = 62605133
new_auto, = np.zeros(1,dtype = [('startstate', np.int32),
('action', np.int32, NUM_STATES), ('transition', np.int32, (NUM_STATES, NUM_OBS))])
start_id = strategy_id%10
action_id = np.int(strategy_id/10)%100
transition_id = np.int(strategy_id/1000)
new_auto['startstate'] = start_id
print new_auto['startstate'],start_id
action_array = new_auto['action'].copy()
for i in xrange(NUM_STATES):
action_array[-1-i] = action_id%NUM_ACTIONS
action_id = np.int(action_id/NUM_ACTIONS)
new_auto['action'] = action_array.copy()
print new_auto['action']
print action_array
transition_array = new_auto['transition'].flatten().copy()
for i in xrange(NUM_STATES*2):
transition_array[-1-i] = transition_id%NUM_STATES
transition_id = np.int(transition_id/NUM_STATES)
new_auto['transition'] = transition_array.reshape((NUM_STATES,NUM_OBS)).copy()
print new_auto['transition']
print transition_array.reshape((NUM_STATES,NUM_OBS))
代码的输出:
startstate
3 3
actions
[1 0 0 0]
[1 1 0 1]
transitions
[[3 0]
[0 0]
[0 0]
[0 0]]
[[3 3]
[1 0]
[2 0]
[3 1]]
对于每个字段,第一个数组给出实际值,而第二个数组给出正确值。理论上,它们应该是相同的,因为我已经使用以下设置了值:
new_auto['action'] = action_array.copy()
new_auto['transition'] = transition_array.reshape((NUM_STATES,NUM_OBS)).copy()
任何人都可以帮助确定导致此问题的原因吗?我使用的 numpy 版本是 1.9.2