我正在尝试创建一个混淆矩阵,其中
我希望我的最高腹肌数能够正常化。这意味着,最高的绝对数决定纯绿色/红色。
import plotly.graph_objects as go
import numpy as np
cf_matrix = np.array([[395, -5], [-100, 20]])
group_names = ["TP", "FP", "FN", "TN"]
group_values = [395, -5, -100, 20]
labels = [f"{v1}\n{v2}" for v1, v2 in zip(group_names, group_values)]
labels = np.asarray(labels).reshape(2, 2)
# Define the colors for 0, positive, and negative values
zero_color = 'white'
positive_color = 'green'
negative_color = 'red'
# Create a custom color scale
colors = [
(0, negative_color),
(0.5 / np.max(abs(custom_cf_matrix)), zero_color), # Normalize the midpoint value to 0.5
(1, positive_color)
]
# Create the figure
fig = px.imshow(
custom_cf_matrix,
labels={"x": "Predicted Label", "y": "True Label"},
color_continuous_scale=colors,
range_color=[np.max(abs(custom_cf_matrix)), np.max(abs(custom_cf_matrix))],
width=500,
height=500,
)
fig.update_xaxes(side="bottom")
fig.update_yaxes(side="left")
# Update the annotations to use black font color
annotations = [
dict(
text=text,
x=col,
y=row,
font=dict(color="black", size=16), # Set font color to black
showarrow=False,
xanchor="center",
yanchor="middle",
)
for row in range(2)
for col, text in zip(range(2), labels[row])
]
fig.update_layout(
title="Value-Weighted Confusion Matrix",
title_x=0.25, # Center the title horizontally
annotations=annotations,
)
fig.update_xaxes(tickvals=[0, 1], ticktext=["0", "1"], showticklabels=True)
fig.update_yaxes(tickvals=[0, 1], ticktext=["0", "1"], showticklabels=True)
# Display the plot
st.plotly_chart(fig)
fig.show()