Python矩阵,有什么解决方案吗?
我的输入(仅作为示例):
from numpy import *
x=[['1' '7']
['1.5' '8']
['2' '5.5']
['2' '9']]
我想在随机矩阵上做下一步:
1。对于每一行计算:
> for example first row: [1;7]*[1,7] = [[1, 7]; #value * value.transpose
[7, 49]]
> for example second row: [1.5;8]*[1.5,8]= [[2.25, 12];
[12, 64]]
>.......
这对于 numpy 来说很简单,因为转置只是 xT
,如果 x=[1,7] 必须对矩阵上的每一行进行计算!
2.现在我想这样总结...
<前><代码>[1+2.25+...7+12+......] [ ] [7+12+...49+64+...]
所以结果就是这个矩阵。
有什么想法吗?
编辑2:
x=[['1','7']
['1.5', '8']
['2', '5.5']
['2','9']]
y = x[:, :, None] * x[:, None]
print y.sum(axis=0)
我收到错误:
“列表索引必须是整数,而不是 元组”
但如果 x 是 x = numpy.array([[1, 7], [1.5, 8], [2, 5.5], [2, 9]]) 那么就可以了,但是我没有这样的输入。
MY input(just for example):
from numpy import *
x=[['1' '7']
['1.5' '8']
['2' '5.5']
['2' '9']]
I want to make next thing on random matrix:
1. for each row calculate:
> for example first row: [1;7]*[1,7] = [[1, 7]; #value * value.transpose
[7, 49]]
> for example second row: [1.5;8]*[1.5,8]= [[2.25, 12];
[12, 64]]
>.......
This is simple with numpy, because transpose is just x.T
, if x=[1,7]
This must be calculated for every row on matrix!
2. now I want to sum as in this way...
[1+2.25+... 7+12+...... ] [ ] [7+12+.... 49+64+.... ]
So result is this matrix.
Any ideas?
EDIT2:
x=[['1','7']
['1.5', '8']
['2', '5.5']
['2','9']]
y = x[:, :, None] * x[:, None]
print y.sum(axis=0)
I received error:
"list indices must be integers, not
tuple"
But if x is x = numpy.array([[1, 7], [1.5, 8], [2, 5.5], [2, 9]])
then it's ok, but I don't have such input.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样:
How about the following:
首先,您应该创建包含浮点数而不是字符串的矩阵:
接下来,您可以使用 NumPy 的 广播规则来构建乘积矩阵:
最后,对所有矩阵求和:
打印
请注意,此解决方案避免了任何 Python 循环。
First, you should create the matrix containing floating point numbers instead of strings:
Next, you can use NumPy's broadcasting rules to build the product matrices:
Finally, sum over all matrices:
printing
Note that this solution avoids any Python loops.