1. numpy.broadcast_to
此函數(shù)將數(shù)組廣播到新形狀圾旨。 它在原始數(shù)組上返回只讀視圖。 它通常不連續(xù)浮声。 如果新形狀不符合 NumPy 的廣播規(guī)則,該函數(shù)可能會(huì)拋出ValueError
读慎。
注意 - 此功能可用于 1.10.0 及以后的版本。
該函數(shù)接受以下參數(shù)。
numpy.broadcast_to(array, shape, subok)
例子
import numpy as np
a = np.arange(4).reshape(1,4)
print '原數(shù)組:'
print a
print '\n'
print '調(diào)用 broadcast_to 函數(shù)之后:'
print np.broadcast_to(a,(4,4))
輸出如下:
[[0 1 2 3]
[0 1 2 3]
[0 1 2 3]
[0 1 2 3]]
2. numpy.expand_dims
函數(shù)通過(guò)在指定位置插入新的軸來(lái)擴(kuò)展數(shù)組形狀。該函數(shù)需要兩個(gè)參數(shù):
numpy.expand_dims(arr, axis)
其中:
-
arr
:輸入數(shù)組 -
axis
:新軸插入的位置
例子
import numpy as np
x = np.array(([1,2],[3,4]))
print '數(shù)組 x:'
print x
print '\n'
y = np.expand_dims(x, axis = 0)
print '數(shù)組 y:'
print y
print '\n'
print '數(shù)組 x 和 y 的形狀:'
print x.shape, y.shape
print '\n'
# 在位置 1 插入軸
y = np.expand_dims(x, axis = 1)
print '在位置 1 插入軸之后的數(shù)組 y:'
print y
print '\n'
print 'x.ndim 和 y.ndim:'
print x.ndim,y.ndim
print '\n'
print 'x.shape 和 y.shape:'
print x.shape, y.shape
輸出如下:
數(shù)組 x:
[[1 2]
[3 4]]
數(shù)組 y:
[[[1 2]
[3 4]]]
數(shù)組 x 和 y 的形狀:
(2, 2) (1, 2, 2)
在位置 1 插入軸之后的數(shù)組 y:
[[[1 2]]
[[3 4]]]
x.shape 和 y.shape:
2 3
x.shape and y.shape:
(2, 2) (2, 1, 2)
(source)