在我实现神经网络之前,我需要预处理一些数据。但我是数学菜鸟,我找不到 Python 中的函数来做我想做的事。
我有这样的矩阵:
[[0 4 ... 0 ]
[0 3 ... 6 ]
[0 3 ... 10]]
我有一个数字,例如 7,它决定了转换后新矩阵中必须有多少行。我想要实现的是:
[[0 4 ... 0 ]
[0 3.66 ... 2 ]
[0 3.33 ... 4 ]
[0 3 ... 6 ]
[0 3 ... 7.33]
[0 3 ... 8.66]
[0 3 ... 10 ]]
您会看到第一列没有变化,因为对于原始矩阵中的每一行,第一列都是零。 对于第二列,第一行在四个第一行上缓慢减少,从 4 到 3,然后稳定下来。 最后一列从 0 增加到 10,增加 6。
一个数学专业的学生告诉我这是一个插值,但我在 scipy 的文档中找不到如何正确地做到这一点。
你知道我该怎么做吗?
请您参考如下方法:
您可以使用 numpy.interp。由于它仅适用于一维,因此我使用了 for 循环。
import numpy as np
# You input matrix:
a = np.array([[0, 4, 0], [0, 3, 6], [0, 3, 10]])
# Put the shape you need here:
old_dim, new_dim = a.shape[1], 7
# Define new matrix
b = np.zeros((7, a.shape[1]))
# Define linspace that will serve for interpolation
nls, ols = np.linspace(0, 1, new_dim), np.linspace(0, 1, old_dim)
# Interpolate on each column
for col in range(old_dim):
b[:,col] = np.interp(nls, ols, a[:,col])
print b
输出:
[[ 0. 4. 0. ]
[ 0. 3.66666667 2. ]
[ 0. 3.33333333 4. ]
[ 0. 3. 6. ]
[ 0. 3. 7.33333333]
[ 0. 3. 8.66666667]
[ 0. 3. 10. ]]
不是二维插值函数,但是我对scipy不是很熟悉(numpy也没有)。
编辑 修复非方阵问题
import numpy as np
a = np.array([[0, 4, 0], [0, 3, 6], [0, 3, 10]])
old_dim, n_col, new_dim = a.shape[0], a.shape[1], 7
b = np.zeros((7, n_col))
nls, ols = np.linspace(0, 1, new_dim), np.linspace(0, 1, old_dim)
for col in range(n_col):
b[:,col] = np.interp(nls, ols, a[:,col])
print b
我的错误,我在某些时候颠倒了 n_col 和 n_rows。
