Функция для поиска косинусного сходства между строками, используя только ненулевые общие столбцы - PullRequest
0 голосов
/ 20 февраля 2019

Я хочу написать функцию, чтобы найти косинусное сходство между строкой индекса (запросом) и каждой другой строкой в ​​кадре данных, используя только общие столбцы.Проблема, с которой я сталкиваюсь, заключается в том, что общие столбцы, не равные NULL, могут различаться в разных строкахЯ попытался заменить значения на 0, как советовалось, когда я задавал подобный вопрос раньше, но это не вывод или метод, который я ищу, поэтому я пытаюсь быть более конкретным здесь.Например, мой запрос выглядит так:

     A    B   C   D    E   F
1    3   Nan  2   1   Nan  4

, и он содержится во фрейме данных Similar_rows:

     A    B   C   D    E   F
0    2    3  Nan  3    1  Nan
1    3   Nan  2   1   Nan  4
2    Nan  4   1   3   Nan  5

Поэтому между запросом должно быть найдено косинусное сходство (которое в этомcase - это индекс 1) и оба 0 и 2 по отдельности, используя только их ненулевые общие столбцы.Таким образом, сходство косинусов между 0 и 1 должно быть найдено с использованием только столбцов A и D, так как они оба не равны NULL.

Моя функция до сих пор выглядит следующим образом:

def sims(index):
    #find_similar_times finds all times within a minutes threshold of the index row, not necessary to know that for this question but just giving some context
    similar_rows = find_similar_rows(index)
    #finding the columns of the query
    query_cols = similar_rows.loc[index]
    #getting them columns as a list after finding only non null columns of the query
    q_cols_names = query_cols[query_cols.notnull()]
    q_cols_names = list(q_cols_names.index)
    #putting the query into it's own dataframe
    qs = pd.DataFrame(query_cols[q_cols_names])
    qs = qs.T

    #this is where the error occurs. I am not sure why
    result = similar_rows[q_cols_names].apply(lambda row: cosine(row, qs))

    return result
    #the error says ('shapes (33,) and (24,) not aligned: 33 (dim 0) != 24 (dim 0)', (obviously my actual dataframe is different from above). I am not sure what this error is telling me

Это сложная проблема, которую нужно объяснить, поэтому извиняюсь заранее, если она не ясна.Любая помощь с благодарностью.

1 Ответ

0 голосов
/ 23 февраля 2019
def cosine_similarity(a, b):
    matrix = pd.DataFrame({"A": a, "B": b})
    matrix = matrix.dropna(axis = 0, how='any')
    a = matrix[['A']]
    b = matrix[['B']]
    return 1 - (cosine(a, b))

def sims(index):
    #find_similar_times finds all times within a minutes threshold of the index row, not necessary to know that for this question but just giving some context
    similar_rows = find_similar_rows(index)
    similar_rows = similar_rows.filter(like='to')
    #finding the columns of the query
    query_cols = list(similar_rows.loc[index])
    similar_rows = similar_rows.drop([index], axis = 0)
    #getting them columns as a list after finding only non null columns of the query
    result = similar_rows.apply(lambda row: cosine_similarity(list(row), query_cols), axis = 1)
    result = result.sort_values(ascending = False) #finding the most similar
    result = result.head(10)


    return result
...