我有一个包含2列的矩阵(矩阵“ X”具有两个功能-Feature0和Feature1),并且行数可变。对于每个样本(矩阵中的行),我想计算一个扩展行,使得每一行都是[feature0,feature1,feature0 ^ 2,feature1 ^ 2,feature0 * feature1、1]。
我写了下面的函数来完成工作。
def expand(X):
X_expanded = np.zeros((X.shape[0], 6))
for i in range(X_expanded.shape[0]):
for j in range(X_expanded.shape[1]):
if j <= 1:
X_expanded[i, j] = X[i, j]
elif j == 2:
X_expanded[i, j] = X[i, 0]*X[i, 0]
elif j == 3:
X_expanded[i, j] = X[i, 1]*X[i, 1]
elif j == 4:
X_expanded[i, j] = X[i, 0]*X[i, 1]
elif j == 5:
X_expanded[i, j] = 1
return X_expanded
我有疑问,是否有更有效或更“更好的方式”执行此计算?对我来说似乎很麻烦,所以欢迎您提出任何建议。预先感谢。
答案 0 :(得分:1)
尝试制作一个简单的函数并将其堆叠:
import numpy as np
def expanded(arr_2d):
c1, c2 = arr.T
return np.hstack([arr_2d, np.vstack([c1 ** 2, c2 ** 2, c1 * c2, np.ones(c1.shape[0])]).T])
大约快145倍:
arr = np.random.randint(0, 100, (10000, 2))
%timeit expand(arr)
# 41 ms ± 3.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit expanded(arr)
# 282 µs ± 10.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
验证检查:
np.all(expand(arr) == expanded(arr))
# True