Flattens the input tensor into a 2D matrix. If input tensor has shape `(d_0, d_1, ... d_n)` then the output will have shape `(d_0 X d_1 ... d_(axis-1), d_axis X d_(axis+1) ... X dn)`.
| 1370 | |
| 1371 | |
| 1372 | class Flatten(Operator): |
| 1373 | """ |
| 1374 | Flattens the input tensor into a 2D matrix. If input tensor has shape |
| 1375 | `(d_0, d_1, ... d_n)` then the output will have shape `(d_0 X d_1 ... |
| 1376 | d_(axis-1), d_axis X d_(axis+1) ... X dn)`. |
| 1377 | """ |
| 1378 | |
| 1379 | def __init__(self, axis=1): |
| 1380 | """ |
| 1381 | Args: |
| 1382 | axis (int): Indicate up to which input dimensions (exclusive) |
| 1383 | should be flattened to the outer dimension of the output. The |
| 1384 | value for axis must be in the range [-r, r], where r is the |
| 1385 | rank of the input tensor. Negative value means counting |
| 1386 | dimensions from the back. When axis = 0, the shape of the |
| 1387 | output tensor is `(1, (d_0 X d_1 ... d_n)`, where the shape |
| 1388 | of the input tensor is `(d_0, d_1, ... d_n)`. |
| 1389 | Returns: |
| 1390 | the result CTensor |
| 1391 | """ |
| 1392 | super(Flatten, self).__init__() |
| 1393 | self.axis = axis |
| 1394 | |
| 1395 | def forward(self, x): |
| 1396 | """ |
| 1397 | Args: |
| 1398 | x (CTensor): the input tensor |
| 1399 | Returns: |
| 1400 | the result CTensor |
| 1401 | """ |
| 1402 | self.shape = list(x.shape()) |
| 1403 | shape, axis = self.shape, self.axis |
| 1404 | # the axis must be within this range (0, r-1) |
| 1405 | assert axis <= len( |
| 1406 | shape) - 1 or axis >= 0, "the axis must be within (0, %d-1)" % len( |
| 1407 | shape) |
| 1408 | # calculate the new shape |
| 1409 | new_shape = (1, int(np.prod(shape))) if axis == 0 else ( |
| 1410 | int(np.prod(shape[0:axis]).astype(int)), |
| 1411 | int(np.prod(shape[axis:]).astype(int))) |
| 1412 | y = singa.Reshape(x, new_shape) |
| 1413 | return y |
| 1414 | |
| 1415 | def backward(self, dy): |
| 1416 | """ |
| 1417 | Args: |
| 1418 | dy (CTensor): data for the dL / dy, L is the loss |
| 1419 | Returns: |
| 1420 | dx (CTensor): data for the dL / dx, L is the loss, |
| 1421 | """ |
| 1422 | dx = singa.Reshape(dy, self.shape) |
| 1423 | return dx |
| 1424 | |
| 1425 | |
| 1426 | def flatten(x, axis=1): |