Untitled

 avatar
unknown
plain_text
4 months ago
1.5 kB
3
Indexable
import numpy as np
from sklearn.metrics import precision_score, recall_score
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import HoverTool

# Assuming you have 'target' (true labels) and 'prob' (predicted probabilities)
# Example:
# target = [1, 0, 1, 0, 1]
# prob = [0.9, 0.1, 0.8, 0.2, 0.7]

# Define specific thresholds
thresholds = np.sort(np.random.uniform(0.1, 0.9, 20))  # 20 random thresholds between 0.1 and 0.9

# Compute precision and recall at each threshold
precision_values = []
recall_values = []

for t in thresholds:
    preds = (prob >= t).astype(int)  # Binarize predictions based on threshold
    precision_values.append(precision_score(target, preds))
    recall_values.append(recall_score(target, preds))

# Create a Bokeh plot
output_notebook()  # To display in Jupyter notebook

p = figure(title="Precision-Recall Curve (Custom Thresholds)",
           x_axis_label="Recall",
           y_axis_label="Precision",
           width=800, height=400)

# Add line for precision-recall curve
p.circle(recall_values, precision_values, size=10, legend_label="Custom Threshold Points",
         color="red", alpha=0.7)

# Add tooltips to show details on hover
hover = HoverTool(tooltips=[("Recall", "@x"), ("Precision", "@y")])
p.add_tools(hover)

# Add some styling
p.legend.location = "bottom_left"
p.legend.click_policy = "hide"
p.grid.grid_line_alpha = 0.3
p.title.text_font_size = "16px"

# Show the plot
show(p)
Editor is loading...
Leave a Comment