我想使用科学工具包-学习NMF (从这里) (或任何其他NMF,如果它做了,实际上)。
具体来说,我有一个输入矩阵(这是一个音频震级谱图),我想分解它。
我已经预先计算了W矩阵。如何在固定W中使用sklearn.decompose.NMF?我没有发现任何其他问题在问这个。
我看到这方法在fit参数中也提到了类似的内容:“如果为False,则假定组件是预先计算的,并存储在转换器中,并且不会更改。”然而,我不知道如何使变压器成为目标。
发布于 2017-06-11 11:18:08
代码的这一部分对内部处理做了一点解释。
听起来你想要修正W,根据代码,你只能修正H,而优化W,这不是问题,因为你只需要转换那些矩阵(反转它们的角色)。
这样做,代码会说:使用init='custom'并设置update_h=False。
因此,总的来说,我希望使用方式类似于(基于示例这里):
未经测试!
import numpy as np
X = np.array([[1,1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]])
fixed_W = np.array([[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]) # size=3 just an example
# might break
fixed_H = fixed_W.T # interpret W as H (transpose)
from sklearn.decomposition import NMF
model = NMF(n_components=2, init='custom', H=fixed_H, update_H=False, random_state=0)
model.fit(X) 您可能希望在再次求解之后切换变量。
编辑:,正如注释中提到的,上面未测试的代码将无法工作。我们需要使用更低级别的函数来实现这一点。
这里有一个快速的黑客攻击(在这里,我不太关心正确的预处理;转置和合作)这应该让你能够处理好你的任务:
import numpy as np
X = np.array([[1,1], [2, 1], [3, 1.2], [4, 1], [5, 0.8], [6, 1]])
fixed_W = np.array([[0.4,0.4],[0.2,0.1]]) # size=2 just an example
fixed_H = fixed_W.T # interpret W as H (transpose)
from sklearn.decomposition import NMF, non_negative_factorization
W, H, n_iter = non_negative_factorization(X, n_components=2, init='random', random_state=0)
print(W)
print(H)
print('error: ')
print(W.dot(H) - X) # just a demo, it's not the loss minimized!
W, H, n_iter = non_negative_factorization(X, n_components=2, init='custom', random_state=0, update_H=False, H=fixed_H)
print(W)
print(H)
print('error: ')
print(W.dot(H) - X)输出:
[[ 0. 0.46880684]
[ 0.55699523 0.3894146 ]
[ 1.00331638 0.41925352]
[ 1.6733999 0.22926926]
[ 2.34349311 0.03927954]
[ 2.78981512 0.06911798]]
[[ 2.09783018 0.30560234]
[ 2.13443044 2.13171694]]
error:
[[ 6.35579822e-04 -6.36528773e-04]
[ -3.40231372e-04 3.40739354e-04]
[ -3.45147253e-04 3.45662574e-04]
[ -1.31898319e-04 1.32095249e-04]
[ 9.00218123e-05 -9.01562192e-05]
[ 8.58722020e-05 -8.60004133e-05]]
[[ 3. 0. ]
[ 5. 0. ]
[ 4.51221142 2.98707026]
[ 0.04070474 9.95690087]
[ 0. 12.23529412]
[ 0. 14.70588235]]
[[ 0.4 0.2]
[ 0.4 0.1]]
error:
[[ 2.00000000e-01 -4.00000000e-01]
[ -2.22044605e-16 -1.11022302e-16]
[ -2.87327549e-04 1.14931020e-03]
[ -9.57758497e-04 3.83103399e-03]
[ -1.05882353e-01 4.23529412e-01]
[ -1.17647059e-01 4.70588235e-01]]https://stackoverflow.com/questions/44478676
复制相似问题