python - Python 中的矩阵补全

标签 python numpy machine-learning scikit-learn mathematical-optimization

假设我有一个矩阵:

> import numpy as nap
> a = np.random.random((5,5))

array([[ 0.28164485,  0.76200749,  0.59324211,  0.15201506,  0.74084168],
       [ 0.83572213,  0.63735993,  0.28039542,  0.19191284,  0.48419414],
       [ 0.99967476,  0.8029097 ,  0.53140614,  0.24026153,  0.94805153],
       [ 0.92478   ,  0.43488547,  0.76320656,  0.39969956,  0.46490674],
       [ 0.83315135,  0.94781119,  0.80455425,  0.46291229,  0.70498372]])

然后我用 np.NaN 在上面打了一些洞,例如:

> a[(1,4,0,3),(2,4,2,0)] = np.NaN; 

array([[ 0.80327707,  0.87722234,         nan,  0.94463778,  0.78089194],
       [ 0.90584284,  0.18348667,         nan,  0.82401826,  0.42947815],
       [ 0.05913957,  0.15512961,  0.08328608,  0.97636309,  0.84573433],
       [        nan,  0.30120861,  0.46829231,  0.52358888,  0.89510461],
       [ 0.19877877,  0.99423591,  0.17236892,  0.88059185,        nan ]])

我想使用来自矩阵其余条目的信息来填充 nan 条目。例如,使用出现 nan 条目的列的平均值 值。

更一般地说,Python 中是否有用于 matrix completion 的库? ? (例如,类似 Candes & Recht's convex optimization method 的内容)。

背景:

这个问题在机器学习中经常出现。例如,在分类/回归或 collaborative filtering 中处理缺失的特征时(例如,参见 Wikipediahere 上的 Netflix 问题)

最佳答案

如果你安装了最新的 scikit-learn 版本 0.14a1,你可以使用它 Shiny 的新 Imputer 类:

>>> from sklearn.preprocessing import Imputer
>>> imp = Imputer(strategy="mean")
>>> a = np.random.random((5,5))
>>> a[(1,4,0,3),(2,4,2,0)] = np.nan
>>> a
array([[ 0.77473361,  0.62987193,         nan,  0.11367791,  0.17633671],
       [ 0.68555944,  0.54680378,         nan,  0.64186838,  0.15563309],
       [ 0.37784422,  0.59678177,  0.08103329,  0.60760487,  0.65288022],
       [        nan,  0.54097945,  0.30680838,  0.82303869,  0.22784574],
       [ 0.21223024,  0.06426663,  0.34254093,  0.22115931,         nan]])
>>> a = imp.fit_transform(a)
>>> a
array([[ 0.77473361,  0.62987193,  0.24346087,  0.11367791,  0.17633671],
       [ 0.68555944,  0.54680378,  0.24346087,  0.64186838,  0.15563309],
       [ 0.37784422,  0.59678177,  0.08103329,  0.60760487,  0.65288022],
       [ 0.51259188,  0.54097945,  0.30680838,  0.82303869,  0.22784574],
       [ 0.21223024,  0.06426663,  0.34254093,  0.22115931,  0.30317394]])

在此之后,您可以使用 imp.transform 对其他数据进行相同的转换,使用 impa 中学到的均值. Imputers 绑定(bind)到 scikit-learn Pipeline 对象中,因此您可以在分类或回归管道中使用它们。

如果您想等待稳定版本,那么 0.14 应该会在下周发布。

全面披露:我是一名 scikit-learn 核心开发人员

关于python - Python 中的矩阵补全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17982931/

相关文章:

python-3.x - 通过 concurrent.futures 多处理填充 numpy 数组

machine-learning - 多元高斯分布中如何处理其中一个特征的零标准差

machine-learning - Kohonen SOM map : Normalizing the input with unknown range

python - 我无法从数据帧保存到 postgresql

python - flask 错误 : typeerror run() got an unexpected keyword argument 'host'

python - 我的 PCA 有什么问题?

python - 在 Pandas 数据框中随机插入 NA 的值

python - 生成指定范围内的N个唯一随机整数

python - 具有交叉验证的scikits混淆矩阵

Python float 及正确使用