簡體   English   中英

如何找到矩陣中每一列的絕對值之和的最大值

[英]How to find the max of the sums of the absolute values of each column in a matrix

我正在嘗試編寫 function 以在不使用 numpy function 的情況下找到矩陣每一列中每個值之和的最大值。

例如,給定以下數組,我想要答案 2.7657527806024733。

A = np.array([[0.94369777, 0.34434054, 0.80366952, 0.665736],
              [0.82367659, 0.13791176, 0.6993436, 0.44473609],
              [0.82337673, 0.56936686, 0.46648214, 0.50403736]])

這是我到目前為止的代碼:

def L1Norm(M):
    x = 0
    S = np.shape(M)
    N = S[0]
    P = S[1]
    answer = np.zeros((1, P))
    for j in range(P):
        t = 0
        for i in M:
            t += np.abs(i[j])
        answer = np.append(answer, t)
    s = np.shape(answer)
    n = s[0]
    p = s[1]
    for j in range(p):
        if answer[0][j] > x:
            x = answer[0][j]
    return x

但我不斷收到以下錯誤:

IndexError                                Traceback (most recent call last)
<ipython-input-113-e06e08ab836c> in <module>
----> 1 L1Norm(A)

<ipython-input-112-624908415c12> in L1Norm(M)
     12     s = np.shape(answer)
     13     n = s[0]
---> 14     p = s[1]
     15     for j in range(p):
     16         if answer[0][j] > x:

IndexError: tuple index out of range

關於如何解決這個問題的任何想法?

這是我的解決方案。 我遍歷列並將每個總和推入一個數組。 然后我遍歷該數組以找到最大值。 它非常冗長,但除了創建矩陣之外,它不使用 numpy 進行任何操作。

import numpy as np

matrix = np.array([[0.94369777, 0.34434054, 0.80366952, 0.665736],
       [0.82367659, 0.13791176, 0.6993436, 0.44473609],
       [0.82337673, 0.56936686, 0.46648214, 0.50403736]])

matrixShape = np.shape(matrix)

i = 0
j = 0

sumsOfColumns = []

while j < matrixShape[1]:
    sumOfElems = 0
    i = 0
    while i < matrixShape[0]:
        sumOfElems += matrix[i,j]
        i += 1
    sumsOfColumns.append(sumOfElems)
    j += 1

print(sumsOfColumns)

maxValue = 0

for value in sumsOfColumns:
    if value > maxValue:
        maxValue = value

print(maxValue)    

回復:https://repl.it/@ShroomCode/FrequentFunnyDisplaymanager

使用 numpy 您可以使用my_np_array[:,column_number]將每一列作為一個數組

所以使用這個你可以做一個for循環:

sums = []
for i in range(0, np.shape(my_np_array)[0] + 1):
    sums.append(sum(my_np_array[:,i]))

max_sum = max(sums)

要在沒有 numpy 的情況下求解,我們可以 go 通過每一行將每個值添加到其對應的列計數中:

import numpy as np

answer = np.array([[0.94369777, 0.34434054, 0.80366952, 0.665736],
       [0.82367659, 0.13791176, 0.6993436, 0.44473609],
       [0.82337673, 0.56936686, 0.46648214, 0.50403736]])

# Convert our numpy array to a normal array
a = answer.tolist()

# list comprehension to initialise list
sums = [0 for x in range(len(a) + 1)]

for i in range(0, len(a)):
    for j in range(0, len(a[i])):
        sums[j] += a[i][j]

# Get the max sum
max_sum = max(sums)

print(max_sum)

如果您希望獲得最大的列總和,這是使用pandas.DataFrame超級簡單方法:

import numpy as np
import pandas as pd

vals = np.array([[0.94369777, 0.34434054, 0.80366952, 0.665736],
                 [0.82367659, 0.13791176, 0.6993436, 0.44473609],
                 [0.82337673, 0.56936686, 0.46648214, 0.50403736]])

# Store values to a DataFrame.
df = pd.DataFrame(vals)
# Get the max of column sums.
max_sum = df.sum(axis=0).max()

作為 Function:

def max_col_sum(vals):
    max_sum = pd.DataFrame(vals).sum(axis=0).max()
    return max_sum

Output:

2.59075109

使用 zip,np.sum 的簡單答案

代碼

def L1Norm(M):
  return max([np.sum(column) for column in zip(*M)])for column in zip(*M)]

結果

2.59075109

解釋

列表理解以循環遍歷每列中的數據:

[... 對於 zip(*M) 中的列]

將列值與

np.sum(column)

計算列表理解的最大值:

max([...])

請嘗試以下方法?-

A.sum(0).max()   

或者

max(sum(A))

兩者都應該給你想要的答案!

暫無
暫無

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

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