### 场景描述

```A  B  C  D  E  F  G  H  I  J  K
0[0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5],
1[0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 3],
2[0, 0, 0, 0, 4, 0, 0, 1, 0, 4, 0],
3[5, 4, 5, 0, 0, 0, 0, 5, 5, 0, 0],
4[0, 0, 0, 0, 5, 0, 1, 0, 0, 5, 0],
5[4, 3, 4, 0, 0, 0, 0, 5, 5, 0, 1],
6[0, 0, 0, 4, 0, 4, 0, 0, 0, 0, 4],
7[0, 0, 0, 2, 0, 2, 5, 0, 0, 1, 2],
8[0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0],
9[1, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0]```

### 相似度计算

```def cosSim(inA,inB):
num = float(inA.T*inB)
denom = la.norm(inA)*la.norm(inB)
return 0.5+0.5*(num/denom)```

### 推荐分计算

```#dataMat 用户与美食的矩阵
#user 用户序号
#simMeas 相似度算法
#item 美食商品
def standEst(dataMat, user, simMeas, item):
n = shape(dataMat)[1]#商品数
simTotal = 0.0; ratSimTotal = 0.0
for j in range(n):#所有商品，遍历
userRating = dataMat[user,j]#user对该商品的推荐分
if userRating == 0: continue#如果user 未推荐该商品则过滤
#logical_and逻辑与，nonzero非零判断，overLap为均为商品item，j推荐的用户
overLap = nonzero(logical_and(dataMat[:,item].A>0, \
dataMat[:,j].A>0))[0]
if len(overLap) == 0: similarity = 0
#以此overLap，计算两商品的相似度。
else: similarity = simMeas(dataMat[overLap,item], \
dataMat[overLap,j])
print('the %d and %d similarity is: %f' % (item, j, similarity))
simTotal += similarity
ratSimTotal += similarity * userRating
if simTotal == 0: return 0
else: return ratSimTotal/simTotal```

```def svdEst(dataMat, user, simMeas, item):
n = shape(dataMat)[1]
simTotal = 0.0; ratSimTotal = 0.0
U,Sigma,VT = la.svd(dataMat) #奇异值分解
Sig4 = mat(eye(4)*Sigma[:4]) #构建对角矩阵
xformedItems = dataMat.T * U[:,:4] * Sig4.I  #数据维度转换
for j in range(n):
userRating = dataMat[user,j]
if userRating == 0 or j==item: continue
similarity = simMeas(xformedItems[item,:].T,\
xformedItems[j,:].T)
print('the %d and %d similarity is: %f' % (item, j, similarity))
simTotal += similarity
ratSimTotal += similarity * userRating
if simTotal == 0: return 0
else: return ratSimTotal/simTotal```

```#dataMat 用户与美食的矩阵
#user 用户序号
#N 推荐前N个商品
#simMeas 相似度计算算法
#estMethod 推荐分计算算法
def recommend(dataMat, user, N=3, simMeas=cosSim, estMethod=standEst):
#找出user未评分的商品
unratedItems = nonzero(dataMat[user,:].A==0)[1]#find unrated items
if len(unratedItems) == 0: return 'you rated everything'
itemScores = []
#依次计算这些商品的推荐分
for item in unratedItems:
estimatedScore = estMethod(dataMat, user, simMeas, item)
itemScores.append((item, estimatedScore))
#返回前N个较好分的结果
return sorted(itemScores, key=lambda jj: jj[1], reverse=True)[:N]```