np.random.RandomState(random_seed)是一个随机数产生器,
随机数产生器可以根据多项分布概率去产生随机数,哪个数字被产生,就在对应位置设为1。多次进行试验,次数会累加。如下所示:
print("Random throwing of dice for 20 times:",np.random.multinomial(20, [1 / 6.] * 6, size=1))
Random throwing of dice for 20 times: [[7 1 4 1 5 2]]
以下例子,按照一定的概率去翻转标签,概率来自trans 矩阵:
import numpy as np
if __name__ == '__main__':
trans = uniform_trans(5, 0.4)
print("Trans: {}".format(trans))
# example of multinomial
print("Random throwing of dice for 20 times:",np.random.multinomial(20, [1 / 6.] * 6, size=1))
flipper = np.random.RandomState(0)
# true labels
y = np.array([0,0,1,2,2,1,3,4,4,3])
new_y = y.copy()
for idx in np.arange(y.shape[0]):
i = y[idx]
# draw a vector with only an 1
# 第一个参数1表示只随机抽一次,抽取的概率来自trans[i,:],第二个1 表示进行一组随机实验
flipped = flipper.multinomial(1, trans[i, :], 1)[0]
print("flipped:{}".format(flipped))
new_y[idx] = np.where(flipped == 1)[0]
print("np.where(flipped == 1):{}".format(np.where(flipped == 1)))
print("y:{}".format(y))
print("new_y:{}".format(new_y))
结果如下:
Trans: [[0.6 0.1 0.1 0.1 0.1]
[0.1 0.6 0.1 0.1 0.1]
[0.1 0.1 0.6 0.1 0.1]
[0.1 0.1 0.1 0.6 0.1]
[0.1 0.1 0.1 0.1 0.6]]
Random throwing of dice for 20 times: [[7 1 4 1 5 2]]
flipped:[1 0 0 0 0]
np.where(flipped == 1):(array([0]),)
flipped:[0 0 0 1 0]
np.where(flipped == 1):(array([3]),)
flipped:[0 1 0 0 0]
np.where(flipped == 1):(array([1]),)
flipped:[0 1 0 0 0]
np.where(flipped == 1):(array([1]),)
flipped:[0 0 1 0 0]
np.where(flipped == 1):(array([2]),)
flipped:[0 0 0 1 0]
np.where(flipped == 1):(array([3]),)
flipped:[0 0 0 0 1]
np.where(flipped == 1):(array([4]),)
flipped:[1 0 0 0 0]
np.where(flipped == 1):(array([0]),)
flipped:[0 0 0 0 1]
np.where(flipped == 1):(array([4]),)
flipped:[0 0 1 0 0]
np.where(flipped == 1):(array([2]),)
y:[0 0 1 2 2 1 3 4 4 3]
new_y:[0 3 1 1 2 3 4 0 4 2]