File size: 14,402 Bytes
1f5470c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 | import math
import numpy as np
from keras.src import tree
from keras.src.api_export import keras_export
from keras.src.backend.common.backend_utils import canonicalize_axis
from keras.src.backend.common.backend_utils import to_tuple_or_list
def broadcast_shapes(shape1, shape2):
"""Broadcast input shapes to a unified shape.
Convert to list for mutability.
Args:
shape1: A tuple or list of integers.
shape2: A tuple or list of integers.
Returns:
output_shape (list of integers or `None`): The broadcasted shape.
Example:
>>> broadcast_shapes((5, 3), (1, 3))
[5, 3]
"""
shape1 = list(shape1)
shape2 = list(shape2)
origin_shape1 = shape1
origin_shape2 = shape2
if len(shape1) > len(shape2):
shape2 = [1] * (len(shape1) - len(shape2)) + shape2
if len(shape1) < len(shape2):
shape1 = [1] * (len(shape2) - len(shape1)) + shape1
output_shape = list(shape1)
for i in range(len(shape1)):
if shape1[i] == 1:
output_shape[i] = shape2[i]
elif shape1[i] is None:
output_shape[i] = None if shape2[i] == 1 else shape2[i]
else:
if shape2[i] == 1 or shape2[i] is None or shape2[i] == shape1[i]:
output_shape[i] = shape1[i]
else:
raise ValueError(
"Cannot broadcast shape, the failure dim has value "
f"{shape1[i]}, which cannot be broadcasted to {shape2[i]}. "
f"Input shapes are: {origin_shape1} and {origin_shape2}."
)
return output_shape
def compute_expand_dims_output_shape(input_shape, axis):
"""Compute the output shape for the `expand_dims` operation.
Args:
input_shape: Input shape.
axis: int or sequence of ints for the axis to expand.
Returns:
Tuple of ints: The output shape after the `expand_dims` operation.
"""
input_shape = list(input_shape)
if axis is None:
axis = len(input_shape)
axis = to_tuple_or_list(axis)
out_ndim = len(axis) + len(input_shape)
axis = [canonicalize_axis(a, out_ndim) for a in axis]
shape_iter = iter(input_shape)
new_shape = [
1 if ax in axis else next(shape_iter) for ax in range(out_ndim)
]
return tuple(new_shape)
def compute_pooling_output_shape(
input_shape,
pool_size,
strides,
padding="valid",
data_format="channels_last",
):
"""Computes the output shape of pooling operations.
Args:
input_shape: Input shape. Must be a tuple of integers.
pool_size: Size of the pooling operation. Must be a tuple of integers.
strides: Stride of the pooling operation. Must be a tuple of integers.
Defaults to `pool_size`.
padding: Padding method. Available methods are `"valid"` or `"same"`.
Defaults to `"valid"`.
data_format: String, either `"channels_last"` or `"channels_first"`.
The ordering of the dimensions in the inputs. `"channels_last"`
corresponds to inputs with shape `(batch, height, width, channels)`
while `"channels_first"` corresponds to inputs with shape
`(batch, channels, height, weight)`. Defaults to `"channels_last"`.
Returns:
Tuple of ints: The output shape of the pooling operation.
Examples:
# Basic usage with square pooling on a single image
>>> compute_pooling_output_shape((1, 4, 4, 1), (2, 2))
(1, 2, 2, 1)
# Strided pooling on a single image with strides different from pool_size
>>> compute_pooling_output_shape((1, 4, 4, 1), (2, 2), strides=(1, 1))
(1, 3, 3, 1)
# Pooling on a batch of images
>>> compute_pooling_output_shape((32, 4, 4, 3), (2, 2))
(32, 2, 2, 3)
"""
strides = pool_size if strides is None else strides
input_shape_origin = list(input_shape)
input_shape = np.array(input_shape)
if data_format == "channels_last":
spatial_shape = input_shape[1:-1]
else:
spatial_shape = input_shape[2:]
none_dims = []
for i in range(len(spatial_shape)):
if spatial_shape[i] is None:
# Set `None` shape to a manual value so that we can run numpy
# computation on `spatial_shape`.
spatial_shape[i] = -1
none_dims.append(i)
pool_size = np.array(pool_size)
if padding == "valid":
output_spatial_shape = (
np.floor((spatial_shape - pool_size) / strides) + 1
)
for i in range(len(output_spatial_shape)):
if i not in none_dims and output_spatial_shape[i] < 0:
raise ValueError(
"Computed output size would be negative. Received: "
f"`inputs.shape={input_shape}` and `pool_size={pool_size}`."
)
elif padding == "same":
output_spatial_shape = np.floor((spatial_shape - 1) / strides) + 1
else:
raise ValueError(
"Argument `padding` must be either 'valid' or 'same'. Received: "
f"padding={padding}"
)
output_spatial_shape = [int(i) for i in output_spatial_shape]
for i in none_dims:
output_spatial_shape[i] = None
output_spatial_shape = tuple(output_spatial_shape)
if data_format == "channels_last":
output_shape = (
(input_shape_origin[0],)
+ output_spatial_shape
+ (input_shape_origin[-1],)
)
else:
output_shape = (
input_shape_origin[0],
input_shape_origin[1],
) + output_spatial_shape
return output_shape
def compute_conv_output_shape(
input_shape,
filters,
kernel_size,
strides=1,
padding="valid",
data_format="channels_last",
dilation_rate=1,
):
"""Compute the output shape of conv ops."""
if data_format == "channels_last":
spatial_shape = input_shape[1:-1]
kernel_shape = kernel_size + (input_shape[-1], filters)
else:
spatial_shape = input_shape[2:]
kernel_shape = kernel_size + (input_shape[1], filters)
if len(kernel_shape) != len(input_shape):
raise ValueError(
"Kernel shape must have the same length as input, but received "
f"kernel of shape {kernel_shape} and "
f"input of shape {input_shape}."
)
if isinstance(dilation_rate, int):
dilation_rate = (dilation_rate,) * len(spatial_shape)
if isinstance(strides, int):
strides = (strides,) * len(spatial_shape)
if len(dilation_rate) != len(spatial_shape):
raise ValueError(
"Dilation must be None, scalar or tuple/list of length of "
"inputs' spatial shape, but received "
f"`dilation_rate={dilation_rate}` and "
f"input of shape {input_shape}."
)
none_dims = []
spatial_shape = np.array(spatial_shape)
for i in range(len(spatial_shape)):
if spatial_shape[i] is None:
# Set `None` shape to a manual value so that we can run numpy
# computation on `spatial_shape`.
spatial_shape[i] = -1
none_dims.append(i)
kernel_spatial_shape = np.array(kernel_shape[:-2])
dilation_rate = np.array(dilation_rate)
if padding == "valid":
output_spatial_shape = (
np.floor(
(spatial_shape - dilation_rate * (kernel_spatial_shape - 1) - 1)
/ strides
)
+ 1
)
for i in range(len(output_spatial_shape)):
if i not in none_dims and output_spatial_shape[i] < 0:
raise ValueError(
"Computed output size would be negative. Received "
f"`inputs shape={input_shape}`, "
f"`kernel shape={kernel_shape}`, "
f"`dilation_rate={dilation_rate}`."
)
elif padding == "same" or padding == "causal":
output_spatial_shape = np.floor((spatial_shape - 1) / strides) + 1
else:
raise ValueError(
"`padding` must be either `'valid'` or `'same'`. Received "
f"{padding}."
)
output_spatial_shape = [int(i) for i in output_spatial_shape]
for i in none_dims:
output_spatial_shape[i] = None
output_spatial_shape = tuple(output_spatial_shape)
if data_format == "channels_last":
output_shape = (
(input_shape[0],) + output_spatial_shape + (kernel_shape[-1],)
)
else:
output_shape = (input_shape[0], kernel_shape[-1]) + output_spatial_shape
return output_shape
def compute_matmul_output_shape(shape1, shape2):
"""Compute the output shape of a `matmul` operation.
Args:
shape1: Shape of the left operand.
shape2: Shape of the right operand.
Returns:
Tuple of ints: The output shape for the `matmul` operation.
"""
if len(shape1) == 1:
shape1 = (1, shape1[0])
if len(shape2) == 1:
shape2 = (shape2[0], 1)
if (
shape1[-1] is not None
and shape2[-2] is not None
and shape1[-1] != shape2[-2]
):
raise ValueError(
"Inner dimensions (`x1.shape[-1]` and `x2.shape[-2]`) must be "
f"equal, but received `x1.shape={shape1}` and "
f"`x2.shape={shape2}`."
)
leading_shape = broadcast_shapes(shape1[:-2], shape2[:-2])
last_2_dims_shape = [shape1[-2], shape2[-1]]
output_shape = leading_shape + last_2_dims_shape
if len(shape1) == 1:
del output_shape[-2]
if len(shape2) == 1:
del output_shape[-1]
return tuple(output_shape)
def compute_reshape_output_shape(input_shape, newshape, newshape_arg_name):
"""Converts `-1` in `newshape` to either an actual dimension or `None`.
This utility does not special case the 0th dimension (batch size).
"""
unknown_dim_count = newshape.count(-1)
if unknown_dim_count > 1:
raise ValueError(
"There must be at most one unknown dimension (-1) in "
f"{newshape_arg_name}. Received: {newshape_arg_name}={newshape}."
)
# If there is a None in input_shape, we can't infer what the -1 is
if None in input_shape:
return tuple(dim if dim != -1 else None for dim in newshape)
input_size = math.prod(input_shape)
# If the `newshape` is fully defined, return it
if unknown_dim_count == 0:
if input_size != math.prod(newshape):
raise ValueError(
"The total size of the tensor must be unchanged. Received: "
f"input_shape={input_shape}, {newshape_arg_name}={newshape}"
)
return newshape
# We have one -1 in `newshape`, compute the actual value
known_output_size = 1
unknown_dim_index = None
for index, dim in enumerate(newshape):
if dim == -1:
unknown_dim_index = index
else:
known_output_size *= dim
if known_output_size == 0 or input_size % known_output_size != 0:
raise ValueError(
"The total size of the tensor must be unchanged, however, the "
"input size cannot by divided by the specified dimensions in "
f"{newshape_arg_name}. Received: input_shape={input_shape}, "
f"{newshape_arg_name}={newshape}"
)
output_shape = list(newshape)
output_shape[unknown_dim_index] = input_size // known_output_size
return tuple(output_shape)
def compute_transpose_output_shape(input_shape, axes):
"""Compute the output shape for the `transpose` operation.
Args:
input_shape: Input shape.
axes: Permutation of the dimensions for the `transpose` operation.
Returns:
Tuple of ints: The output shape after the `transpose` operation.
"""
input_shape = list(input_shape)
if axes is None:
return tuple(input_shape[::-1])
if len(axes) != len(input_shape):
raise ValueError(
"axis must be a list of the same length as the input shape, "
f"expected {len(input_shape)}, but received {len(axes)}."
)
return tuple(input_shape[ax] for ax in axes)
def compute_take_along_axis_output_shape(input_shape, indices_shape, axis):
input_shape = list(input_shape)
indices_shape = list(indices_shape)
if axis is None:
input_shape = (
[None] if None in input_shape else [int(np.prod(input_shape))]
)
if len(input_shape) != len(indices_shape):
raise ValueError(
"`x` and `indices` must have the same number of dimensions, "
f"but receive shape {input_shape} and {indices_shape}."
)
input_shape[axis] = indices_shape[axis]
output_shape = broadcast_shapes(input_shape, indices_shape)
return output_shape
def reduce_shape(shape, axis=None, keepdims=False):
shape = list(shape)
if axis is None:
if keepdims:
return tuple([1 for _ in shape])
else:
return tuple([])
if keepdims:
for ax in axis:
shape[ax] = 1
return tuple(shape)
else:
for ax in sorted(axis, reverse=True):
del shape[ax]
return tuple(shape)
@keras_export("keras.utils.get_source_inputs")
def get_source_inputs(tensor):
"""Returns the list of input tensors necessary to compute `tensor`.
Output will always be a list of tensors
(potentially with 1 element).
Args:
tensor: The tensor to start from.
Returns:
List of input tensors.
"""
if not hasattr(tensor, "_keras_history"):
return tensor
operation, node_index, _ = tensor._keras_history
if not operation or not operation._inbound_nodes:
return [tensor]
else:
node = operation._inbound_nodes[node_index]
if node.is_input:
# Reached input node, stop recursion.
return tree.flatten(node.output_tensors)
else:
source_tensors = []
for tensor in node.input_tensors:
previous_sources = get_source_inputs(tensor)
# Avoid input redundancy.
for x in previous_sources:
if all(x is not t for t in source_tensors):
source_tensors.append(x)
return source_tensors
|