@@ -317,32 +317,69 @@ def collapse(
317
317
fun : Callable [[np .ndarray ], Union [float , np .ndarray ]] = np .sum ,
318
318
) -> Union [float , np .ndarray , tensor ]:
319
319
"""
320
- Collapse tensor along specified dimensions.
320
+ Collapse tensor along specified dimensions using a function .
321
321
322
322
Parameters
323
323
----------
324
- dims:
325
- Dimensions to collapse.
326
- fun:
327
- Method used to collapse dimensions.
324
+ dims: optional
325
+ Dimensions to collapse (default: all) .
326
+ fun: optional
327
+ Method used to collapse dimensions (default: :meth:`numpy.sum`) .
328
328
329
329
Returns
330
330
-------
331
- Collapsed value .
331
+ Scalar (if all dimensions collapsed) or tensor .
332
332
333
333
Examples
334
334
--------
335
- >>> T = ttb.tensor(np.ones((2, 2)))
336
- >>> T.collapse()
337
- 4.0
338
- >>> T.collapse(np.array([0]))
339
- tensor of shape (2,) with order F
340
- data[:] =
341
- [2. 2.]
342
- >>> T.collapse(np.arange(T.ndims), sum)
343
- 4.0
344
- >>> T.collapse(np.arange(T.ndims), np.prod)
345
- 1.0
335
+ Sum all elements of tensor::
336
+
337
+ >>> T = ttb.tensor(np.ones((4,3,2),order='F'))
338
+ >>> T.collapse()
339
+ 24.0
340
+
341
+ Compute the sum for each mode-0 fiber (output is a tensor)::
342
+
343
+ >>> T.collapse(0)
344
+ tensor of shape (3, 2) with order F
345
+ data[:, :] =
346
+ [[4. 4.]
347
+ [4. 4.]
348
+ [4. 4.]]
349
+
350
+ Compute the sum of the entries in each mode-0 slice (output is a tensor)::
351
+
352
+ >>> T.collapse([1, 2])
353
+ tensor of shape (4,) with order F
354
+ data[:] =
355
+ [6. 6. 6. 6.]
356
+
357
+ Compute the max entry in each mode-2 slice (output is a tensor)::
358
+
359
+ >>> T.collapse([0, 1], np.max)
360
+ tensor of shape (2,) with order F
361
+ data[:] =
362
+ [1. 1.]
363
+
364
+ Find the maximum and minimum values in a tensor::
365
+
366
+ >>> randn = lambda s : np.random.randn(np.prod(s))
367
+ >>> np.random.seed(0) # reproducibility
368
+ >>> T = ttb.tensor.from_function(randn, (2, 2, 2))
369
+ >>> print(T)
370
+ tensor of shape (2, 2, 2) with order F
371
+ data[:, :, 0] =
372
+ [[1.76405235 0.97873798]
373
+ [0.40015721 2.2408932 ]]
374
+ data[:, :, 1] =
375
+ [[ 1.86755799 0.95008842]
376
+ [-0.97727788 -0.15135721]]
377
+ >>> max_val = T.collapse(fun=np.max)
378
+ >>> min_val = T.collapse(fun=np.min)
379
+ >>> print(f"Max value: {max_val}")
380
+ Max value: 2.240893199201458
381
+ >>> print(f"Min value: {min_val}")
382
+ Min value: -0.977277879876411
346
383
"""
347
384
if self .data .size == 0 :
348
385
return np .array ([], order = self .order )
0 commit comments