[英]Selecting features randomly from a given matrix using python
I have a 6 by 6 matrix created using python. 我有一个使用python创建的6 x 6矩阵。 From the 36 values included in the matrix, i want to select any 10 values (it should select the values randomly, not by specifying the position) from the matrix which are non-zero and the selected 10 values should be printed at the end.
从矩阵中包含的36个值中,我想从矩阵中选择非零的任何10个值(它应该随机选择值,而不是通过指定位置),并且应该在最后打印所选的10个值。 Please help me with the code in python
请帮我用python中的代码
import numpy as np
from numpy import random
#import Dataframe.sample as df
rows = 6
cols = 6
a = np.matrix(np.random.randint(220,376, size=(rows,cols)))
print (a)
You can access a matrix with matrix[y][x]
and generate random indexes with the package random. 您可以使用
matrix[y][x]
访问矩阵,并使用随机包生成随机索引。 Random can be used with import random
. Random可以与
import random
一起使用。 After it is imported you can generate a random index with x = random.randint(0,5)
. 导入后,您可以使用
x = random.randint(0,5)
生成随机索引。
A short example: 一个简短的例子:
import random
for i in range(10): #10 times
x = random.randint(0,5) #index X
y = random.randint(0,5) #index Y
value = matrix[y][x] #get the value
print(value) #print the value
Please note the name of my matrix is matrix
, yours is named a
. 请注意我的矩阵的名称为
matrix
,你被命名为a
。
Consider a 6x6 matrix: 考虑一个6x6矩阵:
x = np.arange(36).reshape(6,6)
Then you can use random.choice() on the matrix collapsed into one dimension ( flatten() ) 然后您可以在折叠成一维的矩阵上使用random.choice() ( flatten() )
np.random.choice(x.flatten(), 10, replace=False)
to get 10 random elements. 获得10个随机元素。
For a np.matrix
, like in your case it changes and I don't know a direct method. 对于
np.matrix
,就像您的情况一样,它会更改并且我不知道直接方法。 What you can do is as follows. 您可以做如下。 You select the indices.
您选择索引。
selected = np.random.choice(a.shape[0]*a.shape[1], 10, replace=False)
# e.g., array([[25, 19, 5, 4, 32, 33, 13, 1, 2, 16]])
# a.shape[0]*a.shape[1]=36 in your case
Finally, you take the elements corresponding to the selected indices on the flatten() matrix 最后,在flatten()矩阵上获取与所选索引对应的元素
a.flatten()[0,selected]
Edit 编辑
There is also a direct method based on numpy.matrix.A1 还有一种基于numpy.matrix.A1的直接方法
a = np.matrix(np.random.randint(220,376, size=(6,6)))
elements = np.random.choice(a.A1, 10, replace=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.