
現(xiàn)在你已經(jīng)創(chuàng)建了 HTML 和 JavaScript文件,當(dāng)在瀏覽器中打開 index.html 文件,并打開devtools 控制臺(tái)。
- tf 是對(duì) TensorFlow.js 庫(kù)的引用
- tfvis 是對(duì) tfjs-vis 庫(kù)的引用。
安裝好 Tensorflow 后第一步就是加載數(shù)據(jù),對(duì)數(shù)據(jù)進(jìn)行格式化和可視化,我們想要訓(xùn)練模型的數(shù)據(jù)。
加載數(shù)據(jù)
讀取 JSON 文件來(lái)加載 汽車數(shù)據(jù)集,已經(jīng)為你托管了這個(gè)文件。包含了關(guān)于每輛汽車的許多不同特征。在分享中,只想提取有關(guān)馬力和mpg每加侖英里的數(shù)據(jù)。
async function getData() {
const carsDataResponse = await fetch('https://storage.googleapis.com/tfjs-tutorials/carsData.json');
const carsData = await carsDataResponse.json();
const cleaned = carsData.map(car => ({
mpg: car.Miles_per_Gallon,
horsepower: car.Horsepower,
}))
.filter(car => (car.mpg != null && car.horsepower != null));
return cleaned;
}
加載數(shù)據(jù)后,對(duì)出原始數(shù)據(jù)進(jìn)行適當(dāng)處理,也可以理解為對(duì)數(shù)據(jù)的將 Miles_per_Gallon 轉(zhuǎn)換為 mpg 字段,而 Horsepower 轉(zhuǎn)換為 horsepower 字段,并且過(guò)濾調(diào)用這些字段為空(null)數(shù)據(jù)。
2D 數(shù)據(jù)可視化
到現(xiàn)在,你應(yīng)該在頁(yè)面的左側(cè)看到一個(gè)面板,上面有一個(gè)數(shù)據(jù)的散點(diǎn)圖。它看起來(lái)應(yīng)該是這樣的。
async function run() {
// 加載數(shù)據(jù)
const data = await getData();
// 處理原始數(shù)據(jù),將數(shù)據(jù) horsepower 映射為 x 而 mpg 則映射為 y
const values = data.map(d => ({
x: d.horsepower,
y: d.mpg,
}));
// 將數(shù)據(jù)以散點(diǎn)圖形式顯示在開發(fā)者調(diào)試工具
tfvis.render.scatterplot(
{name: 'Horsepower v MPG'},
{values},
{
xLabel: 'Horsepower',
yLabel: 'MPG',
height: 300
}
);
}
document.addEventListener('DOMContentLoaded', run);
這部分代碼如果用過(guò) matplot 朋友應(yīng)該不陌生,就是在 devtool 工具中繪制一個(gè)圖像將數(shù)據(jù)以更直觀方式顯示出來(lái),其實(shí) name 為圖標(biāo)的標(biāo)題,values 為數(shù)據(jù)通常 x 和 y 坐標(biāo)值,而 xLabel 表示 x 軸的坐標(biāo) yLabel 表示 y 軸的坐標(biāo)
tfvis.render.scatterplot(
{name: 'Horsepower v MPG'},
{values},
{
xLabel: 'Horsepower',
yLabel: 'MPG',
height: 300
}
);

個(gè)人對(duì)如何在 devtool 繪制圖標(biāo)還是比較感興趣,有時(shí)間也想自己搞一搞。