[英]Pytorch compute the mean of a 2D tensor at specific rows given a condition
[英]Compute mean and variance on specific columns of 2D array only if a condition on element on each row is satisfied
我有一個尺寸為(690L,15L)的2D numpy數組。 我只需要在某些奇數列中對此數據集計算列的均值,但要滿足以下條件:當且僅當特定列中同一行中的元素滿足條件時,才需要包含一行。 讓我用一些代碼清除更多信息。
f = open("data.data")
dataset = np.loadtxt(fname = f, delimiter = ',')
我有充滿指標的數組,我需要執行均值(和方差)
index_catego = [0, 3, 4, 5, 7, 8, 10, 11]
條件是, dataset[i, 14] == 1
作為輸出,我想要一個長度為len(index_catego)
的一維數組,其中該數組的每個元素都是len(index_catego)
的均值
output = [mean_of_index_0, mean_of_index_3, ..., mean_of_index_11]
我最近正在使用Python,但是我敢肯定有一種很酷的方法可以通過np.where
, mask
, np.mean
或其他方式實現。
我已經實現了一個解決方案,但是它並不優雅,並且不確定是否正確。
import numpy as np
index_catego = [0, 3, 4, 5, 7, 8, 10, 11]
matrix_mean_positive = []
matrix_variance_positive = []
matrix_mean_negative = []
matrix_variance_negative = []
n_positive = 0
n_negative = 0
sum_positive = np.empty(len(index_catego))
sum_negative = np.empty(len(index_catego))
for i in range(dataset.shape[0]):
if dataset[i, 14] == 0:
n_positive = n_positive + 1
j = 0
for k in index_catego:
sum_positive[j] = sum_positive[j] + dataset[i, k]
j = j + 1
else:
n_negative = n_negative + 1
j = 0
for k in index_catego:
sum_negative[j] = sum_negative[j] + dataset[i, k]
j = j + 1
for item in np.nditer(sum_positive):
matrix_mean_positive.append(item / n_positive)
for item in np.nditer(sum_negative):
matrix_mean_negative.append(item / n_negative)
print(matrix_mean_positive)
print(matrix_mean_negative)
如果您想嘗試解決方案,我會舉一些數據示例
1,22.08,11.46,2,4,4,1.585,0,0,0,1,2,100,1213,0
0,22.67,7,2,8,4,0.165,0,0,0,0,2,160,1,0
0,29.58,1.75,1,4,4,1.25,0,0,0,1,2,280,1,0
0,21.67,11.5,1,5,3,0,1,1,11,1,2,0,1,1
1,20.17,8.17,2,6,4,1.96,1,1,14,0,2,60,159,1
0,15.83,0.585,2,8,8,1.5,1,1,2,0,2,100,1,1
1,17.42,6.5,2,3,4,0.125,0,0,0,0,2,60,101,0
感謝您的幫助。
更新1:我嘗試過
output_positive = dataset[:, index_catego][dataset[:, 14] == 0]
mean_p = output_positive.mean(axis = 0)
print(mean_p)
output_negative = dataset[:, index_catego][dataset[:, 14] == 1]
mean_n = output_negative.mean(axis = 0)
print(mean_n)
但是通過第一個解決方案(非冷卻溶液)和第二個解決方案(單線冷卻溶液)計算出的均值不同。 我檢查了選擇了什么dataset[:, index_catego][dataset[:, 14] == 0]
和dataset[:, index_catego][dataset[:, 14] == 1]
(正確的尺寸和正確的元素)。
更新2:好的,第一個解決方案是錯誤的,因為(例如)第一列只有0和1作為元素,但作為平均值返回值>1。我不知道在哪里失敗。 似乎肯定的類別是正確的(或至少是合理的),而否定的類別甚至是不合理的。
那么,第二種解決方案正確嗎? 有更好的方法嗎?
更新3:我認為我發現第一個解決方案的問題:我正在使用jupyter筆記本,有時(並非所有時候)當我重新運行第一個解決方案所在的單元格時, matrix_mean_positive
和matrix_mean_negative
中的元素加倍了。 如果有人知道為什么,可以指出我嗎?
現在,兩種解決方案都返回相同的方法。
在重新運行之前在Jupyter Notebook中執行內核->重新啟動以清除內存
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.