Here is an example of what the json looks like:
{
"a": 1,
"b": 0.8,
"c": 0.6666666666666666,
"d": 0,
"e": 1,
"f": 0.5714285714285714,
"g": 0,
"h": 0
}
<!DOCTYPE html>
<html>
<head>
<title>Text Embedding Regression</title>
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.14.0/dist/ort.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.21.0/dist/tf.min.js"></script>
</head>
<body>
<input type="file" id="jsonFile" accept=".json">
<textarea id="predictText" placeholder="Enter text to predict ranking"></textarea>
<button onclick="processData()">Process Data</button>
<button onclick="predictRanking()">Predict Ranking</button>
<div id="results"></div>
<div id="prediction"></div>
<script>
let session;
let tokenizerData;
let regressionModel;
let top5Indices;
// Load model and tokenizer data
async function loadModelAndTokenizer() {
session = await ort.InferenceSession.create(
'https://huggingface.co/RainbowPiBubbles/mini-gte-onnx/resolve/main/model.onnx'
);
const tokenizerResponse = await fetch(
'https://huggingface.co/RainbowPiBubbles/mini-gte-onnx/resolve/main/tokenizer.json'
);
tokenizerData = await tokenizerResponse.json();
}
// Simple tokenizer implementation
function tokenize(text) {
const tokens = text.toLowerCase().split(/\s+/);
const inputIds = tokens.map(token =>
tokenizerData.model.vocab[token] || tokenizerData.model.vocab['[UNK]']
);
return inputIds.slice(0, 128); // Truncate to max length
}
// Pad sequence
function padSequence(sequence, maxLength) {
const padded = new Array(maxLength).fill(0);
sequence.forEach((val, idx) => {
if (idx < maxLength) padded[idx] = val;
});
return padded;
}
// Get embeddings
async function getEmbedding(text) {
const inputIds = tokenize(text);
const maxLength = 128;
const paddedInput = padSequence(inputIds, maxLength);
const attentionMask = paddedInput.map(id => id > 0 ? 1 : 0);
const feeds = {
input_ids: new ort.Tensor('int64', BigInt64Array.from(paddedInput.map(BigInt)), [1, maxLength]),
attention_mask: new ort.Tensor('int64', BigInt64Array.from(attentionMask.map(BigInt)), [1, maxLength])
};
const results = await session.run(feeds);
return Array.from(results.last_hidden_state.data);
}
// Calculate correlation (R-squared)
function calculateRSquared(x, y) {
const xMean = x.reduce((a, b) => a + b) / x.length;
const yMean = y.reduce((a, b) => a + b) / y.length;
let numerator = 0, denomX = 0, denomY = 0;
for (let i = 0; i < x.length; i++) {
numerator += (x[i] - xMean) * (y[i] - yMean);
denomX += (x[i] - xMean) ** 2;
denomY += (y[i] - yMean) ** 2;
}
const r = numerator / Math.sqrt(denomX * denomY);
return r ** 2;
}
// Process uploaded JSON and train model
async function processData() {
await loadModelAndTokenizer();
const file = document.getElementById('jsonFile').files[0];
const reader = new FileReader();
reader.onload = async function(e) {
const data = JSON.parse(e.target.result);
const texts = Object.keys(data);
const scores = Object.values(data);
// Get embeddings for all texts
const embeddings = [];
for (const text of texts) {
const embedding = await getEmbedding(text);
embeddings.push(embedding);
}
// Transpose embeddings to get per-dimension arrays
const embeddingDim = embeddings[0].length;
const dimensions = Array.from({ length: embeddingDim }, (_, i) =>
embeddings.map(emb => emb[i])
);
// Calculate R-squared for each dimension
const rSquaredValues = dimensions.map(dim =>
calculateRSquared(dim, scores)
);
// Get top 5 dimensions
top5Indices = rSquaredValues
.map((r2, idx) => ({ r2, idx }))
.sort((a, b) => b.r2 - a.r2)
.slice(0, 5)
.map(item => item.idx);
// Prepare training data using top 5 dimensions
const X = embeddings.map(emb =>
top5Indices.map(idx => emb[idx])
);
const y = scores;
// Train linear regression model using TensorFlow.js
const XTensor = tf.tensor2d(X);
const yTensor = tf.tensor2d(y, [y.length, 1]);
const weights = tf.variable(tf.zeros([5, 1]));
const bias = tf.variable(tf.zeros([1]));
const learningRate = 0.01;
const optimizer = tf.train.sgd(learningRate);
// Training loop
for (let i = 0; i < 100; i++) {
optimizer.minimize(() => {
const pred = XTensor.matMul(weights).add(bias);
return tf.losses.meanSquaredError(yTensor, pred);
});
}
regressionModel = { weights, bias };
// Display results
document.getElementById('results').innerHTML = `
<h3>Top 5 Correlated Dimensions (Editable Order):</h3>
<ul id="dimensionList">
${top5Indices.map((idx, i) => `
<li>
Dimension ${idx} (R²: ${rSquaredValues[idx].toFixed(4)})
<button onclick="moveUp(${i})">↑</button>
<button onclick="moveDown(${i})">↓</button>
</li>
`).join('')}
</ul>
`;
};
reader.readAsText(file);
}
// Move dimension up in priority
function moveUp(index) {
if (index > 0) {
[top5Indices[index], top5Indices[index - 1]] =
[top5Indices[index - 1], top5Indices[index]];
processData(); // Refresh display
}
}
// Move dimension down in priority
function moveDown(index) {
if (index < top5Indices.length - 1) {
[top5Indices[index], top5Indices[index + 1]] =
[top5Indices[index + 1], top5Indices[index]];
processData(); // Refresh display
}
}
// Predict ranking for new text
async function predictRanking() {
const text = document.getElementById('predictText').value;
if (!text || !regressionModel) {
alert('Please process data first and enter text to predict');
return;
}
const embedding = await getEmbedding(text);
const X = top5Indices.map(idx => embedding[idx]);
const XTensor = tf.tensor2d([X]);
const prediction = XTensor.matMul(regressionModel.weights)
.add(regressionModel.bias);
const score = (await prediction.data())[0];
document.getElementById('prediction').innerHTML = `
<h3>Prediction:</h3>
<p>Predicted ranking score for "${text}": ${score.toFixed(4)}</p>
`;
}
</script>
</body>
</html>