Chulinz's picture
ICJ Citation Graph release with Parquet and Docker runtime
0a50834
Raw History Blame Contribute Delete
860 Bytes
import numpy as np
def validate_vectors(values, dimension=None, normalize=False):
try:
array = np.asarray(values, dtype=np.float32)
except (TypeError, ValueError) as exc:
raise ValueError('Embedding response is not a rectangular numeric matrix.') from exc
if array.ndim != 2 or array.shape[0] == 0 or array.shape[1] == 0:
raise ValueError('Embeddings must be a nonempty matrix.')
if dimension and array.shape[1] != dimension:
raise ValueError(f'Embedding dimension {array.shape[1]} does not match {dimension}.')
norms = np.linalg.norm(array, axis=1)
if not np.isfinite(array).all() or not np.isfinite(norms).all() or np.any(norms == 0):
raise ValueError('Embeddings contain non-finite values or zero vectors.')
if normalize:
array = array / norms[:, None]
return array.tolist()