示例 1 数据
TensorFlow 数据收集
示例 1 中使用的数据,是一个汽车对象列表,如下所示:
{
"Name": "chevrolet chevelle malibu",
"Miles_per_Gallon": 18,
"Cylinders": 8,
"Displacement": 307,
"Horsepower": 130,
"Weight_in_lbs": 3504,
"Acceleration": 12,
"Year": "1970-01-01",
"Origin": "USA"
},
{
"Name": "buick skylark 320",
"Miles_per_Gallon": 15,
"Cylinders": 8,
"Displacement": 350,
"Horsepower": 165,
"Weight_in_lbs": 3693,
"Acceleration": 11.5,
"Year": "1970-01-01",
"Origin": "USA"
},
该数据集是一个 JSON 文件,存储在:
https://storage.googleapis.com/tfjs-tutorials/carsData.json
Cleaning Data
在为机器学习做准备时,始终重要的是:
- 移除不需要的数据
- 清理数据中的错误
移除数据
移除不必要数据的一种聪明方法是**仅提取你需要的数据**。
这可以通过使用 **map 函数** 迭代(循环)你的数据来完成。
下面的函数接收一个对象,并仅返回对象中 Horsepower 和 Miles_per_Gallon 属性的 **x 和 y** 值:
function extractData(obj) {
return {x:obj.Horsepower, y:obj.Miles_per_Gallon};
}
移除错误
大多数数据集都包含某种类型的错误。
移除错误的一种聪明方法是使用 **filter 函数** 来过滤掉错误。
如果任一属性(x 或 y)包含 null 值,下面的代码将返回 false:
function removeErrors(obj) {
return obj.x != null && obj.y != null;
}
获取数据
当你准备好 map 和 filter 函数后,就可以编写一个函数来获取数据。
async function runTF() {
const jsonData = await fetch("cardata.json");
let values = await jsonData.json();
values = values.map(extractData).filter(removeErrors);
}
绘制数据
这里有一些可以用来绘制数据的代码:
function tfPlot(values, surface) {
tfvis.render.scatterplot(surface,
{values:values, series:['Original','Predicted']},
{xLabel:'Horsepower', yLabel:'MPG'});
}