我是Python的初学者。 我有矩阵乘法的问题。 我使用列表列表(矩阵)从txt文件中读取矩阵。
当我想使用多处理时,我遇到除法列表的问题并在Pool函数中使用新列表。
如何解决此问题?
请帮助
def matrix_multiplication(list1, list2):
A = numpy.matrix(list1)
B = numpy.matrix(list2)
return A*B
def counting(dane):
left_matrix = matrices[0]
for matrix in matrices[1:]:
left_matrix = numpy.matrix(left_matrix)
matrix = numpy.matrix(matrix)
left_matrix = matrix_multiplication(left_matrix, matrix)
if __name__ == "__main__":
matrices = []
with open('sample-probka2.txt', 'r') as file:
matrix_reader = csv.reader(file, delimiter=';')
current_matrix = []
for row in matrix_reader:
if len(row) == 0:
matrices.append(current_matrix)
current_matrix = []
else:
current_matrix.append(list(map(float, row)))
print (matrices)
counting(matrices)
np = multiprocessing.cpu_count()
print('You have', np, 'processors')
matrices2 = numpy.array_split(matrices, np)
print(matrices2)
pool = Pool(processes=np)
count = pool.starmap(liczenie, matrices2)
print count
评论错误,尝试恢复格式:
multiprocessing.pool.RemoteTraceback:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py",
line 119, in worker result = (True, func(*args, **kwds))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 47,
in starmapstar return list(itertools.starmap(args[0], args[1])) TypeError: counting() takes 1 positional argument but 61 were given
答案 0 :(得分:0)
在这种情况下,我认为你不想要pool.starmap
。它正在做的是将每个矩阵解包为61个元素,因为它被传递给counting()
,只需要一个参数。
starmap(func,iterable [,chunksize])
与map()类似,只是迭代的元素应该是 被解压缩为参数的迭代。
因此[(1,2),(3,4)]的可迭代导致[func(1,2), FUNC(3,4)]。
你可以通过多种方式解决这个问题,但我认为最明智的做法是使用pool.map
,因为它不会解压缩输入并将它们保留为单个变量。您还可以定义counting(*dane)
以允许可变数量的输入连接到列表dane
(您不会在函数中使用,但我会留下您弄清楚该怎么做..)
答案 1 :(得分:0)
在
count = pool.starmap(liczenie, matrices2)
什么是liczenie
?我在代码中看不到这样的功能。错误消息表明它是counting
。
但在counting(dane)
中,永远不会使用dane
。
看起来matrices
是浮动列表的列表。所有子列表的长度是否相同?如果是这样,为什么你没有用像csv
这样的numpy加载器读取np.genfromtxt
文件?但这是一个侧面点。
counting(matrices)
是否有效?除了混乱的调用论点,它不会返回任何东西。我猜它应该做一个链式矩阵产品M1*M2*M3*...
。 *
的{{1}}是矩阵产品,而不是逐个元素(np.matrix
的{{1}})。
但那不会起作用; *
是(1,n)矩阵。它不能与另一个(1,n)矩阵相乘,无论你在np.array()
中包裹它多少次(为什么你要多次这样做?)
np.matrix(alist)
多处理的目的是什么?应该对纠正的np.matrix
进行单次调用是做什么的呢?