Preparation for ML on Python

I am going to introduce basic ML(Machine Learning) implementation by Python.
In this article, I introduce basic similarity, cosine similarity, and basic distance, euclidean distance.
the sample code is below…

#! usr/bin/env python
# -*- coding: utf-8 -*-

#コサイン類似度
def simcos(D, l):
    import numpy
    v1 = numpy.array(D[l[0]], dtype=float)
    v2 = numpy.array(D[l[1]], dtype=float)
    return numpy.sum(v1*v2) / (numpy.sqrt(numpy.sum(v1*v1))*
                               numpy.sqrt(numpy.sum(v2*v2)))

#ユークリッド距離
def euclidean_distance(D, l):
    import numpy
    x = D[l[0]]
    y = D[l[1]]
    if type(x) is list:
        x = numpy.array(x)
    if type(y) is list:
        y = numpy.array(y)
    return numpy.sqrt(numpy.sum((x-y)*(x-y)))

#lの中からfを最大化する組合せを返す
#組合せの数はn=len(l)Ck個
def argmax(l, k, f):
    #組合せを作る(雑なやり方…
    def c(i, a):
        fs = frozenset(a)
        if len(fs) == k:
            C.add(fs)
        for j in range(i, n):
            a.append(j)
            c(i+1, a)
            a.remove(j)
    n = len(l)
    C = set()
    c(0, list())#組合せ作成
    max = -float('inf')
    maxcomb = None
    for i in C:#iは基数kのフローズンセット
        i = list(i)
        val = f(D, i)
        print i, val
        if val > max:
            max = val
            maxcomb = i
    return maxcomb

import numpy

#2次元データの作成
print numpy.random.random_sample(2)
#3次元データの作成
print numpy.random.random_sample(3)
print ""

#cos類似度
print u"cos類似度"
x = numpy.random.random_sample(3)
y = numpy.random.random_sample(3)
print "x:", x
print "y:", y
print simcos([x, y], [0, 1])
print ""

#ユークリッド距離
print u"ユークリッド距離"
#x = numpy.array([1., 1.])
#y = numpy.array([0., 0.])
print "x:", x
print "y:", y
print euclidean_distance([x, y], [0, 1])
print ""

#d次元の標本Dを作成、大きさはN
N = 3
d = 3
D = []
for i in range(0, N):
    D.append(numpy.random.random_sample(d))
#標本をプリント、これからはindex番号を、idみたいなものとして扱う。
for i, j in enumerate(D):
    print i, ":", j

#argmax([1, 2, 3], 2, 2)
#Dからコサイン類似度を最大化する組合せを取り出してみる。
print argmax(D, 2, simcos)

#次に、Dからユークリッド距離を最大化する組合せを取り出してみる。
print argmax(D, 2, euclidean_distance)

#この二つからコサイン類似度とユークリッド距離には負の相関があるように思われる。
#次回はこれをテストしてみる。


notes: in this code, the comments are written by Japanese.
the arguments of the functions that calculate the similarity is list, because of the versatility.

コメントを残す