Вы аналитик приложения по распознаванию цветков по фотографии. Вам нужно посчитать качество
классификатора. В классификатор подаются уже обрезанные фотографии, где всегда ожидается 1 вид
цветка. Но обрезка может ошибаться и подать на вход не фотографию цветка.
Вам нужно посчитать долю верно распознанных цветков среди всех входящих фотографий, на которых
действительно были цветки, с учётом пропорций видов цветков у пользователей.
У вас есть 2 файла:
Число каждого вида цветков, как их распознал алгоритм. Получается автоматически из логов
приложения за последний месяц. detection_count.csv со столбцами detected_name - название цветка по
результатам распознавания, count — число цветков такого вида.
Результаты ручной разметки на выборке (из другого периода). Здесь каждая строка - это результат
проверки распознавания экспертом, который проставляет правильный вид цветка. detection_quality.csv
со столбцами detected_name - название цветка по результатам распознавания, human_name —
название цветка согласно ручной проверки (считаем ответ эталоном).
Кроме названия цветка, в detected _name и human_name может присутствовать запись not_a_flower, что
означает, что алгоритм или человек решили, что на изображении не цветок.
Вам нужно перевзвесить результаты замеров качества из detection_quality.csv с учётом реального
распределения классов цветков из detection_count.csv.
При этом по некоторым цветкам у нас очень мало замеров или они вообще отсутствуют. Здесь нужно будет
делать какие-то допущения. Вам нужно будет произвести расчёты по алгоритму ниже.
Разделим цветки на 3 класса:
• not_a_flower - их обрабатываем отдельно;
• популярные - по которым у нас есть 10 или более замеров, где классификатор совпал с вердиктом
человека;
• остальные — где у нас нет 10 замеров, где классификатор совпал с вердиктом человека. Группируем
по распознанному виду цветка.
Для каждой группы считаем среднюю вероятность того, что в реальности на входе был подан не
цветок, но классификатор отнёс его к данной группе.
Далее считаем среднюю вероятность правильной классификации, при этом для цветков из
популярной группы считаем эту вероятность индивидуально для каждого. А для остальных и
not_a_flower считаем вероятность усреднённо по всем внутри группы.
Взвешиваем месячную статистику классифицированных цветков: учитываем вероятность того, что на
входе был не цветок (это должно снижать вес группы), и учитываем качество. Получаем среднее
качество для пользователя.
По результатам прошлого месяца (файл detection_count_previous.csv качество получилось 0.8613
(используйте для отладки кода).
Какое взвешенное качество будет в этом месяце (detection_quality.csv тот же, но другое распределение
частоты распознанных цветков в detection_count.csv)?
Напишите программу, которая читает detection_quality.csv и detection_count.csv и печатает число с
точностью до 4-х знаков после запятой и более ничего не выводит.
Формат ввода
month_detected.csv c полями
• detected_name
• count
human_classification.csv c полями
• detected_name
• human_name
Формат вывода
Распечатайте метрику с точностью до 4-х знаков (округлённо до ближайшего). Например: 0.1234 (вместо
0. 1233987). Больше ничего распечатываться не должно.
Assistant
To solve this problem, we need to calculate the weighted quality of a flower classifier based on two datasets: detection_count.csv and detection_quality.csv. The goal is to determine the proportion of correctly classified flowers while considering the probability that the input might not be a flower at all.
Approach
Group Classification: Split the detected flowers into three groups based on historical data from detection_quality.csv:
not_a_flower: Entries where the detected name is 'not_a_flower'.
popular: Detected names with 10 or more correct classifications.
others: Detected names with fewer than 10 correct classifications.
Compute Group Metrics:
Probability of Non-Flower Input (P_not): For each group, calculate the probability that the input was not a flower but classified into that group.
Quality Metrics: For the popular group, compute individual quality metrics for each detected name. For not_a_flower and others, compute average quality metrics.
Weighted Quality Calculation:
Use the current month's data from detection_count.csv to compute the weighted quality by considering the group metrics and the count of each detected name.
Solution Code
import pandas as pd
# Read detection_quality.csv
df_quality = pd.read_csv('detection_quality.csv')
# Step 1: Determine group for each detected_name in detection_quality
detected_name_to_group = {}
# Process not_a_flower
not_a_flower_mask = df_quality['detected_name'] == 'not_a_flower'
not_a_flower_df = df_quality[not_a_flower_mask]
if not not_a_flower_df.empty:
detected_name_to_group['not_a_flower'] = 'not_a_flower'
# Process other detected_names
other_detected = df_quality[~not_a_flower_mask]['detected_name'].unique()
for name in other_detected:
entries = df_quality[df_quality['detected_name'] == name]
correct = len(entries[entries['detected_name'] == entries['human_name']])
if correct >= 10:
detected_name_to_group[name] = 'popular'
else:
detected_name_to_group[name] = 'others'
# Step 2: Compute group metrics (P_not and quality)
group_metrics = {}
# Group 'not_a_flower'
entries_not = df_quality[df_quality['detected_name'] == 'not_a_flower']
count_not_not = len(entries_not[entries_not['human_name'] == 'not_a_flower'])
total_not = len(entries_not)
P_not_not = count_not_not / total_not if total_not > 0 else 0.0
correct_not = len(entries_not[entries_not['detected_name'] == entries_not['human_name']])
quality_not = correct_not / total_not if total_not > 0 else 0.0
group_metrics['not_a_flower'] = {'P_not': P_not_not, 'quality': quality_not}
# Group 'popular'
popular_names = [name for name, grp in detected_name_to_group.items() if grp == 'popular']
entries_popular = df_quality[df_quality['detected_name'].isin(popular_names)]
count_not_popular = len(entries_popular[entries_popular['human_name'] == 'not_a_flower'])
total_popular = len(entries_popular)
P_not_popular = count_not_popular / total_popular if total_popular > 0 else 0.0
group_metrics['popular'] = {'P_not': P_not_popular}
# Compute individual quality for popular names
popular_quality = {}
for name in popular_names:
entries = df_quality[df_quality['detected_name'] == name]
correct = len(entries[entries['detected_name'] == entries['human_name']])
total = len(entries)
quality = correct / total if total > 0 else 0.0
popular_quality[name] = quality
group_metrics['popular']['quality'] = popular_quality
# Group 'others'
others_names = [name for name, grp in detected_name_to_group.items() if grp == 'others']
entries_others = df_quality[df_quality['detected_name'].isin(others_names)]
count_not_others = len(entries_others[entries_others['human_name'] == 'not_a_flower'])
total_others = len(entries_others)
P_not_others = count_not_others / total_others if total_others > 0 else 0.0
correct_others = len(entries_others[entries_others['detected_name'] == entries_others['human_name']])
quality_others = correct_others / total_others if total_others > 0 else 0.0
group_metrics['others'] = {'P_not': P_not_others, 'quality': quality_others}
# Read detection_count.csv
df_count = pd.read_csv('detection_count.csv')
total_count = df_count['count'].sum()
sum_contribution = 0.0
for index, row in df_count.iterrows():
detected_name = row['detected_name']
count = row['count']
# Determine group
if detected_name == 'not_a_flower':
group = 'not_a_flower'
else:
if detected_name in detected_name_to_group:
group = detected_name_to_group[detected_name]
else:
group = 'others'
# Get P_not
if group == 'not_a_flower':
P_not = group_metrics['not_a_flower']['P_not']
elif group == 'popular':
P_not = group_metrics['popular']['P_not']
else: # others
P_not = group_metrics['others']['P_not']
# Get quality
if group == 'popular':
quality = group_metrics['popular']['quality'].get(detected_name, 0.0)
elif group == 'not_a_flower':
quality = group_metrics['not_a_flower']['quality']
else: # others
quality = group_metrics['others']['quality']
# Compute contribution
contribution = (1 - P_not) * quality * count
sum_contribution += contribution
weighted_quality = sum_contribution / total_count if total_count != 0 else 0.0
# Print with 4 decimal places
print("{0:.4f}".format(weighted_quality))
Explanation
Group Classification: The code first categorizes each detected name into one of three groups based on historical data.
Group Metrics Calculation: For each group, it calculates the probability that the input was not a flower and the average quality of classifications.
Weighted Quality Calculation: Using the current month's data, the code computes the weighted quality by considering the group metrics and the count of each detected name, ensuring the result is formatted to four decimal places.