[英]Create random submatrix of large matrix in python
我有以下代碼來創建一個大集合的隨機子集(大小示例):
def sampling(input_set):
tmp = random.sample(input_set, examples)
return tmp
問題是我的輸入是一個大矩陣,所以 input_set.shape = (n,m)。 但是,sampling(input_set) 是一個列表,而我希望它是 size = (examples, m) 的子矩陣,而不是大小為 m 的向量的長度examples
列表。
我修改了我的代碼來做到這一點:
def sampling(input_set):
tmp = random.sample(input_set, examples)
sample = input_set[0:examples]
for i in range(examples):
sample[i] = tmp[i]
return sample
這有效,但是有沒有更優雅/更好的方法來完成我想要做的事情?
使用 numpy 如下創建 anxm 矩陣(假設 input_set 是一個列表)
import numpy as np
input_matrix = np.array(input_set).reshape(n,m)
好的,如果我正確理解您只想放棄最后幾卷(n - k)的問題,那么:
樣本 = input_matrix[:k - n]
必須為你做這項工作。
不知道是否仍然感興趣,但也許你會做這樣的事情:
#select a random 6x6 matrix with items -10 / 10
import numpy as np
mat = np.random.randint(-10,10,(6,6))
print (mat)
#select a random int between 0 and 5
startIdx = np.random.randint(0,5)
print(startIdx)
#extracy submatrix (will be less than 3x3 id the index is out of bounds)
print(mat[startIdx:startIdx+3,startIdx:startIdx+3])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.