python随机选择不同的行

时间:2016-11-06 18:04:56

标签: python random

我有一个问题,我想在矩阵的不同行上随机选择两个数字。然后,将这些数字放在同一行,但在下面的列上,以完成矩阵。

例如:

#I create a matrix "pop" where there are numbers in the first and second column and where there are zeros on the other columns
tab=np.array([[3, 2, 1, 0, 4, 6], [9, 8, 7, 8, 2, 0]]) 
tab1=tab.transpose()
pop=np.zeros((6,8),int)
pop[:,0:2]=tab1

#I create a function "next" which complete the matrix "pop" by a 
#random sampling with replacement  from the second previous column
def next (a):#a is the column of the data
    for i in range (0,6):#i is the row of the data
        pop[i,a]=np.random.choice(pop[:,(a-2)],1,replace=True)# select a number by a random choice from second previous column
        pop[i,a+1]=np.random.choice(pop[:,(a-1)],1,replace=True)


# loope to complete the data "pop"
for r in range(2,8):
    if r % 2 ==0:
        next(r)

但在我的例子中,有可能在矩阵的同一行上选择两个数字。

所以我试过了:

def whynot (a):#a is the column of the data
    for i in range (0,6):#i is the row of the data
        number=np.random.choice(pop[:,(a-1):(a-2)],2,replace=False)# select a number by a random choice from second previous column
        pop[i,a:a+1]=number

但它不起作用......:_(

感谢您的帮助!

: - )

1 个答案:

答案 0 :(得分:0)

最后我找到了一些东西,但它很长,我觉得有更好的解决方案。但我发布了剧本,因为它可以帮助某人。

import tensorflow as tf
import numpy as np

x = tf.placeholder(tf.float32, shape=[None, 2])
y_ = tf.placeholder(tf.float32, shape=[None, 2])
loss = tf.reduce_sum(tf.abs(tf.sub(x, y_)))#Function chosen arbitrarily
input_x=np.random.randn(100, 2)#Random generation of variable x
input_y=np.random.randn(100, 2)#Random generation of variable y

with tf.Session() as sess:
    print(sess.run(loss, feed_dict={x: input_x, y_: input_y}))