线性回归是机器学习的最基本形式之一,用于预测数值。 它通常用于查找两个或多个事物之间的相关性。 在本教程中,我们将使用线性模型从 Titanic 数据集中预测乘客的存活率。
什么是线性回归 ?这是线性回归算法的表面解释。 线性回归遵循一个非常简单的概念。 如果数据点是线性相关的,我们可以为这些点生成一条最佳拟合线,并用它来预测未来值。这是一个具有一个特征和一个标签的数据集的示例
最佳拟合线由蓝线给出,并由方程式表示(
y
=
m
x
+
b
y=mx+b
y=mx+b)。 在具有更多特征的较大数据集中,找到这种线性回归将变得更加复杂。 但是一旦我们生成了这条线,我们就可以使用该方程来预测输出。 我们只需要将数据点的特征传递到直线方程中,并使用输出作为我们的预测。
先倒入相关模块
# Imports from __future__ import absolute_import, division, print_function, unicode_literals import tensorflow as tf import numpy as np import pandas as pd
数据可能是机器学习中最重要的部分。因此,我们首先必须专注于分析,预处理和选择合适的数据。首先,我们需要加载和分析数据
# load dataset
dftrain = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/train.csv') # training data
dfeval = pd.read_csv('https://storage.googleapis.com/tf-datasets/titanic/eval.csv') # testing data
dftrain.head() # look at first 5 items
Titanic数据集包含床上每位乘客的信息。数据集的形状为
dftrain.shape # (627, 10)
所以,我们有627个条目和10个特征。 然后我们从数据集pop出survived列及存到一个新变量中。survived告诉我们这个人是否生存。这也成为我们的标签。
y_train = dftrain.pop('survived')
y_eval = dfeval.pop('survived')
需要注意的是,有两个数据集,一个用于训练,一个用于测试。训练数据是我们提供给模型的数据,以便他可以学习。训练数据通常比测试数据量大很多。测试数据用于聘雇模型并查看其性能如何。测试数据必须不同于训练数据,因为模型应该能够对未见过的心数据做出准确的预测。
特征列 Feature Columns在我们的数据集中,有两种类型的信息,分类信息和数字信息。 在继续之前,我们必须通过将每个类别编码为整数来将这些类别数据转换为数值数据。 (例如,男性 = 0,女性 = 1)。
CATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck', 'embark_town', 'alone'] NUMERIC_COLUMNS = ['age', 'fare'] feature_columns = [] for feature_name in CATEGORICAL_COLUMNS: vocabulary = dftrain[feature_name].unique() # gets a list of all unique values from given feature column feature_columns.append(tf.feature_column.categorical_column_with_vocabulary_list(feature_name, vocabulary)) for feature_name in NUMERIC_COLUMNS: feature_columns.append(tf.feature_column.numeric_column(feature_name, dtype=tf.float32)) print(feature_columns)
[VocabularyListCategoricalColumn(key='sex', vocabulary_list=('male', 'female'), dtype=tf.string, default_value=-1, num_oov_buckets=0), VocabularyListCategoricalColumn(key='n_siblings_spouses', vocabulary_list=(1, 0, 3, 4, 2, 5, 8), dtype=tf.int64, default_value=-1, num_oov_buckets=0), VocabularyListCategoricalColumn(key='parch', vocabulary_list=(0, 1, 2, 5, 3, 4), dtype=tf.int64, default_value=-1, num_oov_buckets=0), VocabularyListCategoricalColumn(key='class', vocabulary_list=('Third', 'First', 'Second'), dtype=tf.string, default_value=-1, num_oov_buckets=0), VocabularyListCategoricalColumn(key='deck', vocabulary_list=('unknown', 'C', 'G', 'A', 'B', 'D', 'F', 'E'), dtype=tf.string, default_value=-1, num_oov_buckets=0), VocabularyListCategoricalColumn(key='embark_town', vocabulary_list=('Southampton', 'Cherbourg', 'Queenstown', 'unknown'), dtype=tf.string, default_value=-1, num_oov_buckets=0), VocabularyListCategoricalColumn(key='alone', vocabulary_list=('n', 'y'), dtype=tf.string, default_value=-1, num_oov_buckets=0), NumericColumn(key='age', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None), NumericColumn(key='fare', shape=(1,), default_value=None, dtype=tf.float32, normalizer_fn=None)]
本质上,我们在创建一个特征列表。我们的模型使用append()创建的对象对字符串值映射到证书,而无序手动编码titanic数据表。
训练 Training接下来,我们将训练我们的数据。 由于计算机的 RAM 有限,我们通常无法一次将整个数据集加载到模型中,而是必须以小批量条目的形式进行(这也有助于提高效率)。 根据 epoch 的数量,这些批次被多次输入到我们的模型中。 对于我们特定的特定模型,输入模型的数据将以 32 个为小批量。
Epoch 只是我们整个数据集的一次运行。 我们定义的时期数是我们的模型将看到整个数据集的次数。 例如,如果我们有 10 个 epoch,我们的模型将看到数据集 10 次。 我们使用多个 epoch,希望在多次看到相同的数据后,模型会改进并做出更准确的预测。
由于我们需要分批和多次为我们的数据收费,我们需要创建一个称为输入函数的东西,它定义了我们的数据集将如何转换为批次。 输入函数定义为
输入函数 Input Functiondef make_input_fn(data_df, label_df, num_epochs=10, shuffle=True, batch_size=32):
def input_function(): # function to be returned
ds = tf.data.Dataset.from_tensor_slices((dict(data_df), label_df)) # create tf.data.Dataset object with data and its label
if shuffle:
ds = ds.shuffle(1000) # randomize order of data
ds = ds.batch(batch_size).repeat(num_epochs) # split dataset into batches of 32 and repeat process for number of epochs
return ds # return a batch of the dataset
return input_function # return a function object for use
train_input_fn = make_input_fn(dftrain, y_train) # here we will call the input_function that was returned to us to get a dataset object we can feed to the model
eval_input_fn = make_input_fn(dfeval, y_eval, num_epochs=1, shuffle=False)
num_epochs 参数和 batch_size 参数的数量可以被操纵。 我们的工作是找到提供最佳模型的最佳参数。
我们将使用线性估计模型来利用线性回归算法。
# create a linear estimtor by passing the feature columns we created earlier linear_est = tf.estimator.LinearClassifier(feature_columns=feature_columns)
接下来,我们通过传递我们之前创建的输入函数来训练模型
linear_est.train(train_input_fn) # train result = linear_est.evaluate(eval_input_fn) # get model metrics/stats by testing on testing data print(result['accuracy']) # the result variable is simply a dict of states about our model.
我们看到我们可以达到 75% 左右的准确率。这意味着这个模型大约有75%的机会根据一个人的特征准确预测一个人是否能够生存。
Conclusion这是使用 Titanic 数据集对 Tensorflow 和线性回归的简单介绍。 然而,事实上我们可以用数据和模型做很多事情。 并且越来越熟悉 python 和 tensorflow 可以给我们带来更有趣的可视化和结果。下次再见!



