如何使用 TensorFlow 将数据导入到 Auto MPG 数据集中以预测燃油效率(基本回归)?
TensorFlow 是 Google 提供的一个机器学习框架。它是一个开源框架,与 Python 结合使用,可以实现算法、深度学习应用程序等等。它用于研究和生产目的。
可以使用以下代码行在 Windows 上安装 “tensorflow” 包:
pip install tensorflow
张量是 TensorFlow 中使用的一种数据结构。它有助于连接数据流图中的边。此数据流图称为“数据流图”。张量只不过是多维数组或列表。
回归问题的目标是预测连续或离散变量的输出,例如价格、概率、是否会下雨等等。
我们使用的数据集称为“Auto MPG”数据集。它包含 20 世纪 70 年代和 80 年代汽车的燃油效率。它包括重量、马力、排量等属性。通过这些,我们需要预测特定车辆的燃油效率。
我们使用 Google Colaboratory 来运行以下代码。Google Colab 或 Colaboratory 帮助在浏览器上运行 Python 代码,无需任何配置,并可免费访问 GPU(图形处理单元)。Colaboratory 建立在 Jupyter Notebook 之上。
以下是使用 Auto MPG 数据集预测燃油效率的代码:
示例
import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns np.set_printoptions(precision=3, suppress=True) import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras.layers.experimental import preprocessing print("The version of tensorflow is ") print(tf.__version__) url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data' column_names = ['MPG', 'Cylinders', 'Displacement', 'Horsepower', 'Weight', 'Acceleration', 'Model Year', 'Origin'] print("The data is being loaded") print("The column names have been defined") raw_dataset = pd.read_csv(url, names=column_names, na_values='?', comment='\t', sep=' ', skipinitialspace=True) dataset = raw_dataset.copy() print("A sample of the dataset") dataset.head(2)
代码来源 − https://tensorflowcn.cn/tutorials/keras/regression
输出
The version of tensorflow is 2.4.0 The data is being loaded The column names have been defined A sample of the dataset
序号 | MPG | 气缸数 | 排量 | 马力 | 重量 | 加速 | 车型年份 | 产地 |
---|---|---|---|---|---|---|---|---|
0 | 18.0 | 8 | 307.0 | 130.0 | 3504.0 | 12.0 | 70 | 1 |
1 | 15.0 | 8 | 350.0 | 165.0 | 3693.0 | 11.5 | 70 | 1 |
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
解释
导入并为所需的包设置别名。
加载数据,并为其定义列名。
在控制台上显示数据集的样本。
广告