bel*_*nsi 6 python random numpy piecewise
我想生成一个玩具示例来说明 中的凸分段线性函数python,但我无法找出实现此目的的最佳方法。我想做的是指示行数并随机生成函数。
凸分段线性函数定义为:
例如,如果我想要四条线性线,那么我想生成如下所示的内容。
因为有四行。我需要生成四个递增的随机整数来确定 x 轴的间隔。
import random
import numpy as np
random.seed(1)
x_points = np.array(random.sample(range(1, 20), 4))
x_points.sort()
x_points = np.append(0, x_points)
x_points
[0 3 4 5 9]
Run Code Online (Sandbox Code Playgroud)
我现在可以使用前两点并创建一个随机线性函数,但我不知道应该如何继续以保持凸性。请注意,如果函数图形上任意两点之间的线段不位于两点之间的图形下方,则该函数称为凸函数。
斜率从 0 开始按范围 [0,1) 中的随机值单调增加。第一个 y 值也为零,请参阅注释。
import numpy as np
np.random.seed(0)
x_points = np.random.randint(low=1, high=20, size=4)
x_points.sort()
x_points = np.append(0, x_points) # the first 0 point is 0
slopes = np.add.accumulate(np.random.random(size=3))
slopes = np.append(0,slopes) # the first slope is 0
y_incr = np.ediff1d(x_points)*slopes
y_points = np.add.accumulate(y_incr)
y_points = np.append(0,y_points) # the first y values is 0
Run Code Online (Sandbox Code Playgroud)
可能的输出如下所示:
print(x_points)
print(y_points)
# [ 0 1 4 13 16]
# [ 0. 0. 2.57383685 17.92061306 24.90689622]
Run Code Online (Sandbox Code Playgroud)
要打印该图:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(x_points,y_points, '-o', label="convex piecewise-linear function")
ax.legend()
fig.patch.set_facecolor('white')
plt.show()
Run Code Online (Sandbox Code Playgroud)