我有一个数据框,如下所示:
vector_a vector_b
[1,2,3] [2,5,6]
[0,2,1] [2,9,1]
[4,7,1] [1,7,4]
我想在vector_a和vector_b列之间进行sklearn的cosine_similarity
,以在同一数据帧中获得一个名为“ cosine_distance”的新列。请注意,vector_a和vector_b是df
的熊猫list
列。
这是我尝试过的:
df['vector_a'] = df['vector_a'].apply(lambda x: np.asarray(x))
df['vector_b'] = df['vector_b'].apply(lambda x: np.asarray(x))
df['cosine_distance'] = cosine_similarity(df['vector_a'].apply(lambda x: np.transpose(x)),
df['vector_b'].apply(lambda x: np.transpose(x)))
我得到了这个错误:
---> 58 df['cosine_distance'] = cosine_similarity(df['vector_a'].apply(lambda x: np.transpose(x)), df['vector_b'].apply(lambda x: np.transpose(x)))
~\Anaconda3\lib\site-packages\sklearn\metrics\pairwise.py in cosine_similarity(X, Y, dense_output)
1025 # to avoid recursive import
1026
-> 1027 X, Y = check_pairwise_arrays(X, Y)
1028
1029 X_normalized = normalize(X, copy=True)
~\Anaconda3\lib\site-packages\sklearn\metrics\pairwise.py in check_pairwise_arrays(X, Y, precomputed, dtype)
110 else:
111 X = check_array(X, accept_sparse='csr', dtype=dtype,
--> 112 estimator=estimator)
113 Y = check_array(Y, accept_sparse='csr', dtype=dtype,
114 estimator=estimator)
~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_all_finite, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, warn_on_dtype, estimator)
494 try:
495 warnings.simplefilter('error', ComplexWarning)
--> 496 array = np.asarray(array, dtype=dtype, order=order)
497 except ComplexWarning:
498 raise ValueError("Complex data not supported\n"
~\Anaconda3\lib\site-packages\numpy\core\numeric.py in asarray(a, dtype, order)
536
537 """
--> 538 return array(a, dtype, copy=False, order=order)
539
540
ValueError: setting an array element with a sequence.
提前谢谢!
答案 0 :(得分:2)
TLDR:
df['cosine_similarity'] = df.apply(
lambda row: cosine_similarity([row['vector_a']], [row['vector_b']])[0][0],
axis=1)
说明:
cosine_similarity
需要二维np.array或列表列表。它不知道如何解释pd。一系列列表。但是,即使我们确实将其转换为列表列表,也会出现下一个问题:cosine_similarity
返回所有与所有相似度。因此,让我们限于成对比较,人为地创建第二维(请注意[row['vector_a']], [row['vector_b']]
中的额外方括号),然后获取1x1数组的唯一元素(cosine_similarity(...)[0][0]
末尾为零)