Created
June 11, 2012 14:22
-
-
Save romichi/2910301 to your computer and use it in GitHub Desktop.
2つの文字列のcos類似度を測る
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- coding:utf-8 -*- | |
| import math | |
| #cos類似度 | |
| def cosSim(s1,s2): | |
| v1 = dict([(word, s1.count(word)) for word in s1 + s2]) #s1の各キャラクタと頻度 | |
| v2 = dict([(word, s2.count(word)) for word in s1 + s2]) #s2の各キャラクタと頻度 | |
| print v1 | |
| print v2 | |
| nume = sum([i*j for i,j in zip(v1.values(), v2.values())]) #分子 | |
| deno = math.sqrt(sum([i**2 for i in v1.values()]) * sum([i**2 for i in v2.values()])) #分母 | |
| return nume / deno | |
| s1 = 'a cat sat on the mat' | |
| s2 = 'cats are sitting on the mat' | |
| print cosSim(s1.split(' '), s2.split(' ')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment