我想生成一個玩具示例來說明 中的凸分段線性函式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]
我現在可以使用前兩個點并創建一個隨機線性函式,但我不知道我應該如何從那里繼續以保持凸性。請注意,如果函式圖形上任意兩點之間的線段不位于兩點之間的圖形下方,則該函式稱為凸函式。
uj5u.com熱心網友回復:
斜率從 [0,1) 范圍內的隨機值單調增加,從 0 開始。第一個 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]

種子值不同,我只依賴 numpy 的隨機函式,這就是為什么x_points它們不同。
為了得到上圖,我使用了 gnuplot。首先,我使用np.savetxt("points.txt",np.concatenate([x_points.reshape(-1,1),y_points.reshape(-1,1)],axis=1)),然后使用 gnuplot 的格式set yrange [-2:26]; set xrange [-1:17]; set key left和 gnuplot 的繪圖功能保存資料p "points.txt" w lp t "convex piecewise-linear function"
uj5u.com熱心網友回復:
確保梯度 (=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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/394728.html
