gpt4 book ai didi

python - 消除 numpy 实现中的循环

转载 作者:行者123 更新时间:2023-11-28 21:24:32 25 4
gpt4 key购买 nike

我在 numpy 中有以下数据集

indices | real data (X)    |targets (y)
| |
0 0 | 43.25 665.32 ... |2.4 } 1st block
0 0 | 11.234 |-4.5 }
0 1 ... ... } 2nd block
0 1 }
0 2 } 3rd block
0 2 }
1 0 } 4th block
1 0 }
1 0 }
1 1 ...
1 1
1 2
1 2
2 0
2 0
2 1
2 1
2 1
...

这些是我的变量

idx1 = data[:,0]
idx2 = data[:,1]
X = data[:,2:-1]
y = data[:,-1]

我还有一个变量 W,它是一个 3D 数组。

我需要在代码中做的是循环遍历数据集中的所有 block ,并在经过一些计算后为每个 block 返回一个标量,然后将所有标量相加,并将其存储在名为 cost 的变量中。问题是循环实现非常慢,所以如果可能的话,我会尝试对其进行矢量化。这是我当前的代码。是否可以在 numpy 中不使用 for 循环来执行此操作?

IDX1 = 0
IDX2 = 1

# get unique indices
idx1s = np.arange(len(np.unique(data[:,IDX1])))
idx2s = np.arange(len(np.unique(data[:,IDX2])))

# initialize global sum variable to 0
cost = 0
for i1 in idx1s:
for i2 in idx2:

# for each block in the dataset
mask = np.nonzero((data[:,IDX1] == i1) & (data[:,IDX2] == i2))

# get variables for that block
curr_X = X[mask,:]
curr_y = y[mask]
curr_W = W[:,i2,i1]

# calculate a scalar
pred = np.dot(curr_X,curr_W)
sigm = 1.0 / (1.0 + np.exp(-pred))
loss = np.sum((sigm- (0.5)) * curr_y)

# add result to global cost
cost += loss

这里是一些示例数据

data = np.array([[0,0,5,5,7],
[0,0,5,5,7],
[0,1,5,5,7],
[0,1,5,5,7],
[1,0,5,5,7],
[1,1,5,5,7]])
W = np.zeros((2,2,2))
idx1 = data[:,0]
idx2 = data[:,1]
X = data[:,2:-1]
y = data[:,-1]

最佳答案

那个 W 很棘手......实际上,除了获取 W 的正确切片来执行 np.dot< 之外,你的 block 非常不相关 与相应的 X,所以我创建了一个简单的 aligned_W 数组,如下所示:

aligned_W = W[:, idx2, idx1]

这是一个形状为 (2, rows) 的数组,其中 rows 是数据集的行数。您现在可以在没有任何 for 循环的情况下继续进行整个计算:

from numpy.core.umath_tests import inner1d
pred = inner1d(X, aligned_W.T)
sigm = 1.0 / (1.0 + np.exp(-pred))
loss = (sigm - 0.5) * curr_y
cost = np.sum(loss)

关于python - 消除 numpy 实现中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15904819/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com