NumPy 数组创建
2019-02-24 10:26:23
•
阅读
打赏
NumPy创建数组的几种方法
- 从其他Python结构(例如,列表,元组)转换
- numpy原生数组的创建(例如,arange、ones、zeros等)
- 从磁盘读取数组,无论是标准格式还是自定义格式
- 通过使用字符串或缓冲区从原始字节创建数组
- 使用特殊库函数(例如,random)
numpy.empty
numpy.empty 方法创建一个指定形状(shape)、数据类型(dtype)未初始化的数组:
未初始化的数组元素为随机值。
numpy.empty(shape, dtype = float, order = 'C')
函数接受下列参数:
序号 | 参数及描述 |
---|---|
1. | Shape 空数组的形状,整数或整数元组 |
2. | Dtype 所需的输出数组类型,可选 |
3. | Order 'C' 为按行的 C 风格数组,'F' 为按列的 Fortran 风格数组 |
import numpy as np
x = np.empty([3,2], dtype = int)
print(x)
# [[0 0]
# [0 0]
# [0 0]]
numpy.zeros
创建指定大小的数组,数组元素以 0 来填充,默认的dtype是float64:
numpy.zeros(shape, dtype = float, order = 'C')
函数接受下列参数:
import numpy as np
# 默认为浮点数
x = np.zeros(5)
print(x) # [0. 0. 0. 0. 0.]
# 设置类型为整数
y = np.zeros((5,), dtype=np.int)
print(y) # [0 0 0 0 0]
# 自定义类型
z = np.zeros((2, 2), dtype=[('x', 'i4'), ('y', 'i4')])
print(z)
# [[(0, 0) (0, 0)]
# [(0, 0) (0, 0)]]
numpy.ones
创建指定形状的数组,数组元素以 1 来填充:
numpy.ones(shape, dtype = None, order = 'C')
函数接受下列参数:
序号 | 参数及描述 |
---|---|
1. | Shape 空数组的形状,整数或整数元组 |
2. | Dtype 所需的输出数组类型,可选 |
3. | Order 'C' 为按行的 C 风格数组,'F' 为按列的 Fortran 风格数组 |
import numpy as np
# 默认为浮点数
x = np.ones(5)
print(x) # [1. 1. 1. 1. 1.]
# 自定义类型
x = np.ones([2, 2], dtype=int)
print(x)
# [[1 1]
# [1 1]]
相关推荐
深度学习 -- 损失函数
深度残差网络(Deep Residual Networks (ResNets))
深度学习 -- 激活函数
神经网络训练 -- 调整学习速率
生成对抗网络(GAN)改进与发展
生成对抗网络(GAN)优点与缺点
生成对抗网络(GAN)的训练
生成对抗网络(GAN)基本原理
生成模型与判别模型