test14.py

  1. #-*- coding:utf-8
  2. import sys
  3. sys.path.append("svdRec.py")
  4.  
  5. import svdRec
  6. from numpy import *
  7. from numpy import linalg as la
  8.  
  9. # U, Sigma, VT = linalg.svd([[1, 1], [7, 7]])
  10. # print(U)
  11. # print(Sigma)
  12. # print(VT)
  13.  
  14. # Data = svdRec.loadExData()
  15. # U, Sigma, VT = linalg.svd(Data)
  16. # print(Sigma)
  17. #
  18. # Sig3 = mat([[Sigma[0], 0, 0], [0, Sigma[1], 0], [0, 0, Sigma[2]]])
  19. # res = U[:, :3]*Sig3*VT[:3, :]
  20. # print("res:")
  21. # print(res)
  22. #
  23. # myMat = mat(svdRec.loadExData())
  24. # ecl = svdRec.ecludSim(myMat[:, 0], myMat[:, 4])
  25. # print("ecl:")
  26. # print(ecl)
  27. # cos = svdRec.cosSim(myMat[:, 0], myMat[:, 4])
  28. # print("cos:")
  29. # print(cos)
  30. # pears = svdRec.pearsSim(myMat[:, 0], myMat[:, 4])
  31. # print("pears:")
  32. # print(pears)
  33. # myMat = mat(svdRec.loadExData())
  34. # myMat[0, 1] = myMat[0, 0] = myMat[1, 0] = myMat[2, 0] = 4
  35. # myMat[3, 3] = 2
  36. # print("myMat:")
  37. # print(myMat)
  38. #
  39. # tuiJian = svdRec.recommend(myMat, 2)
  40. # print("tuiJian:")
  41. # print(tuiJian)
  42. #
  43. # tuiJian1 = svdRec.recommend(myMat, 2, simMeas = svdRec.ecludSim)
  44. # print("tuiJian1:")
  45. # print(tuiJian1)
  46. #
  47. # tuiJian2 = svdRec.recommend(myMat, 2, simMeas = svdRec.pearsSim)
  48. # print("tuiJian2:")
  49. # print(tuiJian2)
  50.  
  51. # myMat = mat(svdRec.loadExData2())
  52. # U, Sigma, VT = la.svd(mat(svdRec.loadExData2()))
  53. # print(Sigma)
  54. #
  55. # Sig2 = Sigma**2
  56. # total = sum(Sig2)
  57. # total9 = total*0.9
  58. # print("total9:")
  59. # print(total9)
  60. #
  61. # total3 = sum(Sig2[:3])
  62. # print("total3:")
  63. # print(total3)
  64.  
  65. # svdRes = svdRec.recommend(myMat, 1, estMethod = svdRec.svdEst)
  66. # print("svdRes:")
  67. # print(svdRes)
  68.  
  69. originalMat = svdRec.imgCompress(2)
  70. print(originalMat)
  71.  
  72. print("over!!!")
  1. svdRec.py
  1. '''
  2. Created on Mar 8, 2011
  3.  
  4. @author: Peter
  5. '''
  6. from numpy import *
  7. from numpy import linalg as la
  8.  
  9. def loadExData():
  10. return[[0, 0, 0, 2, 2],
  11. [0, 0, 0, 3, 3],
  12. [0, 0, 0, 1, 1],
  13. [1, 1, 1, 0, 0],
  14. [2, 2, 2, 0, 0],
  15. [5, 5, 5, 0, 0],
  16. [1, 1, 1, 0, 0]]
  17.  
  18. def loadExData2():
  19. return[[0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5],
  20. [0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 3],
  21. [0, 0, 0, 0, 4, 0, 0, 1, 0, 4, 0],
  22. [3, 3, 4, 0, 0, 0, 0, 2, 2, 0, 0],
  23. [5, 4, 5, 0, 0, 0, 0, 5, 5, 0, 0],
  24. [0, 0, 0, 0, 5, 0, 1, 0, 0, 5, 0],
  25. [4, 3, 4, 0, 0, 0, 0, 5, 5, 0, 1],
  26. [0, 0, 0, 4, 0, 4, 0, 0, 0, 0, 4],
  27. [0, 0, 0, 2, 0, 2, 5, 0, 0, 1, 2],
  28. [0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0],
  29. [1, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0]]
  30.  
  31. def ecludSim(inA,inB):
  32. return 1.0/(1.0 + la.norm(inA - inB))
  33.  
  34. def pearsSim(inA,inB):
  35. if len(inA) < 3 : return 1.0
  36. return 0.5+0.5*corrcoef(inA, inB, rowvar = 0)[0][1]
  37.  
  38. def cosSim(inA,inB):
  39. num = float(inA.T*inB)
  40. denom = la.norm(inA)*la.norm(inB)
  41. return 0.5+0.5*(num/denom)
  42.  
  43. def standEst(dataMat, user, simMeas, item):
  44. n = shape(dataMat)[1]
  45. simTotal = 0.0; ratSimTotal = 0.0
  46. for j in range(n):
  47. userRating = dataMat[user,j]
  48. if userRating == 0: continue
  49. # test0 = dataMat[:,item].A>0
  50. # test1 = dataMat[:,j].A>0
  51. # test2 = logical_and(dataMat[:,item].A>0, dataMat[:,j].A>0)
  52. overLap = nonzero(logical_and(dataMat[:,item].A>0, dataMat[:,j].A>0))[0]
  53. if len(overLap) == 0: similarity = 0
  54. else: similarity = simMeas(dataMat[overLap,item], dataMat[overLap,j])
  55. print('the %d and %d similarity is: %f' % (item, j, similarity))
  56. simTotal += similarity
  57. ratSimTotal += similarity * userRating
  58. if simTotal == 0: return 0
  59. else: return ratSimTotal/simTotal
  60.  
  61. def svdEst(dataMat, user, simMeas, item):
  62. n = shape(dataMat)[1]
  63. simTotal = 0.0; ratSimTotal = 0.0
  64. U,Sigma,VT = la.svd(dataMat)
  65. Sig4 = mat(eye(4)*Sigma[:4]) #arrange Sig4 into a diagonal matrix
  66. xformedItems = dataMat.T * U[:,:4] * Sig4.I #create transformed items
  67. for j in range(n):
  68. userRating = dataMat[user,j]
  69. if userRating == 0 or j==item: continue
  70. similarity = simMeas(xformedItems[item,:].T, xformedItems[j,:].T)
  71. print('the %d and %d similarity is: %f' % (item, j, similarity))
  72. simTotal += similarity
  73. ratSimTotal += similarity * userRating
  74. if simTotal == 0: return 0
  75. else: return ratSimTotal/simTotal
  76.  
  77. def recommend(dataMat, user, N=3, simMeas=cosSim, estMethod=standEst):
  78. unratedTest = nonzero(dataMat[user,:].A==0)
  79. unratedItems = nonzero(dataMat[user,:].A==0)[1]#find unrated items
  80. if len(unratedItems) == 0: return 'you rated everything'
  81. itemScores = []
  82. for item in unratedItems:
  83. estimatedScore = estMethod(dataMat, user, simMeas, item)
  84. itemScores.append((item, estimatedScore))
  85. # testSort = sorted(itemScores, key=lambda jj: jj[1], reverse=True)[:N]
  86. return sorted(itemScores, key=lambda jj: jj[1], reverse=True)[:N]
  87.  
  88. def printMat(inMat, thresh=0.8):
  89. for i in range(32):
  90. for k in range(32):
  91. if float(inMat[i,k]) > thresh:
  92. print(1),
  93. else: print(0),
  94. print('')
  95.  
  96. def imgCompress(numSV=3, thresh=0.8):
  97. myl = []
  98. for line in open('0_5.txt').readlines():
  99. newRow = []
  100. for i in range(32):
  101. newRow.append(int(line[i]))
  102. myl.append(newRow)
  103. myMat = mat(myl)
  104. print("****original matrix******")
  105. printMat(myMat, thresh)
  106. U,Sigma,VT = la.svd(myMat)
  107. SigRecon = mat(zeros((numSV, numSV)))
  108. for k in range(numSV):#construct diagonal matrix from vector
  109. SigRecon[k,k] = Sigma[k]
  110. reconMat = U[:,:numSV]*SigRecon*VT[:numSV,:]
  111. print("****reconstructed matrix using %d singular values******" % numSV)
  112. printMat(reconMat, thresh)
  1.  

机器学习14—SVD学习笔记的更多相关文章

  1. 《机器学习实战》学习笔记第十四章 —— 利用SVD简化数据

    相关博客: 吴恩达机器学习笔记(八) —— 降维与主成分分析法(PCA) <机器学习实战>学习笔记第十三章 —— 利用PCA来简化数据 奇异值分解(SVD)原理与在降维中的应用 机器学习( ...

  2. 《机器学习实战》学习笔记第九章 —— 决策树之CART算法

    相关博文: <机器学习实战>学习笔记第三章 —— 决策树 主要内容: 一.CART算法简介 二.分类树 三.回归树 四.构建回归树 五.回归树的剪枝 六.模型树 七.树回归与标准回归的比较 ...

  3. (转载)林轩田机器学习基石课程学习笔记1 — The Learning Problem

    (转载)林轩田机器学习基石课程学习笔记1 - The Learning Problem When Can Machine Learn? Why Can Machine Learn? How Can M ...

  4. Coursera台大机器学习基础课程学习笔记1 -- 机器学习定义及PLA算法

    最近在跟台大的这个课程,觉得不错,想把学习笔记发出来跟大家分享下,有错误希望大家指正. 一机器学习是什么? 感觉和 Tom M. Mitchell的定义几乎一致, A computer program ...

  5. 《SAS编程和数据挖掘商业案例》第14部分学习笔记

    继续<SAS编程与数据挖掘商业案例>学习笔记系列,本次重点:经常使用全程语句 所谓全程语句.是指能够用在不论什么地方的sas语句,既能够用在data数据步语句里面,也能够用在proc过程步 ...

  6. MNIST机器学习入门【学习笔记】

    平台信息:PC:ubuntu18.04.i5.anaconda2.cuda9.0.cudnn7.0.5.tensorflow1.10.GTX1060 作者:庄泽彬(欢迎转载,请注明作者) 说明:本文是 ...

  7. 《机器学习实战》学习笔记——第14章 利用SVD简化数据

    一. SVD 1. 基本概念: (1)定义:提取信息的方法:奇异值分解Singular Value Decomposition(SVD) (2)优点:简化数据, 去除噪声,提高算法的结果 (3)缺点: ...

  8. [转]Python3《机器学习实战》学习笔记(一):k-近邻算法(史诗级干货长文)

    转自http://blog.csdn.net/c406495762/article/details/75172850 版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[-] 一 简 ...

  9. 林轩田机器学习基石课程学习笔记5 — Training versus Testing

    上节课,我们主要介绍了机器学习的可行性.首先,由NFL定理可知,机器学习貌似是不可行的.但是,随后引入了统计学知识,如果样本数据足够大,且hypothesis个数有限,那么机器学习一般就是可行的.本节 ...

随机推荐

  1. HDOJ 1300 Pearls 斜率优化dp

    原题连接:http://acm.hdu.edu.cn/showproblem.php?pid=1300 题意: 题目太长了..自己看吧 题解: 看懂题目,就会发现这是个傻逼dp题,斜率优化一下就好 代 ...

  2. 【状态压缩DP】【BZOJ1087】【SCOI2005】互不侵犯king

    1087: [SCOI2005]互不侵犯King Time Limit: 10 Sec  Memory Limit: 162 MBSubmit: 3135  Solved: 1825[Submit][ ...

  3. 用swift开发自己的MacOS锁屏软件(3)

    前两篇中实现了MacOS端的锁屏软件,现在需要再实现一个移动端的app用来实现和mac的通信,以后的文章可能就会两个项目来回穿插了. 写完MacOS的软件又回来接着写iOS真的是享受,看着堆积如山的各 ...

  4. Bluetooth篇 开发实例之十 官网的Bluetooth Chat sample app.

    运行的时候,会报错: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Action ...

  5. Jenkins配置Java项目1(Java+Maven+Tomcat+SVN/Git)

    先收集几个网址,后续再自己动手过一遍 http://www.cnblogs.com/leefreeman/p/4211530.html http://www.cnblogs.com/sunzhench ...

  6. 基于avalon+jquery做的bootstrap分页控件

    刚开始学习avalon,项目需要就尝试写了个分页控件Pager.js:基于BootStrap样式这个大家都很熟悉 在这里推荐下国产前端神器avalon:确实好用,帮我解决了很多前端问题. 不多说了,代 ...

  7. FreeRTOS+FreeModbus+神舟IV号

    下面的这个例子是FreeModbus和FreeRTOS在神舟IV号上的应用,仅当做学习用途. 这个demo完成的功能也比较简单,创建了两个任务,一个任务用于控制板子上的LED1,使它每1秒钟闪烁一次. ...

  8. iOS GCD 拾遗

    GCD里就有三种queue(分派队列)来处理. 1. Main queue:(主队列) 顾名思义,运行在主线程,由dispatch_get_main_queue获得.和ui相关的就要使用Main Qu ...

  9. 利用jquery.form.js实现将form提交转为ajax方式提交的方法(带上传的表单提交)

    提供一种方法就是利用jquery.form.js. (1)这个框架集合form提交.验证.上传的功能. 核心方法 -- ajaxForm() 和 ajaxSubmit() $('#myForm').a ...

  10. 2017.7.1 mysql安装与启动(已验证可以使用)

    下载地址:http://learning.happymmall.com/ 之前一直用解压版安装,启动mysql服务的时候总是失败,这次用mysql installer安装一遍,终于成功启动. 1.下载 ...