Core Learning Algorithms

TensorFlow Core Learning Algorithms

In this notebook we will walk through 4 fundemental machine learning algorithms. We will apply each of these algorithms to uniqueproblems and datasets before highlighting the use cases of each.
The algorithms we will focus on include:
Linear Regression
Classification.Clustering
Hidden Markov Models
lt is worth noting that there are many tools within TensorHlow that could be used to solve the problems we willsee below. l have chosen thetools that I belive give the most variety and are easiest to use.

在这个笔记本中,我们将介绍 4 种基本的机器学习算法。在强调每种算法的用例之前,我们将把这些算法中的每一种应用于独特的问题和数据集。
我们将重点关注的算法包括:
线性回归
分类.聚类
隐马尔可夫模型
值得注意的是,TensorHlow 中有许多工具可以用来解决我们将在下面看到的问题。我选择了我认为种类最多且最容易使用的工具。

Linear Regression

Linear regression is one of the most basic forms of machine learning and is used to predict numeric values.In this tutorial we will use a linear model to predict the survival rate of passangers
from the titanic dataset.
This section is based on the following documentation: https://www.tensorflow.org/htutorials/estimator/linear

线性回归是机器学习的最基本形式之一,用于预测数值。在本教程中,我们将使用线性模型来预测乘客的存活率
来自泰坦尼克号数据集。
本节基于以下文档:https://www.tensorflow.org/htutorials/estimator/linear

We can see that this data has a linear coorespondence.When the x value increases, so does the y. Because of this relation we can create a line of best fit for this dataset.In this example our line will only use one input variable, as we areworking with two dimensions. In larger datasets with more features our line will have more features and inputs.
Line of best fit refers to a line through a scatter plot of data points that best expresses the relationship between thosepoints." (https://www.investopeia.com/terms/V/line-of-best-fit.asp)
Here’s a refresher on the eqaution of a line in 2D.
y =ma+b
Here’s an example of a line of best fit for this graph.

我们可以看到这个数据有一个线性的对应关系。当x值增加时,y也会增加。因为这
关系,我们可以为这个数据集创建一条最适合的线。在这个例子中,我们的线将只使用一个输入变量,因为我们正在使用二维。在具有更多特征的较大数据集中,我们的行将具有更多特征和输入。
最佳拟合线是指通过数据点散点图的一条线,最能表达这些点之间的关系。”(https://www.investopeia.com/terms/V/line-of-best-fit.asp)
这是对 2D 中线的等式的复习。
y =ma+b
这是一个最适合该图的线的示例。

plt.plot(x, y, 'ro ')
plt.axis([e,6020])
plt.plot(np.unique(x),np.poly1d(np. polyfit(x,y,1))(np. ugique(x)))plt.show()
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VRYNtzEx-1643012446946)(c2e31d6f294fda72dfc4c7c93463f65c.png)]

多维线性回归

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZLh759VZ-1643012446948)(8835ae4bfeffaf9ff3ad30b5f14708d3.png)]

Training vs Testing Data

You may have noticed that we loaded two diferent datasets above. This is because when we train models we need two sets of data:training and testing.
The training data is what we feed to the model so that it can develop and learn.It is usually a much larger size than the testing data.
The testing data is what we use to evaulate the model and see how well it is performing. We mustuse a seperate set of data that the modelhas not been trained on to evaluate it. Can you think of why this is?
Wel,the point of our model is to be able to make predictions on NEW data,data that we have never seen before If we simply test the modelon the data that it has already seen we cannot measure its accuracy accuratly, We cant be sure that the model hasnt simply memorized ourtraining data. This is why we need our testing and training data to be seperate.

您可能已经注意到我们在上面加载了两个不同的数据集。这是因为当我们训练模型时,我们需要两组数据:训练和测试。
训练数据是我们提供给模型的,以便它可以开发和学习。它通常比测试数据大得多。
测试数据是我们用来评估模型并查看其执行情况的数据。我们必须使用模型尚未经过训练的单独数据集来评估它。你能想到这是为什么吗?
嗯,我们模型的重点是能够对我们从未见过的新数据进行预测该模型并没有简单地记住我们的训练数据。这就是为什么我们需要我们的测试和训练数据是分开的。

Feature Columns

In our dataset we have two different kinds of information: Categorical and Numer
Our categorical data is anything that is not numericl For example,the sex column does not use numbers, it uses the words “male” and"female".
Before we continue and create/train a model we must convet our categorical data into numeric data. We can do this by encoding eachcategory with an integer (ex. male = 1, female = 2).
Fortunately for us TensorFlow has some tools to help!

在我们的数据集中,我们有两种不同的信息:分类和数字
我们的分类数据是任何非数字的数据。例如,性别列不使用数字,它使用“男性”和“女性”这两个词。
在我们继续创建/训练模型之前,我们必须将分类数据转换为数字数据。我们可以通过使用整数对每个类别进行编码来做到这一点(例如,男性 = 1,女性 = 2)。
对我们来说幸运的是,TensorFlow 有一些工具可以提供帮助!

创建特征列与输入函数

梯度提升(Gradient Boosting) Estimator 可以利用数值和分类特征。特征列适用于所有的 Tensorflow estimator,其目的是定义用于建模的特征。此外,它们还提供一些特征工程功能,如独热编码(one-hot-encoding)、标准化(normalization)和桶化(bucketization)。在本教程中,CATEGORICAL_COLUMNS 中的字段从分类列转换为独热编码列(指标列):

fc = tf.feature_column
CATEGORICAL_COLUMNS = ['sex', 'n_siblings_spouses', 'parch', 'class', 'deck',
                       'embark_town', 'alone']
NUMERIC_COLUMNS = ['age', 'fare']

def one_hot_cat_column(feature_name, vocab):
  return tf.feature_column.indicator_column(
      tf.feature_column.categorical_column_with_vocabulary_list(feature_name,
                                                 vocab))
feature_columns = []
for feature_name in CATEGORICAL_COLUMNS:
  # Need to one-hot encode categorical features.
  vocabulary = dftrain[feature_name].unique()
  feature_columns.append(one_hot_cat_column(feature_name, vocabulary))

for feature_name in NUMERIC_COLUMNS:
  feature_columns.append(tf.feature_column.numeric_column(feature_name,
                                           dtype=tf.float32))

您可以查看特征列生成的转换。例如,以下是在单个样本中使用 indicator_column 的输出:

example = dict(dftrain.head(1))
class_fc = tf.feature_column.indicator_column(tf.feature_column.categorical_column_with_vocabulary_list('class', ('First', 'Second', 'Third')))
print('Feature value: "{}"'.format(example['class'].iloc[0]))
print('One-hot encoded: ', tf.keras.layers.DenseFeatures([class_fc])(example).numpy())

Feature value: “Third”
One-hot encoded: [[ 0. 0. 1.]]

此外,您还可以一起查看所有特征列的转换:

tf.keras.layers.DenseFeatures(feature_columns)(example).numpy()

array([[ 22. , 1. , 0. , 1. , 0. , 0. , 1. , 0. ,

      0.  ,   0.  ,   0.  ,   0.  ,   0.  ,   0.  ,   1.  ,   0.  ,
      0.  ,   0.  ,   7.25,   1.  ,   0.  ,   0.  ,   0.  ,   0.  ,
      0.  ,   0.  ,   1.  ,   0.  ,   0.  ,   0.  ,   0.  ,   0.  ,
      1.  ,   0.  ]], dtype=float32)

接下来,您需要创建输入函数。这些将指定如何将数据读入到我们的模型中以供训练与推理。您将使用 tf.dataAPI 中的 from_tensor_slices 方法直接从 Pandas 中读取数据。这适用于较小的内存数据集。对于较大的数据集,tf.data API 支持各种文件格式(包括 csv),以便您能处理那些不适合放入内存中的数据集。

# 使用大小为全部数据的 batch ,因为数据规模非常小.
NUM_EXAMPLES = len(y_train)

def make_input_fn(X, y, n_epochs=None, shuffle=True):
  def input_fn():
    dataset = tf.data.Dataset.from_tensor_slices((dict(X), y))
    if shuffle:
      dataset = dataset.shuffle(NUM_EXAMPLES)
    # 对于训练,可以按需多次循环数据集(n_epochs=None)。
    dataset = dataset.repeat(n_epochs)
    # 在内存中训练不使用 batch。
    dataset = dataset.batch(NUM_EXAMPLES)
    return dataset
  return input_fn

# 训练与评估的输入函数。
train_input_fn = make_input_fn(dftrain, y_train)
eval_input_fn = make_input_fn(dfeval, y_eval, shuffle=False, n_epochs=1)

训练与评估模型

您将执行以下步骤:

初始化模型,指定特征和超参数。
使用 train_input_fn 将训练数据输入模型,使用 train 函数训练模型。
您将使用此示例中的评估集评估模型性能,即 dfeval DataFrame。您将验证预测是否与 y_eval 数组中的标签匹配。
在训练提升树(Boosted Trees)模型之前,让我们先训练一个线性分类器(逻辑回归模型)。最好的做法是从更简单的模型开始建立基准。

linear_est = tf.estimator.LinearClassifier(feature_columns)

# 训练模型。
linear_est.train(train_input_fn, max_steps=100)

# 评估。
result = linear_est.evaluate(eval_input_fn)
clear_output()
print(pd.Series(result))

accuracy 0.765152
accuracy_baseline 0.625000
auc 0.832844
auc_precision_recall 0.789631
average_loss 0.478908
global_step 100.000000
label/mean 0.375000
loss 0.478908
precision 0.703297
prediction/mean 0.350790
recall 0.646465
dtype: float64

下面让我们训练提升树(Boosted Trees)模型。提升树(Boosted Trees)是支持回归(BoostedTreesRegressor)和分类(BoostedTreesClassifier)的。由于目标是预测一个生存与否的标签,您将使用 BoostedTreesClassifier。

# 由于数据存入内存中,在每层使用全部数据会更快。
# 上面一个 batch 定义为整个数据集。
n_batches = 1
est = tf.estimator.BoostedTreesClassifier(feature_columns,
                                          n_batches_per_layer=n_batches)

# 一旦建立了指定数量的树,模型将停止训练,
# 而不是基于训练步数。
est.train(train_input_fn, max_steps=100)

# 评估。
result = est.evaluate(eval_input_fn)
clear_output()
print(pd.Series(result))

accuracy 0.829545
accuracy_baseline 0.625000
auc 0.872788
auc_precision_recall 0.857807
average_loss 0.411839
global_step 100.000000
label/mean 0.375000
loss 0.411839
precision 0.793478
prediction/mean 0.381942
recall 0.737374
dtype: float64

现在您可以使用训练的模型从评估集上对乘客进行预测了。Tensorflow 模型经过优化,可以同时在一个 batch 或一个集合的样本上进行预测。之前,eval_inout_fn 是使用整个评估集定义的。

pred_dicts = list(est.predict(eval_input_fn))
probs = pd.Series([pred['probabilities'][1] for pred in pred_dicts])

probs.plot(kind='hist', bins=20, title='predicted probabilities')
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RMpmDCWG-1643012446949)(f7a53f9cb8f8ca7de19ac47aab71780e.png)]

最后,您还可以查看结果的受试者工作特征曲线(ROC),这将使我们更好地了解真阳性率与假阴性率之间的权衡。

from sklearn.metrics import roc_curve

fpr, tpr, _ = roc_curve(y_eval, probs)
plt.plot(fpr, tpr)
plt.title('ROC curve')
plt.xlabel('false positive rate')
plt.ylabel('true positive rate')
plt.xlim(0,)
plt.ylim(0,)
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vC7CI3ON-1643012446949)(2e60920f844eeb7c8b1161cdcaa4b2c4.png)]

The Training Process

The Training Process
So we are almost done preparing our dataset and I feel as though it’s a good time to explain how our model is trained.Specifically how input data is fed to our model.
For this specific model data is going to be streamed into it in small batches of 32. This means we will not feed the entire dataset to our model at once,but simply small batches of entrill actually feed these batches to our model multiple times accord
of epochs.
An epoch is simply one stream of our entire dataset. The number of epochs we define is the amount of times our model will see the entire dataset. We use multiple epochs in hope that after seeing the same data multiple times the model will better determine how to estimate it.
Ex. if we have 10 ephocs, our model will see the same dataset 10 times.
Since we need to feed our data in batches and multiple times we need to create something called input fuction.The input fuction simply defines how our dataset will be converted into batches at each epoch.

所以我们几乎完成了数据集的准备工作,我觉得现在是解释我们的模型是如何训练的好时机。特别是如何将输入数据馈送到我们的模型中。
对于这个特定的模型,数据将以 32 个的小批量流入其中。这意味着我们不会一次将整个数据集提供给我们的模型,而只是小批量的 entrill 实际上将这些批次多次提供给我们的模型
的时代。
一个纪元只是我们整个数据集的一个流。我们定义的时期数是我们的模型将看到整个数据集的次数。我们使用多个时期,希望在多次看到相同的数据后,模型将更好地确定如何估计它。
前任。如果我们有 10 个 ephoc,我们的模型将看到相同的数据集 10 次。
由于我们需要分批多次输入数据,我们需要创建一个叫做输入函数的东西。输入函数简单地定义了我们的数据集如何在每个时期被转换成批次。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值