Numpy Tips

1. numpy.broadcast_to

此函数将数组广播到新形状。 它在原始数组上返回只读视图。 它通常不连续。 如果新形状不符合 NumPy 的广播规则,该函数可能会抛出ValueError

注意 - 此功能可用于 1.10.0 及以后的版本。

该函数接受以下参数。

numpy.broadcast_to(array, shape, subok)

例子

import numpy as np
a = np.arange(4).reshape(1,4)

print '原数组:'
print a
print '\n'  

print '调用 broadcast_to 函数之后:'
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

函数通过在指定位置插入新的轴来扩展数组形状。该函数需要两个参数:

numpy.expand_dims(arr, axis)

其中:

  • arr:输入数组
  • axis:新轴插入的位置

例子

import numpy as np
x = np.array(([1,2],[3,4]))

print '数组 x:'
print x
print '\n'  
y = np.expand_dims(x, axis = 0)

print '数组 y:'
print y
print '\n'

print '数组 x 和 y 的形状:'
print x.shape, y.shape
print '\n'  
# 在位置 1 插入轴
y = np.expand_dims(x, axis = 1)

print '在位置 1 插入轴之后的数组 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

输出如下:

数组 x:
[[1 2]
 [3 4]]

数组 y:
[[[1 2]
 [3 4]]]

数组 x 和 y 的形状:
(2, 2) (1, 2, 2)

在位置 1 插入轴之后的数组 y:
[[[1 2]]
 [[3 4]]]

x.shape 和 y.shape:
2 3

x.shape and y.shape:
(2, 2) (2, 1, 2)

source

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容