cover_002.png
現在你已經創建了 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
}
);
截屏2021-06-25上午11.01.49.png
個人對如何在 devtool 繪制圖標還是比較感興趣,有時間也想自己搞一搞。