
cover_002.png
現(xiàn)在你已經(jīng)創(chuàng)建了 HTML 和 JavaScript文件,當在瀏覽器中打開 index.html 文件,并打開devtools 控制臺。
- tf 是對 TensorFlow.js 庫的引用
- tfvis 是對 tfjs-vis 庫的引用。
安裝好 Tensorflow 后第一步就是加載數(shù)據(jù),對數(shù)據(jù)進行格式化和可視化,我們想要訓(xùn)練模型的數(shù)據(jù)。
加載數(shù)據(jù)
讀取 JSON 文件來加載 汽車數(shù)據(jù)集,已經(jīng)為你托管了這個文件。包含了關(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ù)后,對出原始數(shù)據(jù)進行適當處理,也可以理解為對數(shù)據(jù)的將 Miles_per_Gallon 轉(zhuǎn)換為 mpg 字段,而 Horsepower 轉(zhuǎn)換為 horsepower 字段,并且過濾調(diào)用這些字段為空(null)數(shù)據(jù)。
2D 數(shù)據(jù)可視化
到現(xiàn)在,你應(yīng)該在頁面的左側(cè)看到一個面板,上面有一個數(shù)據(jù)的散點圖。它看起來應(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ù)以散點圖形式顯示在開發(fā)者調(diào)試工具
tfvis.render.scatterplot(
{name: 'Horsepower v MPG'},
{values},
{
xLabel: 'Horsepower',
yLabel: 'MPG',
height: 300
}
);
}
document.addEventListener('DOMContentLoaded', run);
這部分代碼如果用過 matplot 朋友應(yīng)該不陌生,就是在 devtool 工具中繪制一個圖像將數(shù)據(jù)以更直觀方式顯示出來,其實 name 為圖標的標題,values 為數(shù)據(jù)通常 x 和 y 坐標值,而 xLabel 表示 x 軸的坐標 yLabel 表示 y 軸的坐標
tfvis.render.scatterplot(
{name: 'Horsepower v MPG'},
{values},
{
xLabel: 'Horsepower',
yLabel: 'MPG',
height: 300
}
);

截屏2021-06-25上午11.01.49.png
個人對如何在 devtool 繪制圖標還是比較感興趣,有時間也想自己搞一搞。