【发布时间】:2019-07-27 10:24:29
【问题描述】:
我目前正在尝试掌握 Surag Nair 关于神经网络的工作。
在(https://github.com/suragnair/alpha-zero-general/blob/master/othello/keras/OthelloNNet.py)中有这行代码:
self.input_boards = keras.Input(shape=(self.board_x, self.board_y)) # s: batch_size x board_x x board_y
x_image = keras.layers.Reshape((self.board.grid_shape, 1))(self.input_boards) # ??
x_image = (shape)(tensor) 如何是一个有效的呼叫?
输入返回一个张量,重塑返回一个形状。
据我了解,张量是一个潜在的高级矩阵和一个操作,可能会在以后完成。
但如果我想稍后调用它,输入形状必须是张量的参数,而不是相反?
我试过了,结果是这样的:
class Connect4NN():
def __init__(self, board, args):
self.board = board
self.action_size = board.action_space
self.args = args
#Neural Net
self.input_boards = keras.Input(shape = (self.board.grid_shape) ) #shape: batch size x X x Y (batch size not needed here)
#tf.Tensorobject represents a partially defined computation that will eventually produce a value.
self.input_boards = keras.Input(shape=self.board.grid_shape) # s: batch_size x board_x x board_y
x_image = keras.layers.Reshape((self.board.grid_shape, 1))(self.input_boards) # ??
print("input_boards : {}".format(self.input_boards))
print("x_image: {}".format(x_image))
return
在控制台中:
b = Connect4()
args = "bla"
nn = Connect4NN(b,args)
Traceback (most recent call last):
File "<ipython-input-20-7d7efde846db>", line 1, in <module>
nn = Connect4NN(b,args)
File "D:/Programming/code/conn4neuralnet.py", line 22, in __init__
x_image = keras.layers.Reshape((self.board.grid_shape, 1))(self.input_boards) # ??
File "D:\Anaconda\lib\site-packages\keras\engine\base_layer.py", line 457, in __call__
output = self.call(inputs, **kwargs)
File "D:\Anaconda\lib\site-packages\keras\layers\core.py", line 401, in call
return K.reshape(inputs, (K.shape(inputs)[0],) + self.target_shape)
File "D:\Anaconda\lib\site-packages\keras\backend\tensorflow_backend.py", line 1969, in reshape
return tf.reshape(x, shape)
File "D:\Anaconda\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 7178, in reshape
"Reshape", tensor=tensor, shape=shape, name=name)
File "D:\Anaconda\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 529, in _apply_op_helper
(input_name, err))
ValueError: Tried to convert 'shape' to a tensor and failed. Error: Shapes must be equal rank, but are 1 and 0
From merging shape 1 with other shapes. for 'reshape_1/Reshape/packed' (op: 'Pack') with input shapes: [], [2], [].
添加我的 Connect4 位板实现的相关部分:
class Connect4():
def __init__(self):
self.board = [0, 0]
self.height = [0,7,14,21,28,35,42]
self.nn_height = [0,6,12,18,24,30,36]
self.counter = 0
self.moves = []
self.nn_board = np.zeros(shape = 42, dtype = int)
self.grid_shape = (6,7)
self.action_space = 7
【问题讨论】:
-
self.board.grid_shape的值是多少?
-
返回一个 (6,7) 形式的元组
-
然后产生 (6,7,1) 你应该做 self.board.grid_shape + (1,)
-
好的,谢谢!我只是直接在板上添加了一个 x 和 y 组件,以使其更清晰,但这也可以。我对python语法还不是很熟悉,所以像添加元组、尾随逗号、星号等所有这些事情真的很难:P
标签: python tensorflow keras