英文:
Create this simple array
问题
我有两个一维数组 u 和 q,如下所示:
import numpy as np
n = 300
u1 = np.random.uniform(0.5, 4.5, size=n)
u2 = 2 / u1 + np.random.normal(scale=0.09, size=n)
u = np.array([u1, u2])
d = np.random.uniform(0.0, np.pi, size=100)
q = np.array([np.cos(d), np.sin(d)])
我有以下代码:
np.max(np.quantile(np.dot(q[:, 0], u[:, ]), 0.01)) - np.max(np.quantile(np.dot(q[:, 0], u[:, ]), 0.99))
对于 q[:, 0],但我想对每个 q[:,m](其中m从1到100,即q 的所有列)执行相同的操作,并将它们全部保存在一个新的数组中。如何实现?
英文:
I have two one-dimensional arrays u and q as follows:
import numpy as np
n = 300
u1 = np.random.uniform(0.5, 4.5, size=n)
u2 = 2 / u1 + np.random.normal(scale=0.09, size=n)
u = np.array([u1,u2])
and
d=np.random.uniform(0.0, np.pi, size=100)
q = np.array([np.cos(d), np.sin(d)])
I have the following
np.max(np.quantile(np.dot(q[:, 0],u[:,]), 0.01))-np.max(np.quantile(np.dot(q[:, 0],u[:,]), 0.99))
for q[:, 0], but I want to have it for every q[:,m] from m=1 to 100 (I mean for all columns of q) and save them all in a new array.
How can I do that?
答案1
得分: 1
我不确定你想做什么以及你期望的结果是什么。我在解释时走得比较慢,这样如果我理解错了你的想法,你可以修改我的代码以适应你的需求。
用以下代码替换 np.dot(q[:, 0],u[:,]:
np.dot(q.transpose(), u)
np.dot(q[:, 0],u[:,] 的形状是 (300),而 np.dot(q.transpose(), u) 的形状是 (100, 300)。这基本上是对 q 的每一列与 u 进行点积。
用以下代码替换你的分位数操作:
np.quantile(np.dot(q.transpose(), u), q=0.01, axis=-1)
# 或者对另一个分位数使用 q=0.99
通过指定一个轴,你限制了 quantile 仅在该轴上操作,而不是在整个数组上操作。结果的形状是 (100)。
之前,你的分位数操作返回一个标量,因此将其包装在 np.max 中没有任何效果。现在它返回了一个大小为 100 的数组的最大值。最后一行应该是:
np.max(np.quantile(np.dot(q.transpose(), u), q=0.01, axis=-1))
- np.max(np.quantile(np.dot(q.transpose(), u), q=0.99, axis=-1))
结果是一个标量。
英文:
I'm not sure what you're trying to do and what result you expect. I'm going slow with my explanation so that if I got your idea wrong, you can modify my code to suit your need.
Replace np.dot(q[:, 0],u[:,] with:
np.dot(q.transpose(), u)
The shape of np.dot(q[:, 0],u[:,] is (300), and that of np.dot(q.transpose(), u) is (100, 300). This basically dot-product each of 100 columns of q with u.
Replace your quantile operation with:
np.quantile(np.dot(q.transpose(), u), q=0.01, axis=-1)
# or q=0.99 for the other one
By specifying an axis, you restrict quantile to only operate on that axis, rather than on the entire array. The result has shape (100).
Before, your quantile operation returns a scalar, so wrapping it in np.max does nothing. Now it returns the max of a 100-size array. The final line should be:
np.max(np.quantile(np.dot(q.transpose(), u), q=0.01, axis=-1))
- np.max(np.quantile(np.dot(q.transpose(), u), q=0.99, axis=-1))
The result is a scalar.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论