## 유클리드 유사도 vs 코사인 유사도
- 유클리드 유사도 구하는 함수 구현하기
- 코사인 유사도 구하는 함수 구현하기
- 코드설명
- 두 결과 비교
- 응용분야 예시

#### Similarity 
```The similairt measure is the measure of how much alike 
two data objects are. 

Similarity measure in a data mining context is a distance with 
dimensions representing features of the objects.

If this distance is small, it will be the high degree of similarity where large distance will be the low degree of similarity.```

##### 1.  Euclidean distance 
- literally distance b/w two vectors 


```python
import sympy
sympy.init_printing(use_latex='mathjax')
```


```python
from math import*

def e_d(x,y) : 
    "e_d stands for Euclidean distance"
    c = [(a-b)**2 for a,b in zip(x,y)]
    return sqrt(sum(c))

print(e_d([1,2], [4,1]))
```

    3.1622776601683795



```python
a = np.array([1,2])
b = np.array([4,1])
c = a-b

plt.plot(a[0],a[1], 'ro')
plt.plot(b[0],b[1], 'ro')

plt.text(0.6, 1.6 , "$a$", fontdict={"size" : 18})
plt.text(3.6, 0.6 , "$b$", fontdict={"size" : 18})

plt.annotate('', xy=a, xytext=(0,0), arrowprops=dict(facecolor='gray', ls="dashed"))
plt.annotate('', xy=b, xytext=(0,0), arrowprops=dict(facecolor='gray', ls="dashed"))
plt.arrow(4,1,-3,1, width=0.008)

plt.xticks(range(6))
plt.yticks(range(6))
plt.show()
```


```python
e_d([1,2], [4,1]), sqrt(10)
```




$$\left ( 3.1622776601683795, \quad 3.1622776601683795\right )$$



##### 2. Cosine similarity 
- Cosine similarty metric finds the nomalized dot product of two attributes. 


```python
def norm(x) : 
    return sqrt(sum([ a**2 for a in x]))

def dot_product(x,y):
    return sum(a*b for a,b in zip(x,y))

def c_s(x,y):
    """c_s stands for consine similarity"""
    denominator = norm(x)*norm(y)
    numerator = dot_product(x,y)
    return numerator / denominator

def c_d(*arg):
    "c_d stands for consine distance"
    return 1 - c_s(x,y)

print(c_s([1,2],[4,1]))    
print(c_d([1,2],[4,1]))
```

    0.6507913734559685
    0.3492086265440315



```python

```

#### Example


```python
index = ["D1","D2","D3","D4"]
columns = ["team","coach","hockey","baseball","soccer","penalty","score","win","loss","season"]
datas = {
    "team" : [5,3,0,0],
    "coach" : [0,0,7,1],
    "hockey" : [3,2,0,0],
    "baseball" : [0,0,2,0],
    "soccer" : [2,1,1,1],
    "penalty" : [0,1,0,2],
    "score" : [0,0,0,2],
    "win" : [2,1,3,0],
    "loss" : [0,0,0,3],
    "season" : [0,1,0,0] 
}
```


```python
df = pd.DataFrame(index=index, columns=columns, data=datas)
df 
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>team</th>
      <th>coach</th>
      <th>hockey</th>
      <th>baseball</th>
      <th>soccer</th>
      <th>penalty</th>
      <th>score</th>
      <th>win</th>
      <th>loss</th>
      <th>season</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>D1</th>
      <td>5</td>
      <td>0</td>
      <td>3</td>
      <td>0</td>
      <td>2</td>
      <td>0</td>
      <td>0</td>
      <td>2</td>
      <td>0</td>
      <td>0</td>
    </tr>
    <tr>
      <th>D2</th>
      <td>3</td>
      <td>0</td>
      <td>2</td>
      <td>0</td>
      <td>1</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>1</td>
    </tr>
    <tr>
      <th>D3</th>
      <td>0</td>
      <td>7</td>
      <td>0</td>
      <td>2</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>3</td>
      <td>0</td>
      <td>0</td>
    </tr>
    <tr>
      <th>D4</th>
      <td>0</td>
      <td>1</td>
      <td>0</td>
      <td>0</td>
      <td>1</td>
      <td>2</td>
      <td>2</td>
      <td>0</td>
      <td>3</td>
      <td>0</td>
    </tr>
  </tbody>
</table>
</div>




```python
#cosine similarity 
```


```python
def norm(x) : 
    return sqrt(sum([ a**2 for a in x]))

def dot_product(x,y):
    return sum(a*b for a,b in zip(x,y))

def c_s(x,y):
    """c_s stands for consine similarity"""
    denominator = norm(x)*norm(y)
    numerator = dot_product(x,y)
    return numerator / denominator

def c_d(*arg):
    "c_d stands for consine distance"
    return 1 - c_s(x,y)

print(c_s([1,2],[4,1]))    
print(c_d([1,2],[4,1]))
```

    0.6507913734559685
    0.3492086265440315



```python
C_D1_D2 = c_s(df.loc["D1"],df.loc["D2"])
C_D1_D2
```




$$0.9356014857063997$$




```python
C_D1_D3 = c_s(df.loc["D1"],df.loc["D3"])
C_D1_D3
```




$$0.1555231582719478$$




```python
C_D1_D4 = c_s(df.loc["D1"],df.loc["D4"])
C_D1_D4
```




$$0.07079923254047886$$




```python
C_D2_D3 = c_s(df.loc["D2"],df.loc["D3"])
C_D2_D3
```




$$0.12222646627042817$$




```python
C_D2_D4 = c_s(df.loc["D2"],df.loc["D4"])
C_D2_D4
```




$$0.16692446522239712$$




```python
C_D3_D4 = c_s(df.loc["D3"],df.loc["D4"])
C_D3_D4
```




$$0.23122932520643197$$




```python
#Euclidean similarty
```


```python
from math import*

def e_d(x,y) : 
    "e_d stands for Euclidean distance"
    c = [(a-b)**2 for a,b in zip(x,y)]
    return sqrt(sum(c))

print(e_d([1,2], [4,1]))
```

    3.1622776601683795



```python
E_D1_D2 = e_d(df.loc["D1"],df.loc["D2"])
E_D1_D2
```




$$3.0$$




```python
E_D1_D3 = e_d(df.loc["D1"],df.loc["D3"]) 
E_D1_D3
```




$$9.433981132056603$$




```python
E_D1_D4 = e_d(df.loc["D1"],df.loc["D4"])
E_D1_D4
E_D1_D4
```




$$7.54983443527075$$




```python
E_D2_D3 = e_d(df.loc["D2"],df.loc["D3"])
E_D2_D3
```




$$8.48528137423857$$




```python
E_D2_D4 = e_d(df.loc["D2"],df.loc["D4"])
E_D2_D4
```




$$5.477225575051661$$




```python
E_D3_D4 = e_d(df.loc["D3"],df.loc["D4"])
E_D3_D4
```




$$8.12403840463596$$




```python
data1 = {"D1_D2" : [C_D1_D2, E_D1_D2] ,
         "D1_D3" : [C_D1_D3, E_D1_D3],
         "D1_D4" : [C_D1_D4, E_D1_D4],
         "D2_D3" : [C_D2_D3, E_D2_D3],
         "D2_D4" : [C_D2_D4, E_D2_D4],
         "D3_D4" : [C_D3_D4, E_D3_D4] }
```


```python
df2 = pd.DataFrame(columns=["D1_D2","D1_D3","D1_D4","D2_D3","D2_D4","D3_D4"], index=["Cosine_similarity","Euclidean_similarty"], data=data1)
df2
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>D1_D2</th>
      <th>D1_D3</th>
      <th>D1_D4</th>
      <th>D2_D3</th>
      <th>D2_D4</th>
      <th>D3_D4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Cosine_similarity</th>
      <td>0.935601</td>
      <td>0.155523</td>
      <td>0.070799</td>
      <td>0.122226</td>
      <td>0.166924</td>
      <td>0.231229</td>
    </tr>
    <tr>
      <th>Euclidean_similarty</th>
      <td>3.000000</td>
      <td>9.433981</td>
      <td>7.549834</td>
      <td>8.485281</td>
      <td>5.477226</td>
      <td>8.124038</td>
    </tr>
  </tbody>
</table>
</div>




```python

```


```python

```


```python
data1 = {"D1_D2" : [C_D1_D2, E_D1_D2**2] ,
         "D1_D3" : [C_D1_D3, E_D1_D3**2],
         "D1_D4" : [C_D1_D4, E_D1_D4**2],
         "D2_D3" : [C_D2_D3, E_D2_D3**2],
         "D2_D4" : [C_D2_D4, E_D2_D4**2],
         "D3_D4" : [C_D3_D4, E_D3_D4**2] }
```


```python
df2 = pd.DataFrame(columns=["D1_D2","D1_D3","D1_D4","D2_D3","D2_D4","D3_D4"], index=["Cosine_similarity","Euclidean_similarty"], data=data1)
df2
```




<div>
<style scoped>
    .dataframe tbody tr th:only-of-type {
        vertical-align: middle;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }

    .dataframe thead th {
        text-align: right;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>D1_D2</th>
      <th>D1_D3</th>
      <th>D1_D4</th>
      <th>D2_D3</th>
      <th>D2_D4</th>
      <th>D3_D4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Cosine_similarity</th>
      <td>0.935601</td>
      <td>0.155523</td>
      <td>0.070799</td>
      <td>0.122226</td>
      <td>0.166924</td>
      <td>0.231229</td>
    </tr>
    <tr>
      <th>Euclidean_similarty</th>
      <td>9.000000</td>
      <td>89.000000</td>
      <td>57.000000</td>
      <td>72.000000</td>
      <td>30.000000</td>
      <td>66.000000</td>
    </tr>
  </tbody>
</table>
</div>




```python

```


```python

```


```python

```


```python
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import euclidean_distances
```


```python
corpus =[
    "All my cats in a row",
    "When my cat sits down, she looks like a Furby toy!",
    "The cat from outer space",
    "Sunshine loves to sit like this for some reason."
]
```


```python
vectorizer = CountVectorizer()
features = vectorizer.fit_transform(corpus).todense()
print(vectorizer.vocabulary_ )
```

    {'all': 0, 'my': 11, 'cats': 2, 'in': 7, 'row': 14, 'when': 25, 'cat': 1, 'sits': 17, 'down': 3, 'she': 15, 'looks': 9, 'like': 8, 'furby': 6, 'toy': 24, 'the': 21, 'from': 5, 'outer': 12, 'space': 19, 'sunshine': 20, 'loves': 10, 'to': 23, 'sit': 16, 'this': 22, 'for': 4, 'some': 18, 'reason': 13}



```python
for i in features:
    print(i)
```

    [[1 0 1 0 0 0 0 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0]]
    [[0 1 0 1 0 0 1 0 1 1 0 1 0 0 0 1 0 1 0 0 0 0 0 0 1 1]]
    [[0 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 1 0 0 0 0]]
    [[0 0 0 0 1 0 0 0 1 0 1 0 0 1 0 0 1 0 1 0 1 0 1 1 0 0]]



```python
for i in features : 
    print(euclidean_distances(features[0], i))
```

    [[0.]]
    [[3.60555128]]
    [[3.16227766]]
    [[3.74165739]]



```python
for i in features:
    print(cosine_similarity(features[0], i))
```

df647fd8a7e8e13ed94480c57a98fba34ff8b6d1
ipynb
Jupyter Notebook
01_linearalgebra/01_Euclidean Distance & Cosine distance.ipynb
seokyeongheo/study-math-with-python
18266dc137e46ea299cbd89241e474d7fd610122
MIT
01_linearalgebra/01_Euclidean Distance & Cosine distance.ipynb
seokyeongheo/study-math-with-python
18266dc137e46ea299cbd89241e474d7fd610122
MIT
01_linearalgebra/01_Euclidean Distance & Cosine distance.ipynb
seokyeongheo/study-math-with-python
18266dc137e46ea299cbd89241e474d7fd610122
MIT
2018-06-07T05:57:02.000Z
2018-06-07T05:57:02.000Z
Qwen/Qwen-72B
1. YES
2. YES