我想在Python上实现NMF,以下是我在Google上发现的内容:
def matrix_factorization(R, P, Q, K, steps = 500, alpha = 0.0002, beta = 0.02):
Q = Q.T
for step in xrange(steps):
for i in xrange(len(R)):
for j in xrange(len(R[i])):
if R[i][j] > 0:
eij = R[i][j] - numpy.dot(P[i,:],Q[:,j])
for k in xrange(K):
P[i][k] = P[i][k] + alpha * (2 * eij * Q[k][j] - beta * P[i][k])
Q[k][j] = Q[k][j] + alpha * (2 * eij * P[i][k] - beta * Q[k][j])
eR = numpy.dot(P, Q)
e = 0
for i in xrange(len(R)):
for j in xrange(len(R[i])):
if R[i][j] > 0:
e = e + pow(R[i][j] - numpy.dot(P[i,:],Q[:,j]), 2)
for k in xrange(K):
e = e + (beta/2) * ( pow(P[i][k],2) + pow(Q[k][j],2) )
if e < 0.001:
break
return P, Q.T
当我运行代码时,某些值是负数,这可能不符合技术的定义。
我注意到误差项 eij = R [i] [j] - numpy.dot(P [i,:],Q [:,j])不是绝对值,
所以我尝试了eij = numpy.fabs(eij),它返回在double_scalars中遇到的 RuntimeWarning:overflow 。
返回绝对值的其他方法(例如math.abs()等)也不起作用。 请帮帮我!