如何在Tensorflow.js的评估方法"evaluate(("中使用返回的"tf.data.csv"值?
我想在TFJS上训练一个简单的模型。首先,我从 CSV 文件中读取数据。然后我训练了模型,最后我计算了损失和准确性。 但我无法测量由"tf.data.csv"导入的测试数据集的准确性。
<html>
<head></head>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>
<script lang="js">
async function run(){
const trainingUrl = 'wdbc-train.csv';
const trainingData = tf.data.csv(trainingUrl, {
columnConfigs: {
diagnosis:{
isLabel: true
}
}
});
const numOfFeatures = (await trainingData.columnNames()).length - 1;
const numOfSamples= 455
const convertedData =
trainingData.map(({xs, ys}) => {
const labels = [
ys.diagnosis == 1 ? 1 : 0
]
return{ xs: Object.values(xs), ys: Object.values(labels)};
}).batch(20);
const testingUrl = 'wdbc-test.csv';
const testingData = tf.data.csv(testingUrl, {
columnConfigs: {
diagnosis:{
isLabel: true
}
}
});
const convertedTestingData = // YOUR CODE HERE
testingData.map(({xs, ys}) => {
const labels = [
ys.diagnosis == 1 ? 1 : 0
]
return{ xs: Object.values(xs), ys: Object.values(labels)};
}).batch(10);
const numOfTestFeatures = (await testingData.columnNames()).length - 1;
const a =testingData.toArray()
console.log(a)
const model = tf.sequential();
model.add(tf.layers.dense({inputShape: [numOfFeatures], activation: "relu", units: 10}));
model.add(tf.layers.dense({inputShape: 10 , activation: "relu", units: 10}));
model.add(tf.layers.dense({activation: "sigmoid", units: 1}));
model.compile({loss: "binaryCrossentropy", optimizer: tf.train.rmsprop(0.05),metrics: "accuracy"});
await model.fitDataset(convertedData,
{epochs:2,
callbacks:{
onEpochEnd: async(epoch, logs) =>{
console.log("Epoch: " + epoch + " Loss: " + logs.loss );
}
}});
const result = model.evaluateDataset(convertedData,{batchSize: 10});
console.log("Accuracy: " + result);
await model.save('downloads://my_model');
}
run();
</script>
<body>
</body>
</html>
tf.data.csv
返回一个tf.data.Dataset
。evaluate
方法需要tensor
或tensor
数组。如果要评估tf.data.Dataset
,则可以改用方法evaluateDataset
。
evaluateDataset
返回一个承诺。
const data = await model.evaluateDataset(testingData)
// data can be a tf.Scalar or an array of tf.Scalar