Spaces:
Running
Running
Create relationships.py
Browse files- relationships.py +140 -0
relationships.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Full-dimensional analogy arithmetic and shared linear projections."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
import plotly.graph_objects as go
|
| 4 |
+
from plotly.colors import qualitative
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def cosine(a, b):
|
| 8 |
+
a, b = np.asarray(a, dtype=float), np.asarray(b, dtype=float)
|
| 9 |
+
denominator = np.linalg.norm(a) * np.linalg.norm(b)
|
| 10 |
+
return float(np.clip(np.dot(a, b) / denominator, -1, 1)) if denominator > 0 and np.isfinite(denominator) else None
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def analyse_pairs(pairs, target, expected=None):
|
| 14 |
+
"""Each pair is (A, B); apply their mean offset to C, optionally compare D."""
|
| 15 |
+
if not pairs:
|
| 16 |
+
raise ValueError('Add at least one example pair.')
|
| 17 |
+
arrays = [np.asarray(v, dtype=float) for pair in pairs for v in pair] + [np.asarray(target, dtype=float)]
|
| 18 |
+
if expected is not None:
|
| 19 |
+
arrays.append(np.asarray(expected, dtype=float))
|
| 20 |
+
if any(v.ndim != 1 or v.shape != arrays[0].shape or not np.isfinite(v).all() for v in arrays):
|
| 21 |
+
raise ValueError('All inputs must be finite vectors with matching dimensions.')
|
| 22 |
+
offsets = np.array([np.asarray(b, dtype=float) - np.asarray(a, dtype=float) for a, b in pairs])
|
| 23 |
+
offset = offsets.mean(axis=0)
|
| 24 |
+
prediction = np.asarray(target, dtype=float) + offset
|
| 25 |
+
agreement = [cosine(v, offset) for v in offsets]
|
| 26 |
+
result = {'offset': offset, 'prediction': prediction, 'offset_length': float(np.linalg.norm(offset)),
|
| 27 |
+
'example_agreement': float(np.mean([x for x in agreement if x is not None])) if any(x is not None for x in agreement) else None}
|
| 28 |
+
if expected is not None:
|
| 29 |
+
observed = np.asarray(expected, dtype=float) - np.asarray(target, dtype=float)
|
| 30 |
+
alignment = cosine(offset, observed)
|
| 31 |
+
result.update(direction_cosine=alignment,
|
| 32 |
+
angle_degrees=float(np.degrees(np.arccos(alignment))) if alignment is not None else None,
|
| 33 |
+
observed_length=float(np.linalg.norm(observed)),
|
| 34 |
+
length_ratio=float(np.linalg.norm(observed) / np.linalg.norm(offset)) if np.linalg.norm(offset) > 0 else None,
|
| 35 |
+
prediction_error=float(np.linalg.norm(prediction - expected)))
|
| 36 |
+
return result
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def fit_projection(points, dimensions):
|
| 40 |
+
points = np.asarray(points, dtype=float)
|
| 41 |
+
if points.ndim != 2 or not len(points) or not np.isfinite(points).all() or dimensions not in (2, 3):
|
| 42 |
+
raise ValueError('Projection needs finite points and two or three components.')
|
| 43 |
+
mean = points.mean(axis=0)
|
| 44 |
+
centered = points - mean
|
| 45 |
+
_, singular, vt = np.linalg.svd(centered, full_matrices=False)
|
| 46 |
+
basis = np.zeros((dimensions, points.shape[1]))
|
| 47 |
+
tolerance = max(centered.shape) * np.finfo(float).eps * (singular[0] if len(singular) else 0.)
|
| 48 |
+
rank = int(np.count_nonzero(singular > tolerance))
|
| 49 |
+
count = min(dimensions, rank)
|
| 50 |
+
basis[:count] = vt[:count]
|
| 51 |
+
total = float(np.dot(singular, singular))
|
| 52 |
+
retained = float(np.dot(singular[:count], singular[:count]) / total) if total > 0 else 1.
|
| 53 |
+
return mean, basis, retained
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def relationship_figure(analysis, dimensions, extra_vectors=None, extra_labels=None):
|
| 57 |
+
"""Fit one PCA to the example endpoints; project predictions/candidates with it."""
|
| 58 |
+
points, point_labels, point_codes, point_keys = [], [], [], []
|
| 59 |
+
for index, pair in enumerate(analysis['pairs'], 1):
|
| 60 |
+
for letter in ('a', 'b'):
|
| 61 |
+
points.append(pair[letter]['values'])
|
| 62 |
+
point_labels.append(pair[letter]['label'])
|
| 63 |
+
point_codes.append(letter.upper() + (str(index) if len(analysis['pairs']) > 1 else ''))
|
| 64 |
+
point_keys.append(pair[letter]['key'])
|
| 65 |
+
points.append(analysis['target']['values'])
|
| 66 |
+
point_labels.append(analysis['target']['label'])
|
| 67 |
+
point_codes.append('C')
|
| 68 |
+
point_keys.append(analysis['target']['key'])
|
| 69 |
+
if analysis['expected'] is not None:
|
| 70 |
+
points.append(analysis['expected']['values'])
|
| 71 |
+
point_labels.append(analysis['expected']['label'])
|
| 72 |
+
point_codes.append('D')
|
| 73 |
+
point_keys.append(analysis['expected']['key'])
|
| 74 |
+
mean, basis, retained = fit_projection(points, dimensions)
|
| 75 |
+
project = lambda values: (np.asarray(values) - mean) @ basis.T
|
| 76 |
+
coords = project(points)
|
| 77 |
+
predicted = project(analysis['metrics']['prediction'])
|
| 78 |
+
c_index = 2 * len(analysis['pairs'])
|
| 79 |
+
palette = qualitative.Plotly
|
| 80 |
+
fig = go.Figure()
|
| 81 |
+
scatter = go.Scatter if dimensions == 2 else go.Scatter3d
|
| 82 |
+
|
| 83 |
+
def add_points(coordinates, **kwargs):
|
| 84 |
+
axes = {'x': coordinates[:, 0], 'y': coordinates[:, 1]}
|
| 85 |
+
if dimensions == 3:
|
| 86 |
+
axes['z'] = coordinates[:, 2]
|
| 87 |
+
fig.add_trace(scatter(**axes, **kwargs))
|
| 88 |
+
|
| 89 |
+
extent = max(float(np.linalg.norm(np.ptp(np.vstack([coords, predicted]), axis=0))), .01)
|
| 90 |
+
|
| 91 |
+
def arrow(start, end, label, color, dash='solid', showlegend=True, group=None):
|
| 92 |
+
group = group or label
|
| 93 |
+
add_points(np.array([start, end]), mode='lines', name=label, showlegend=showlegend,
|
| 94 |
+
legendgroup=group,
|
| 95 |
+
line={'color': color, 'width': 4 if dimensions == 3 else 2, 'dash': dash},
|
| 96 |
+
hoverinfo='name')
|
| 97 |
+
if np.linalg.norm(end - start) < 1e-12:
|
| 98 |
+
return
|
| 99 |
+
if dimensions == 2:
|
| 100 |
+
fig.add_annotation(x=end[0], y=end[1], ax=start[0], ay=start[1], xref='x', yref='y',
|
| 101 |
+
axref='x', ayref='y', text='', showarrow=True, arrowhead=3,
|
| 102 |
+
arrowwidth=2, arrowcolor=color)
|
| 103 |
+
else:
|
| 104 |
+
delta = end - start
|
| 105 |
+
fig.add_trace(go.Cone(x=[end[0]], y=[end[1]], z=[end[2]], u=[delta[0]], v=[delta[1]], w=[delta[2]],
|
| 106 |
+
anchor='tip', sizemode='absolute', sizeref=extent * .045,
|
| 107 |
+
colorscale=[[0, color], [1, color]], showscale=False, hoverinfo='skip',
|
| 108 |
+
legendgroup=group, showlegend=False))
|
| 109 |
+
|
| 110 |
+
for i in range(len(analysis['pairs'])):
|
| 111 |
+
arrow(coords[i * 2], coords[i * 2 + 1], 'Example offset' if len(analysis['pairs']) == 1 else 'Example offsets',
|
| 112 |
+
palette[0], showlegend=i == 0, group='examples')
|
| 113 |
+
arrow(coords[c_index], predicted, 'C + mean(B − A)', palette[2], 'dash')
|
| 114 |
+
if analysis['expected'] is not None:
|
| 115 |
+
arrow(coords[c_index], coords[c_index + 1], 'C → D', palette[1])
|
| 116 |
+
arrow(predicted, coords[c_index + 1], 'Prediction error', palette[3], 'dot')
|
| 117 |
+
add_points(coords, mode='markers+text', text=point_codes, textposition='top center',
|
| 118 |
+
customdata=point_labels, name='Input vectors',
|
| 119 |
+
marker={'size': 7 if dimensions == 2 else 4, 'color': palette[0]},
|
| 120 |
+
hovertemplate='%{text}: %{customdata}<extra></extra>')
|
| 121 |
+
add_points(predicted[None, :], mode='markers+text', text=['Predicted'], textposition='bottom center',
|
| 122 |
+
name='Predicted D', marker={'size': 10 if dimensions == 2 else 6, 'symbol': 'diamond', 'color': palette[2]},
|
| 123 |
+
hovertemplate='Predicted D = C + mean(B − A)<extra></extra>')
|
| 124 |
+
extra = [key for key in (extra_vectors or {}) if key not in point_keys]
|
| 125 |
+
if extra:
|
| 126 |
+
extra_coords = project([extra_vectors[key] for key in extra])
|
| 127 |
+
add_points(extra_coords, mode='markers', customdata=[extra_labels[key] for key in extra],
|
| 128 |
+
name='Other chart vectors', marker={'size': 5 if dimensions == 2 else 3, 'color': palette[4]},
|
| 129 |
+
hovertemplate='%{customdata}<extra></extra>')
|
| 130 |
+
fig.update_layout(template='plotly_dark', autosize=True,
|
| 131 |
+
title={'text': f'PCA · {retained:.1%} of input variance retained', 'font': {'size': 13}, 'x': .01, 'y': .98, 'yanchor': 'top'},
|
| 132 |
+
margin={'l': 20, 'r': 20, 't': 72, 'b': 25},
|
| 133 |
+
legend={'orientation': 'h', 'y': 1.02, 'yanchor': 'bottom'},
|
| 134 |
+
uirevision=f'relationship:{analysis["id"]}:{dimensions}')
|
| 135 |
+
if dimensions == 2:
|
| 136 |
+
fig.update_xaxes(title='PC 1')
|
| 137 |
+
fig.update_yaxes(title='PC 2', scaleanchor='x', scaleratio=1)
|
| 138 |
+
else:
|
| 139 |
+
fig.update_layout(scene={'xaxis_title': 'PC 1', 'yaxis_title': 'PC 2', 'zaxis_title': 'PC 3', 'aspectmode': 'data'})
|
| 140 |
+
return fig
|