簡體   English   中英

Numpy根據閾值更改元素,然后逐元素相加

[英]Numpy change elements based on threshold and then do element by element addition

我有3247個197x10尺寸矩陣。 我需要對它們進行掃描,如果值大於1,則將其設置為1。如果值小於或等於1,我想將其設置為零。 然后,我必須將此修改后的矩陣添加到其他3246集的修改后的矩陣中。 這是我到目前為止的內容:

for i in range(LOWER, UPPER + 1):
    fname = file_name+str(i)+".txt"
    cur_resfile = np.genfromtxt(fname, delimiter = ",", skiprows = 1)
    m_cur = cur_resfile

    m_cur[m_cur <= 1] = 0
    m_cur[m_cur > 1 ] = 1

    m_ongoing = m_ongoing + m_cur

我希望m_ongoing保持正在進行的運行總和,以便可以將其保存到文件中。 但是,它不起作用,似乎只是在循環中寫入最后一個m_cur。 如果我總共運行3次循環,則有些單元格相互之間都具有1s,因此我希望有幾個3s。 我當然希望有很多2,但是我只會看到1和0。

做我想做的最好的方法是什么?

-根據條件更改值

-接受大量矩陣,然后逐個元素地添加所有元素,以為每個單元格創建運行總和。

您可以使用numpy.clip()

for i in range(LOWER, UPPER + 1):
    fname = file_name+str(i)+".txt"

    cur_resfile = np.genfromtxt(fname, delimiter = ",", skiprows = 1)

    m_ongoing += cur_resfile.clip(0,1)

編輯回答所問的問題:

m_ongoing = np.zeros((197,10))

for i in range(LOWER, UPPER + 1):
    fname = file_name+str(i)+".txt"
    cur_resfile = np.genfromtxt(fname, delimiter = ",", skiprows = 1)

    # add one to the places where cur_file > 1
    m_ongoing[cur_resfile > 1] += 1

正如@RootTwo所建議的那樣,clip()是一個很好的內置numpy內置函數。 但是出於性能原因,您可以在數據的3D“堆棧”上使用矢量化操作。

例:

import numpy as np
#simulating your data as a list of 3247 2D matrices, each 197x10
some_data = [np.random.randint(-2,2,(197,10)) for _i in range(3247)]
#stack the matrices
X = np.dstack(some_data)
print(X.shape)

(197,10,3247)

Y = X.clip(0,1)
Z = Y.sum(axis=2)
#Z is now the output you want!
print(Z.shape)

(197,10)

編輯:添加計時結果,並更改我的答案

因此,我的建議似乎是創建一個深度堆棧並使用clip和sum函數的單個應用程序是不明智的。 我進行了一些時序測試,發現增量方法更快,主要是由於分配大3D數組的分配時間開銷。

在這些測試中,我考慮了數據加載方面,因為兩種方法都相同。 以下是將ipython中的兩種方法與%timeit宏進行比較的結果。

import numpy as np
# some_data is simulated as in the above code sample
def f1(some_data):
    x = some_data[0]
    x = x.clip(0,1)
    for y in some_data[1:]:
        x += y.clip(0,1)
    return x

def f2(some_data):
    X = np.dstack(some_data)
    X = X.clip(0,1)
    X = X.sum(axis=2)
    return X

%timeit x1 = f1(some_data)

10個循環,最佳3:每個循環28.1毫秒

%timeit x2 = f2(some_data)

10個循環,最好3:每個循環103毫秒

因此,相對於在堆棧數據后進行單個操作而言,增量執行該過程的速度提高了3.7倍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM