JSFiddle - React, Tailwind, and code Playground
by frogggeee McFrogggeee
HTML
<!DOCTYPE html>
<html>
<head>
<title>Simplified TensorFlow.js Experiment</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
</head>
<body>
<div id="result"></div>
<script>
// Step 1: Generate Simple Synthetic Data for Training
function generateData() {
const inputs = [
[0.5, 0.6], // Closing price, Moving average
[0.6, 0.7],
[0.8, 0.75],
[0.9, 0.85],
[0.7, 0.65],
[0.6, 0.55]
];
const labels = [
[1], // Buy
[1], // Buy
[-1], // Sell
[-1], // Sell
[1], // Buy
[1] // Buy
];
return { inputs, labels };
}
// Step 2: Build a Simple Model
function buildModel() {
const model = tf.sequential();
model.add(tf.layers.dense({ units: 4, inputShape: [2], activation: 'relu' })); // 2 input features, 4 neurons
model.add(tf.layers.dense({ units: 1, activation: 'tanh' })); // 1 output for buy/sell decision
model.compile({ optimizer: 'adam', loss: 'meanSquaredError' });
return model;
}
// Step 3: Train the Model
async function trainModel(model, inputs, labels) {
const xs = tf.tensor2d(inputs);
const ys = tf.tensor2d(labels);
await model.fit(xs, ys, {
epochs: 10, // Fewer epochs for simplicity
callbacks: {
onEpochEnd: (epoch, logs) => {
console.log(`Epoch ${epoch + 1}: Loss = ${logs.loss.toFixed(4)}`);
}
}
});
}
// Step 4: Test the Model
async function testModel(model, input) {
const inputTensor = tf.tensor2d([input]); // Input is an array [close, moving average]
...