Numpy库学习之np.linspace函数
一、简介
np.linspace
是 NumPy 库中的一个函数,用于在指定的区间内生成【等间距】的数字序列。这个函数非常有用,尤其是在需要在固定间隔内对数据进行采样时。
二、语法和参数
np.linspace
的基本语法如下:
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
start
:序列的起始值。stop
:序列的结束值。num
:要生成的样本数量,默认为50。endpoint
:布尔值,如果为True,则包含stop
值在序列中;如果为False,则不包含。retstep
:布尔值,如果为True,则返回样本和步长。dtype
:输出数组的类型。如果未指定,则根据其他输入参数推断数据类型。axis
:返回的样本数组中沿哪个轴存放样本,0表示沿第一个轴。
三、实例
3.1 基础使用
import numpy as np
# 生成从0到10的5个等间距的样本
samples = np.linspace(0, 10, num=5)
print(samples)
输出:
[ 0. 2.5 5. 7.5 10. ]
3.2 包含结束点
# 生成从0到10的11个等间距的样本,包含结束点
samples_with_endpoint = np.linspace(0, 10, num=11, endpoint=True)
print(samples_with_endpoint)
输出:
[ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.]
3.3 不包含结束点
# 生成从0到10的10个等间距的样本,不包含结束点
samples_without_endpoint = np.linspace(0, 10, num=10, endpoint=False)
print(samples_without_endpoint)
输出:
[0. 0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5]
3.4 返回步长
# 生成样本并返回步长
samples_with_step = np.linspace(0, 10, num=5, retstep=True)
print("Samples:", samples_with_step[0])
print("Step:", samples_with_step[1])
输出:
Samples: [ 0. 2.5 5. 7.5 10. ]
Step: 2.5
四、注意事项
- 当
endpoint=False
时,num
参数表示不包括结束点stop
的样本数量,因此实际生成的样本数量会比num
多一个。 - 如果需要更高精度的等间距样本,可以通过设置
dtype
参数来指定输出数组的数据类型,例如np.float64
。