首页 > 解决方案 > 计算预测的置信度

问题描述

我正在制作一个简单的程序,试图从一组值中预测一个值:

require('@tensorflow/tfjs-node');
const {layers, setBackend, sequential, train} = require('@tensorflow/tfjs');

setBackend('tensorflow');

const {xs, ys} = require('./data.v2');

const [samples] = xs.shape;
const MAX_SAMPLES = samples - 3; // Leave 3 for predictions

const trainXs = xs.slice([0], MAX_SAMPLES);
const trainYs = ys.slice([0], MAX_SAMPLES);

const predict = xs.slice([MAX_SAMPLES]);
const expect = ys.slice([MAX_SAMPLES]);


const LEARNING_RATE = 0.01;

const BATCH_SIZE = 2;
const EPOCHS = 1000;


// Define a model for linear regression.
const model = sequential();

// First layer must have an input shape defined
model.add(layers.dense({units: 16, inputShape: [37,]}));
// Afterwards, TF.js does automatic shape inference
model.add(layers.dense({units: 4}));
model.add(layers.dense({units: 1}));


// https://js.tensorflow.org/api/0.10.0/#Training-Optimizers
const optimizer = train.adam(LEARNING_RATE);

// NOTE: For classification we would use a cross entropy loss fn,
// but for regression, we prefer mean squared error
// https://stackoverflow.com/a/36516373/1092007
// Prepare the model for training: Specify the loss and the optimizer.
model.compile({
    optimizer,
    loss: 'meanSquaredError'
});


fit(trainXs, trainYs, EPOCHS, BATCH_SIZE)
    .then(() => {
        console.log('Done training');
        // Use the model to do inference on a data point the model hasn't seen before:
        const item = predict.slice([0], 1);
        console.log(item.dataSync());

        model.predict(item, true)
            .print();

        expect.slice([0], 1)
            .print();
    });


async function fit(xs, ys, epochs, batchSize) {
    // Train the model using the data
    const history = await model.fit(xs, ys, {
        batchSize,
        epochs,
        shuffle: true,
        validationSplit: 0.3,
        callbacks: {
            onEpochEnd(...args) {
                const [epoch, history] = args;
                const {loss} = history;
                console.log(`Loss after epoch ${epoch}: ${loss}`);
            }
        }
    });
}

输入数据是一个形状张量[53, 37]

[[1, 2, 3, ...], [4, 5, 6, ...], ...]

输出是向量(形状[53]):

[3, 4, ...]

但我想知道如何计算输出的置信度.predict()

注意:我将tensorflow.js与 Node 一起使用,因此 API 可能与 Python API 有点不同。

标签: tensorflowtensorflow.js

解决方案


推荐阅读