現在你已經創建了 HTML 和 JavaScript文件,當在瀏覽器中打開 index.html 文件,並打開devtools 控制檯。
- tf 是對 TensorFlow.js 庫的引用
- tfvis 是對 tfjs-vis 庫的引用。
安裝好 Tensorflow 後第一步就是加載數據,對數據進行格式化和可視化,我們想要訓練模型的數據。
加載數據
讀取 JSON 文件來加載 汽車數據集,已經爲你託管了這個文件。包含了關於每輛汽車的許多不同特徵。在分享中,只想提取有關馬力和mpg每加侖英里的數據。
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;
}
加載數據後,對出原始數據進行適當處理,也可以理解爲對數據的將 Miles_per_Gallon 轉換爲 mpg 字段,而 Horsepower 轉換爲 horsepower 字段,並且過濾調用這些字段爲空(null)數據。
2D 數據可視化
到現在,你應該在頁面的左側看到一個面板,上面有一個數據的散點圖。它看起來應該是這樣的。
async function run() {
// 加載數據
const data = await getData();
// 處理原始數據,將數據 horsepower 映射爲 x 而 mpg 則映射爲 y
const values = data.map(d => ({
x: d.horsepower,
y: d.mpg,
}));
// 將數據以散點圖形式顯示在開發者調試工具
tfvis.render.scatterplot(
{name: 'Horsepower v MPG'},
{values},
{
xLabel: 'Horsepower',
yLabel: 'MPG',
height: 300
}
);
}
document.addEventListener('DOMContentLoaded', run);
這部分代碼如果用過 matplot 朋友應該不陌生,就是在 devtool 工具中繪製一個圖像將數據以更直觀方式顯示出來,其實 name 爲圖標的標題,values 爲數據通常 x 和 y 座標值,而 xLabel 表示 x 軸的座標 yLabel 表示 y 軸的座標
tfvis.render.scatterplot(
{name: 'Horsepower v MPG'},
{values},
{
xLabel: 'Horsepower',
yLabel: 'MPG',
height: 300
}
);
個人對如何在 devtool 繪製圖標還是比較感興趣,有時間也想自己搞一搞。