如何生成随机凸分段线性函数

how to generate a random convex piecewise-linear function

我想生成一个玩具示例来说明 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]

我现在可以使用前两个点并创建一个随机线性函数,但我不知道我应该如何从那里继续以保持凸性。请注意,如果函数图形上任意两点之间的线段不位于两点之间的图形下方,则函数称为凸函数。

确保渐变 (=dx/dy) 正在增加。 伪代码:

s = 1;
x = 0;
y = 0;
n = 4;
while(--n>0)
{
  //increase x randomly
  dx = rand(3);
  dy = dx * s;
  x += dx;
  y += dy; 
  //increase gradient randomly
  s += rand(3);
  print x + "/" +y;
}

从 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

可能的输出如下所示:

print(x_points)
print(y_points)
# [ 0  1  4 13 16]
# [ 0.          0.          2.57383685 17.92061306 24.90689622]

要打印此图:

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()