File size: 6,392 Bytes
655a244
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
"""Render the report's PNGs from the released metrics and inference example."""

import json
from pathlib import Path

import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter
import numpy as np
from PIL import Image

REPORTS = Path(__file__).resolve().parent
EXAMPLES = REPORTS.parent / "examples"
OUTPUT = REPORTS / "figures"
MODES = ("global", "unary", "pair", "factorized")
LABELS = ("Global", "Unary", "Learned pair", "Factorized pair")
COLORS = ("#7b899d", "#597791", "#7355b5", "#008272")
BACKGROUND = "#f7f9fc"
INK = "#122235"
MUTED = "#4c6177"

plt.rcParams.update({
    "font.family": "DejaVu Sans",
    "font.size": 11,
    "text.color": INK,
    "axes.labelcolor": MUTED,
    "xtick.color": MUTED,
    "ytick.color": INK,
    "figure.facecolor": BACKGROUND,
    "axes.facecolor": BACKGROUND,
    "axes.titleweight": "bold",
})


def read_json(path):
    return json.loads(path.read_text())


def header(fig, title, subtitle):
    fig.text(0.045, 0.91, title, fontsize=21, weight="bold")
    fig.text(0.045, 0.839, subtitle, fontsize=11, color=MUTED)


def save(fig, name):
    OUTPUT.mkdir(exist_ok=True)
    fig.savefig(OUTPUT / name, dpi=150)
    plt.close(fig)


def accuracy_grid(ax, axis):
    for spine in ax.spines.values():
        spine.set_visible(False)
    ax.tick_params(axis="both", length=0)
    ax.set_axisbelow(True)
    ax.grid(axis=axis, color="#dce5ee", linewidth=0.8)


def plot_results():
    fig, axes = plt.subplots(1, 2, figsize=(11.8, 4.25), sharey=True)
    fig.subplots_adjust(left=0.17, right=0.975, top=0.71, bottom=0.2, wspace=0.18)
    header(fig, "Caption ranking under a color–shape shift",
           "Joint accuracy requires the correct caption to outrank both alternatives.")
    for ax, source, title in zip(
        axes, ("valA.json", "valB-offset1000.json"), ("Condition A", "Disjoint condition B")
    ):
        metrics = read_json(REPORTS / source)["metrics"]
        y = np.arange(len(MODES))
        values = np.array([metrics[mode]["joint"] * 100 for mode in MODES])
        intervals = np.array([metrics[mode]["joint_ci"]["ci95"] for mode in MODES]).T * 100
        ax.barh(y, values, color=COLORS, height=0.53)
        ax.errorbar(values, y, xerr=[values - intervals[0], intervals[1] - values],
                    fmt="none", ecolor=INK, capsize=3, linewidth=1.15)
        for row, (value, upper) in enumerate(zip(values, intervals[1])):
            ax.text(upper + 2.3, row, f"{value:.1f}%", va="center", fontsize=10, weight="bold")
        ax.set_title(title, loc="left", pad=10, fontsize=13)
        ax.set_yticks(y, LABELS)
        ax.set_xlim(0, 110)
        ax.set_xticks([0, 25, 50, 75, 100])
        ax.xaxis.set_major_formatter(PercentFormatter())
        accuracy_grid(ax, "x")
    axes[0].invert_yaxis()
    fig.text(0.045, 0.055, "Whiskers show 95% intervals from resampling images.", color=MUTED, fontsize=10)
    save(fig, "joint-accuracy.png")


def plot_training():
    fig, ax = plt.subplots(figsize=(11.8, 4.35))
    fig.subplots_adjust(left=0.1, right=0.966, top=0.71, bottom=0.19)
    header(fig, "Validation across 12 epochs", "Open markers identify the selected condition A checkpoints.")
    for mode, label, color in zip(MODES, LABELS, COLORS):
        history = read_json(REPORTS / mode / "history.json")
        selected_epoch = read_json(REPORTS / mode / "results.json")["selected_epoch"]
        epochs = [row["epoch"] for row in history]
        scores = [100 * row["valA"]["joint"] for row in history]
        ax.plot(epochs, scores, color=color, label=label, linewidth=2.25)
        ax.plot(selected_epoch, scores[epochs.index(selected_epoch)], "o", color=color,
                markerfacecolor=BACKGROUND, markeredgewidth=2, markersize=7)
    ax.legend(loc="upper left", bbox_to_anchor=(-0.005, 1.165), ncol=4, frameon=False,
              borderaxespad=0, fontsize=10)
    ax.set_xticks(range(1, 13))
    ax.set_xlabel("Training epoch")
    ax.set_ylim(25, 100)
    ax.set_yticks([25, 50, 75, 100])
    ax.yaxis.set_major_formatter(PercentFormatter())
    accuracy_grid(ax, "y")
    save(fig, "training-curves.png")


def plot_example():
    sample = read_json(EXAMPLES / "captions.json")
    positive, swap, flip = sample["captions"]
    factorized = read_json(EXAMPLES / "factorized-ranking.json")
    learned = read_json(EXAMPLES / "learned-pair-ranking.json")
    best = {row["caption"]: row for row in factorized}[positive]
    image = Image.open(EXAMPLES / "cogent-valB.png")
    fig, (scene, ranking) = plt.subplots(1, 2, figsize=(11.8, 4.6), gridspec_kw={"width_ratios": (1.05, 1.45)})
    fig.subplots_adjust(left=0.045, right=0.955, top=0.76, bottom=0.1, wspace=0.12)
    header(fig, "One image, three competing captions", "CLEVR condition B · " + sample["source_image"])
    scene.imshow(image, extent=(0, 1, 1, 0))
    scene.set_aspect(image.height / image.width)
    scene.set_axis_off()
    for (x, y), label in zip(best["phrase_centers_xy"], ("1", "2")):
        scene.text(x, y, label, ha="center", va="center", color="white", fontsize=10,
                   weight="bold", bbox={"boxstyle": "circle,pad=0.35", "fc": COLORS[3], "ec": "white", "lw": 1.5})
    scene.set_title("Predicted phrase centers", loc="left", fontsize=12, pad=8)
    ranking.set_axis_off()
    for x, label in zip((0.67, 0.89), ("Learned pair", "Factorized pair")):
        ranking.text(x, 0.90, label, ha="center", fontsize=9, weight="bold")
    for index, (caption, label) in enumerate(zip((positive, swap, flip), ("Correct", "Color swap", "Spatial flip"))):
        y = 0.75 - index * 0.23
        ranking.axhline(y + 0.095, color="#dce5ee", lw=0.8)
        ranking.text(0.0, y, label, weight="bold", color=COLORS[3] if index == 0 else INK)
        ranking.text(0.0, y - 0.075, caption, color=MUTED, fontsize=9)
        for x, rows in zip((0.67, 0.89), (learned, factorized)):
            rank = next(i for i, row in enumerate(rows, 1) if row["caption"] == caption)
            ranking.text(x, y - 0.02, f"#{rank}", ha="center", weight="bold",
                         color=COLORS[3] if index == 0 and rank == 1 else INK)
    fig.text(0.045, 0.044, "1  Brown cylinder     2  Purple cube", color=MUTED, fontsize=10)
    save(fig, "caption-example.png")


if __name__ == "__main__":
    plot_results()
    plot_training()
    plot_example()