# 二、非负矩阵分解

## 2.4、非负矩阵分解的实现

#!/bin/python

from numpy import *

f = open(file_path)
V = []
for line in f.readlines():
lines = line.strip().split("\t")
data = []
for x in lines:
data.append(float(x))
V.append(data)
return mat(V)

def train(V, r, k, e):
m, n = shape(V)
W = mat(random.random((m, r)))
H = mat(random.random((r, n)))

for x in xrange(k):
#error
V_pre = W * H
E = V - V_pre
#print E
err = 0.0
for i in xrange(m):
for j in xrange(n):
err += E[i,j] * E[i,j]
print err

if err < e:
break

a = W.T * V
b = W.T * W * H
#c = V * H.T
#d = W * H * H.T
for i_1 in xrange(r):
for j_1 in xrange(n):
if b[i_1,j_1] != 0:
H[i_1,j_1] = H[i_1,j_1] * a[i_1,j_1] / b[i_1,j_1]

c = V * H.T
d = W * H * H.T
for i_2 in xrange(m):
for j_2 in xrange(r):
if d[i_2, j_2] != 0:
W[i_2,j_2] = W[i_2,j_2] * c[i_2,j_2] / d[i_2, j_2]

return W,H

if __name__ == "__main__":
#file_path = "./data_nmf"
file_path = "./data1"

W, H = train(V, 2, 100, 1e-5 )

print V
print W
print H
print W * H

'''
Date:20160411
@author: zhaozhiyong
'''

from pylab import *
from numpy import *

data = []

f = open("result_nmf")
for line in f.readlines():
lines = line.strip()
data.append(lines)

n = len(data)
x = range(n)
plot(x, data, color='r',linewidth=3)
plt.title('Convergence curve')
plt.xlabel('generation')
plt.ylabel('loss')
show()

# 参考文献

292 篇文章59 人订阅

0 条评论

## 相关文章

### python科学计算之numpy

1.np.logspace(start,stop,num): 函数表示的意思是;在（start,stop）间生成等比数列num个 eg:  import num...

3706

2161

1662

1414

1.7K10

953

### Tensorflow使用的预训练的resnet_v2_50，resnet_v2_101，resnet_v2_152等模型预测，训练

tensorflow 实现：Inception，ResNet ， VGG ， MobileNet， Inception-ResNet； 地址： https:/...

1K8

48711

69612

1222