在Python中高效地按轴(常用)数字分配数组

2024-09-27 23:17:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个图像,我的子样本

Count=0
classim = np.zeros([temp1.shape[0],temp1.shape[1]])
for rows in range(int(np.floor(temp1.shape[0]/SAMPLE_SIZE))):
    for cols in range(int(np.floor(temp1.shape[1]/SAMPLE_SIZE))):

        classim[np.multiply(rows,SAMPLE_SIZE):np.multiply(rows+1,SAMPLE_SIZE),
                np.multiply(cols,SAMPLE_SIZE):np.multiply(cols+1,SAMPLE_SIZE)] = predict.argmax(axis=-1)[Count]
        Count = np.add(Count,1)

这太慢了。我的标签来自“预测.argmax(axis=-1)[Count]“,当然可以是向量形式。 换言之,如何对上述循环进行矢量化?


Tags: sampleinforsizecountnprangemultiply
1条回答
网友
1楼 · 发布于 2024-09-27 23:17:03

将行计算放在内部循环之外会有一点帮助。因此,每行只进行一次计算。你知道吗

其他一些整理可以:

classim = np.zeros_like(temp1)
predict_args = predict.argmax(axis=-1)
for rows in range(temp1.shape[0]//SAMPLE_SIZE):
    row_0 = rows * SAMPLE_SIZE
    row_1 = (rows+1) * SAMPLE_SIZE
    for cols in range(temp1.shape[1]//SAMPLE_SIZE):
        col_0 = cols * SAMPLE_SIZE
        col_1 = (cols+1) * SAMPLE_SIZE
        classim[row_0:row_1,col_0:col_1] = predict_args[Count]
        Count+=1

在我做更多之前,你需要告诉我们更多关于预测对象的信息。但这些改变会有一点帮助。你知道吗

编辑

你可以利用numpy.重复功能。那么就不需要遍历整个classim:

SAMPLE_SIZE = 2
temp1 = np.arange(20*20).reshape((20,20))

sample_shape = (temp1.shape[0]//SAMPLE_SIZE, temp1.shape[0]//SAMPLE_SIZE)

#This line should work as per your question, but returns a single value
#predict_args = predict.argmax(axis=-1)
#Use this for illustration purposes
predict_args = np.arange(sample_shape[0] * sample_shape[1])


subsampled = predict_args.reshape(sample_shape)
classim = np.repeat(np.repeat(subsampled,SAMPLE_SIZE,axis =1),SAMPLE_SIZE, axis=0)


print(subsampled)
print(classim)

相关问题 更多 >

    热门问题