矩阵乘法和行求和类型错误

时间:2016-02-21 12:46:04

标签: python vector sum matrix-multiplication

我想将[260 * 2500]矩阵与[1 * 2500]向量相乘。然后我想总结这个乘法矩阵的行。

矩阵:original_nonspam_matrix

矢量:train_probs_nonspam_word

我写了下面的代码,但我有:

  

TypeError:' float'对象没有属性' getitem '

有没有人可以帮我快点?

sums = []
for row in original_nonspam_matrix:
    for i in range(0,len(row)):
        multiply = row[i] * train_probs_nonspam_word[i]
        sum = sum(multiply[i])
        sums.append(sum) 
print sums

输入:

original_nonspam_matrix[0] (sample):

[-0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -5.259440519499674, -5.259440519499674, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -5.259440519499674, -0.0, -5.259440519499674, -0.0, -0.0]

original_nonspam_matrix[1] (sample):

[-5.5014525551182665, -5.5014525551182665, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -5.5014525551182665, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0, -5.5014525551182665, -0.0, -0.0, -0.0, -0.0, -0.0, -0.0] 

train_probs_nonspam_word (sample): 

[0.005198212203653323, 0.004080839486980179, 0.0019756445135380232, 0.018299002461458738, 0.0009392408343049617, 0.002283326855810338, 0.0011335665241611608, 0.014671589584143024, 0.0030120481927710845, 0.001862287861121907]

1 个答案:

答案 0 :(得分:0)

multiply是一个浮点数。 这是一个解决方案:

class Matrix:
def __init__(self, rows: int, columns: int, data):
    self.rows = rows
    self.columns = columns
    self.data = data
    assert rows * columns == len(data)

def _index_from_r_c(self, r: int, c: int):
    assert 0 <= r < self.rows
    assert 0 <= c < self.columns

    return r * self.columns + c

def get(self, r: int, c: int):
    return self.data[self._index_from_r_c(r, c)]

def set(self, r, c, d):
    self.data[self._index_from_r_c(r, c)] = d

def __str__(self):
    s = ''
    for r in range(0, self.rows):
        s += ', '.join([str(self.get(r, c)) for c in range(0, self.columns)])
        s += '\n'
    return s


def multiply(m1: Matrix, m2: Matrix) -> Matrix:
    assert m1.columns == m2.rows

    result = Matrix(m1.rows, m2.columns, [0] * m1.rows * m2.columns)

    for r in range(0, m1.rows):
        for c in range(0, m2.columns):
            r_c_element = 0
            for i in range(0, m1.columns):
                r_c_element += m1.get(r, i) * m2.get(i, c)
            result.set(r, c, r_c_element)

    return result

def sum_of_rows(m: Matrix):
    return [sum([m.get(r, c) for c in range(0, m.columns)]) for r in range(0, m1.rows)]