我目前正在尝试掌握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
答案 0 :(得分:0)
您有一个误解,Reshape
是执行整形操作的图层,它不会“返回形状”。它采用一个符号输入张量,并根据构造函数的形状返回经过重整的张量。
我们的代码中的问题是形状不正确,形状是带有整数的元组,似乎您的元组内部包含另一个元组,并且不支持。这段代码可以很好地作为示例:
x = Input((2,2))
>>> x
<tf.Tensor 'input_2:0' shape=(?, 2, 2) dtype=float32>
x = Reshape((2,2,1))(x)
>>> x
<tf.Tensor 'reshape_1/Reshape:0' shape=(?, 2, 2, 1) dtype=float32>