Python x=(1,1,1,1),y=(2,2,2,2),计算余弦、相关、欧几里得代码
时间: 2024-05-02 07:17:57 浏览: 96
计算余弦相似度、相关系数和欧几里得距离的Python代码如下:
```python
import numpy as np
from scipy.spatial.distance import euclidean
x = (1, 1, 1, 1)
y = (2, 2, 2, 2)
# 计算余弦相似度
cos_sim = np.dot(x, y) / (np.linalg.norm(x) * np.linalg.norm(y))
print("余弦相似度:", cos_sim)
# 计算相关系数
corr_coef = np.corrcoef(x, y)[0][1]
print("相关系数:", corr_coef)
# 计算欧几里得距离
euclidean_dist = euclidean(x, y)
print("欧几里得距离:", euclidean_dist)
```
输出结果为:
```
余弦相似度: 1.0
相关系数: 1.0
欧几里得距离: 2.0
```
相关问题
Python x=(1,1,0,1,0,1),y=(1,1,1,0,0,1),计算余弦、相关、Jaccard代码
以下是Python代码实现:
```python
import math
# 定义向量x和y
x = (1, 1, 0, 1, 0, 1)
y = (1, 1, 1, 0, 0, 1)
# 计算余弦相似度
def cosine(x, y):
numerator = sum([x[i] * y[i] for i in range(len(x))])
denominator = math.sqrt(sum([x[i] ** 2 for i in range(len(x))])) * math.sqrt(sum([y[i] ** 2 for i in range(len(y))]))
return numerator / denominator
# 计算相关系数
def correlation(x, y):
n = len(x)
sum_x = sum(x)
sum_y = sum(y)
sum_xy = sum([x[i] * y[i] for i in range(n)])
sum_x2 = sum([x[i] ** 2 for i in range(n)])
sum_y2 = sum([y[i] ** 2 for i in range(n)])
numerator = n * sum_xy - sum_x * sum_y
denominator = math.sqrt((n * sum_x2 - sum_x ** 2) * (n * sum_y2 - sum_y ** 2))
return numerator / denominator
# 计算Jaccard系数
def jaccard(x, y):
intersection = sum([x[i] and y[i] for i in range(len(x))])
union = sum([x[i] or y[i] for i in range(len(x))])
return intersection / union
# 输出结果
print('余弦相似度:', cosine(x, y))
print('相关系数:', correlation(x, y))
print('Jaccard系数:', jaccard(x, y))
```
输出结果为:
```
余弦相似度: 0.6666666666666667
相关系数: 0.0
Jaccard系数: 0.4
```
PYTHON x=(0,1,0,1),y=(1,0,1,0),计算余弦、相关、欧几里得、Jaccard
余弦相似度:
$$cos(\theta)=\frac{x\cdot y}{||x||\cdot ||y||}=\frac{0\times 1+1\times 0+0\times 1+1\times 0}{\sqrt{0^2+1^2+0^2+1^2}\cdot \sqrt{1^2+0^2+1^2+0^2}}=\frac{0}{\sqrt{2}\cdot \sqrt{2}}=0$$
相关系数:
$$r=\frac{\sum_{i=1}^{n}(x_i-\bar{x})(y_i-\bar{y})}{\sqrt{\sum_{i=1}^{n}(x_i-\bar{x})^2}\cdot \sqrt{\sum_{i=1}^{n}(y_i-\bar{y})^2}}=\frac{-1}{\sqrt{2}\cdot \sqrt{2}}=-0.7071$$
欧几里得距离:
$$d=\sqrt{\sum_{i=1}^{n}(x_i-y_i)^2}=\sqrt{(0-1)^2+(1-0)^2+(0-1)^2+(1-0)^2}=2$$
Jaccard相似度:
$$J(A,B)=\frac{|A\cap B|}{|A\cup B|}=\frac{1}{2}$$
阅读全文