如何使用 Tensorflow 与 Estimators 构建线性模型来加载泰坦尼克号数据集?

tensorflowserver side programmingprogramming更新于 2025/5/21 11:07:17

可以使用 Estimators 构建线性模型,使用 ‘read_csv’ 方法加载泰坦尼克号数据集,该方法存在于 ‘Pandas’ 包中。此方法采用存储泰坦尼克号数据集的 Google API。读取 API 并将数据以 CSV 文件的形式存储。

阅读更多: 什么是 TensorFlow,以及 Keras 如何与 TensorFlow 配合使用来创建神经网络?

我们将使用 Keras Sequential API,它有助于构建用于处理普通层堆栈的顺序模型,其中每个层都有一个输入张量和一个输出张量。

包含至少一个层的神经网络称为卷积层。我们可以使用卷积神经网络构建学习模型。

TensorFlow Text 包含可与 TensorFlow 2.0 一起使用的文本相关类和操作的集合。TensorFlow Text 可用于预处理序列建模。

我们正在使用 Google Colaboratory 运行以下代码。 Google Colab 或 Colaboratory 可帮助在浏览器上运行 Python 代码,并且无需配置,可以免费访问 GPU(图形处理单元)。Colaboratory 是在 Jupyter Notebook 之上构建的。

Estimator 是 TensorFlow 对完整模型的高级表示。它旨在轻松扩展和异步训练。

我们将使用 tf.estimator API 训练逻辑回归模型。该模型用作其他算法的基线。我们使用泰坦尼克号数据集,目标是根据性别、年龄、等级等特征预测乘客的生存情况。

pip install -q sklearn

示例

import os
import sys
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import clear_output
from six.moves import urllib
import tensorflow.compat.v2.feature_column as fc
import tensorflow as tf
print("Load the dataset")
dftrain = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv')
dfeval = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/eval.csv')
print("Removing feature 'survived'")
y_train = dftrain.pop('survived')
y_eval = dfeval.pop('survived')

代码来源 −https://www.tensorflow.org/tutorials/estimator/linear

输出

Load the dataset
Removing feature 'survived'

解释

  • 已下载所需软件包。
  • 已从 API 下载数据。
  • 已删除"survived"列。

相关文章