提交 bc4074ad 编写于 作者: W wizardforcel

2021-01-16 20:32:15

上级 b9acee42
......@@ -44,17 +44,17 @@
此处简要介绍并解释了使用深度学习的银行和金融服务中的某些领域:
* **Loan application evaluation**: Banks issue loans to customers based on different factors, including demographical information, credit history, and so on. Their main objective in this process is to minimize the number of customers who will default on loan payments (minimize the failure rate), thereby maximizing the returns obtained through the loans that have been issued.
* **贷款申请评估**:银行根据不同的因素(包括人口统计信息,信用记录等)向客户发放贷款。 他们在此过程中的主要目标是最大程度地减少将拖欠贷款的客户数量(使失败率最小),从而使通过已发行贷款获得的回报最大化。
神经网络用于帮助决定是否授予贷款。 通常使用以前未偿还贷款的贷款人以及按时偿还贷款的人的数据对他们进行训练。 创建模型后,想法是将新申请人的数据输入模型中,以便预测他们是否会偿还贷款,考虑到模型的重点应该是减少虚假的数量 正数(模型预测的客户会拖欠贷款,但实际上没有)。
在行业中,已知神经网络的故障率低于依靠人类专业知识的传统方法。
* **Detection of fraud**: Fraud detection is crucial for banks and financial providers, considering the advancements of technology that, in spite of making our lives easier, also leave us exposed to greater financial risks.
* **欺诈检测**:欺诈检测对于银行和金融服务提供商至关重要,考虑到技术的进步,尽管使我们的生活更轻松,但也使我们面临更大的金融风险。
在该域中,特别是 CNN,使用神经网络进行字符和图像识别,以检测字符图像中的隐藏和抽象图案,以确定用户是否遭受欺诈。
* **Credit card customer selection**: To remain profitable in the long term, credit card providers need to find the right customers. For instance, approving a credit card to a customer with limited credit card needs (that is, a customer who will not use it) will result in low credit card revenues.
* **信用卡客户选择**:为了长期保持盈利,信用卡提供商需要找到合适的客户。 例如,将信用卡批准给信用卡需求有限的客户(即不会使用的客户)将导致信用卡收入较低。
另一方面,信用卡发行商也有兴趣预测客户是否会拖欠下一次付款。 这将帮助发卡机构提前知道将拖欠的资金数量,以便他们进行准备,以保持盈利。
......@@ -110,7 +110,7 @@
但是,在开始训练模型之前,必须处理一些关键方面。 您已经从上一章中了解了其中的大多数内容,这些内容将应用于当前数据集,并在目标特征中添加了类不平衡的修订:
* **Take a look at the data**: After reading the dataset using Pandas, print the head of the dataset. This helps to ensure that the correct dataset has been loaded. Additionally, it serves to provide evidence of transforming the dataset after preparation.
* **看看数据**:使用熊猫读取数据集后,打印数据集的标题。 这有助于确保已加载正确的数据集。 此外,它还提供了准备后转换数据集的证据。
注意
......@@ -139,7 +139,7 @@
print("rows:",data.shape[0]," columns:", data.shape[1])
```
* **Remove irrelevant features**: By performing analysis on each of the features, it is possible to determine that two of the features should be removed from the dataset as they are irrelevant to the purpose of the study:
* **删除不相关的特征**:通过对每个特征进行分析,可以确定应从数据集中删除两个特征,因为它们与研究目的无关:
```py
data_clean = data.drop(columns=["ID", "SEX"])
......@@ -152,7 +152,7 @@ print("rows:",data.shape[0]," columns:", data.shape[1])
图 3.4:删除无关特征后的 DCCC 数据集的标题
* **Check for missing values**: Next, it is time to check whether the dataset is missing any values, and, if so, calculate the percentage of how much they represent each feature, which can be done using the following lines of code:
* **检查缺失值**:接下来,是时候检查数据集是否缺失任何值,如果是,则计算它们代表每个要素的百分比,这可以使用以下代码行完成 :
```py
total = data_clean.isnull().sum()
......@@ -170,7 +170,7 @@ print("rows:",data.shape[0]," columns:", data.shape[1])
根据这些结果,可以说数据集没有丢失任何值,因此这里不需要采取进一步的措施。
* **Check for outliers**: As we mentioned in *Chapter 2*, *Building Blocks of Neural Networks*, there are several ways to check for outliers. However, in this book, we will stick to the standard deviation methodology, where values that are three standard deviations away from the mean will be considered outliers. Using the following code, it is possible to identify outliers from each feature and calculate the proportion they represent against the entire set of values:
* **检查异常值**:正如我们在“第 2 章”,“神经网络的构建基块”中提到的,有几种方法可以检查异常值。 但是,在本书中,我们将坚持使用标准差方法,将偏离均值三个标准差的值视为离群值。 使用以下代码,可以从每个特征中识别离群值,并计算它们在整个值集中所占的比例:
```py
outliers = {}
......@@ -192,7 +192,7 @@ print("rows:",data.shape[0]," columns:", data.shape[1])
这意味着,鉴于异常值对每个特征的参与度太低,因此不需要采取进一步的措施,因此它们不太可能对最终模型产生影响。
* **Check for class imbalance**: Class imbalance occurs when the class labels in the target feature are not equally represented; for instance, a dataset containing 90% of customers who did not default on the next payment, against 10% of customers who did, is considered to be imbalanced.
* **检查类不平衡**:当目标要素中的类标签未均等表示时,发生类不平衡; 例如,一个数据集包含90%的未拖欠下次付款的客户,而10%的客户未拖欠下一次付款,则被认为是不平衡的。
有几种处理类不平衡的方法,其中一些方法在这里说明:
......@@ -254,7 +254,7 @@ print("rows:",data.shape[0]," columns:", data.shape[1])
使用新创建的数据集,可以再次计算整个数据集中目标要素中每个类标签的参与度,这现在应该反映出具有相同参与度的两个类标签的均等表示的数据集。 此时,数据集的最终形状应等于(46728,23)。
* **Split features from target**: We split the dataset into a features matrix and a target matrix to avoid rescaling the target values:
* **从目标拆分特征**:我们将数据集拆分为要素矩阵和目标矩阵,以避免重新调整目标值:
```py
data_resampled = data_resampled.reset_index(drop=True)
......@@ -262,7 +262,7 @@ print("rows:",data.shape[0]," columns:", data.shape[1])
y = data_resampled ["default payment next month"]
```
* **Rescaling the data**: Finally, we rescale the values of the features matrix in order to avoid introducing bias to the model:
* **重新缩放数据**:最后,我们重新缩放要素矩阵的值,以避免对模型造成偏差:
```py
X = (X - X.min())/(X.max() - X.min())
......@@ -321,7 +321,7 @@ final_data.to_csv("dccc_prepared.csv", index=False)
考虑到所有这些,将解释以下一组惯例和经验法则,以帮助决策过程定义 ANN 的初始架构:
* **输入层**:这很简单; 只有一个输入层,其单位数量取决于训练数据的形状。 具体来说,输入层中的单位数应等于输入数据包含的要素数。
* **Hidden layer**: Hidden layers can vary in quantity. ANNs can have one hidden layer, more, or none. To choose the right number, it is important to consider the following:
* **隐藏层**:隐藏层的数量可能有所不同。 ANN可以有一个隐藏层,也可以没有,也可以没有。 要选择正确的号码,请考虑以下几点:
数据问题越简单,所需的隐藏层就越少。 请记住,线性可分离的简单数据问题应该只有一个隐藏层。 另一方面,可以并且应该使用许多隐藏层(没有限制)解决更复杂的数据问题。
......@@ -378,7 +378,7 @@ class Classifier(torch.nn.Module):
使用前面解释的理论,我们将使用定制模块的语法定义模型的架构:
1. Open a Jupyter Notebook and import the required libraries:
1. 打开Jupyter 笔记本并导入所需的库:
```py
import torch
......@@ -386,7 +386,7 @@ class Classifier(torch.nn.Module):
import torch.nn.functional as F
```
2. Define the necessary variables for the input, hidden, and output dimensions. Set them to`10`,`5`, and`2`, respectively:
2. 定义输入,隐藏和输出尺寸的必要变量。 将它们分别设置为`10``5``2`
```py
D_i = 10
......@@ -394,7 +394,7 @@ class Classifier(torch.nn.Module):
D_o = 2
```
3. Using PyTorch's custom modules, create a class called **Classifier** and define the model's architecture so that it has two linear layers—the first one followed by a **ReLU** activation function, and the second one by a **Softmax** activation function:
3. 使用PyTorch的自定义模块,创建一个名为`Classifier`的类并定义模型的体系结构,使其具有两个线性层-第一个层是 **ReLU** 激活函数,第二层是 **Softmax** 激活功能:
```py
class Classifier(torch.nn.Module):
......@@ -408,7 +408,7 @@ class Classifier(torch.nn.Module):
        return o
```
4. Instantiate the class and feed it with the three variables we created in *Step 2*. Print the model:
4. 实例化该类,并将我们在“步骤 2”中创建的三个变量输入该类。打印模型。
```py
model = Classifier(D_i, D_h, D_o)
......@@ -462,7 +462,7 @@ batch_size = 100
2. 通过比较上一步的预测值和训练集的标签(真实情况)来计算损失。
3. 将梯度设置为零并针对当前步骤再次计算。
4. 网络的参数基于梯度进行更新。
5. The accuracy of the model over the training data is calculated as follows:
5. 该模型对训练数据的准确性计算如下:
获取模型预测的指数,以便获得属于每个类标签的给定数据片段的概率。
......@@ -474,7 +474,7 @@ batch_size = 100
1. 该模型对验证集中的数据执行预测。
2. 通过将先前的预测与验证集中的标签进行比较来计算损失函数。
3. The accuracy is calculated over the validation set. To calculate the accuracy of the model over the validation set, use the same set of steps that you did for the same calculation over the training data:
3. 准确性是根据验证集计算得出的。 要在验证集上计算模型的准确性,请使用对训练数据进行相同计算所用的同一组步骤:
注意
......@@ -533,7 +533,7 @@ batch_size = 100
让我们看一下以下情况:您在一家数据科学精品店工作,该精品店专门为世界各地的银行提供机器/深度学习解决方案。 他们最近为一家银行开展了一个项目,该项目希望能够预测下个月将收到或将不会收到的款项。 探索性数据分析团队已经为您准备了数据集,他们已要求您构建模型并计算模型的准确率。 请按照以下步骤完成此活动:
1. Import the following libraries:
1. 导入以下库:
```py
import pandas as pd
......@@ -557,7 +557,7 @@ batch_size = 100
5. 考虑到要素矩阵应为浮点型,而目标矩阵则应为非浮点型,将验证和测试集转换为张量。 目前暂时不要转换训练集,因为它们将进行进一步的转换。
6. 构建用于定义网络层的自定义模块类。 包括一个前向功能,该功能指定将应用于每层输出的激活函数。 对于除输出之外的所有层,请使用 **ReLU**,在此处应使用`log_softmax`
7. 实例化模型并定义训练模型所需的所有变量。 将时期数设置为`50`,并将批大小设置为`128`。 使用`0.001`的学习率。
8. Train the network using the training set's data. Use the validation sets to measure performance. To do this, save the loss and the accuracy for both the training and validation sets in each epoch.
8. 使用训练集的数据训练网络。 使用验证集来衡量性能。 为此,请保存每个时期中训练集和验证集的损失和准确性。
注意
......@@ -595,7 +595,7 @@ batch_size = 100
执行错误分析的过程如下:
1. 计算选择的度量标准以衡量模型的性能。 应该在训练和验证数据集上计算该度量。
2. Using this measure, calculate the error rate of each of the sets by subtracting the performance metric that was previously calculated from 1\. Take, for instance, the following equation:
2. 使用此度量,通过减去以前从 1 中计算出的性能指标来计算每个集合的错误率。以下面的等式为例:
![Figure 3.9: The equation to calculate the error rate of the model over the training set ](img/B15778_03_09.jpg)
......@@ -603,7 +603,7 @@ batch_size = 100
3. 从训练集误差`A)`中减去贝叶斯误差。 保存差异,将用于进一步分析。
4. 从验证集错误`B)`中减去训练集错误,并保存差值。
5. Take the differences calculated in Steps 3 and 4 and use the following set of rules:
5. 取步骤3和步骤4中计算出的差值,并使用以下一组规则。
如果在“步骤 3”中计算出的差大于在“步骤 4”中计算出的差,则该模型不适合,也称为遭受高偏差。
......@@ -617,11 +617,11 @@ batch_size = 100
让我们解释一下如何处理这些问题:
* **High bias**: An underfitted model, or a model suffering from high bias, is a model that is not capable of understanding the training data, and, hence, it is not able to uncover patterns and generalize with other sets of data. This means that the model does not perform well over any set of data.
* **高偏差**:拟合不足的模型或遭受高偏差的模型是无法理解训练数据的模型,因此无法发现模式并不能与其他数据集进行概括 。 这意味着该模型在任何数据集上的表现都不理想。
为了减少影响模型的高偏差,建议您定义一个更大/更深的网络(更多隐藏层)或训练更多迭代。 通过添加更多的层并增加训练时间,网络将拥有更多资源来发现描述训练数据的模式。
* **High variance**: An overfitted model, or a model suffering from high variance, is a model that is having trouble generalizing the training data; it is learning the details of the training data too well (this means that through the training process, the model learned the information from the training set too well, which means that it is unable to generalize to other sets of data), including its outliers. This means that the model is performing too well over the training data, but poorly over other sets of data.
* **高方差**:过拟合模型或遭受高方差的模型是难以归纳训练数据的模型; 太好地学习了训练数据的细节(这意味着通过训练过程,模型从训练集中学习的信息也太好了,这意味着它无法推广到其他数据集),包括其异常值 。 这意味着该模型在训练数据上的表现很好,但在其他数据集上的表现却很差。
通常可以通过将更多数据添加到训练集中,或通过将正则项添加到损失函数来解决此问题。 第一种方法旨在迫使网络将数据概括化,而不是理解少量示例的细节。 另一方面,第二种方法对权重较高的输入进行惩罚,以忽略异常值,并平等地考虑所有值。
......@@ -639,7 +639,7 @@ batch_size = 100
该练习不需要进行任何编码,而是需要对先前活动的结果进行分析。
1. Assuming a Bayes error of`0.15`, perform error analysis and diagnose the model:
1. 假设贝叶斯误差为0.15,执行误差分析并诊断模型:
```py
Bayes error (BE) = 0.15
......@@ -656,7 +656,7 @@ batch_size = 100
据此,该模型存在高偏差,这意味着该模型不适合。
2. Determine the actions necessary to improve the accuracy of the model.
2. 确定提高模型准确性所需的操作。
为了提高模型的性能,可以遵循的两个操作过程是增加时期数并增加隐藏层数和/或单元数(每层中的神经元)。
......@@ -674,7 +674,7 @@ batch_size = 100
1. 导入与上一个活动相同的库。
2. 加载数据并从目标拆分要素。 接下来,使用 60:20:20 的分割比例将数据分割为三个子集(训练,验证和测试)。 最后,将验证和测试集转换为 PyTorch 张量,就像在上一个活动中一样。
3. Considering that the model is suffering from a high bias, the focus should be on increasing the number of epochs or increasing the size of the network by adding additional layers or units to each layer. The aim should be to approximate the accuracy over the testing set to 80%.
3. 考虑到该模型存在较高的偏差,因此重点应放在通过向每个层添加其他层或单元来增加时期数或网络规模。 目的应该是将测试范围内的准确度近似为80%。
注意
......@@ -707,7 +707,7 @@ batch_size = 100
此处提供了有关如何保存和加载经过训练的模型的分步指南:
1. Originally, a checkpoint of a model will only include the model's parameters. However, when loading the model, this is not the only information that's required. Depending on the arguments that your classifier takes in (that is, the class containing the network architecture), it may be necessary to save further information, such as the number of **input** units. Considering this, the first step is to define the information to be saved:
1. 最初,模型的检查点将仅包含模型的参数。 但是,在加载模型时,这不是唯一需要的信息。 根据分类器采用的参数(即包含网络体系结构的类),可能有必要保存更多信息,例如** input **单元的数量。 考虑到这一点,第一步是定义要保存的信息:
```py
checkpoint = {"input": X_train.shape[1], \
......@@ -716,7 +716,7 @@ batch_size = 100
这会将输入层中的单位数保存到检查点中,这在加载模型时会派上用场。
2. Save the model using PyTorch's **save()** function:
2. 使用 PyTorch 的`save()`函数保存模型。
```py
torch.save(checkpoint, "checkpoint.pth")
......@@ -725,7 +725,7 @@ batch_size = 100
第一个参数指的是我们之前创建的字典,第二个参数是要使用的文件名。
3. 使用您选择的文本编辑器,创建一个 Python 文件,该文件导入 PyTorch 库并包含创建模型的网络架构的类。 这样做是为了使您可以方便地将模型加载到新的工作表中,而无需使用用于训练模型的工作表。
4. To load the model, let's create a function that will perform three main actions:
4. 要加载模型,让我们创建一个函数,它将执行三个主要操作。
```py
def load_model_checkpoint(path):
......@@ -772,7 +772,7 @@ prediction = traced_script(input)
关键术语解释如下:
* **Hypertext Transfer Protocol** (**HTTP**): This is the primary means of transferring data on the web. It works using **methods**, which help to determine the way in which data is transferred. The two most commonly used methods are explained as follows:
* **超文本传输协议****HTTP**):这是在网络上传输数据的主要方式。 它使用**方法**来运作,这有助于确定数据传输的方式。 两种最常用的方法解释如下:
`POST`:此方法允许您将消息中的数据从客户端(正在向 API 发出请求的 Web 浏览器或平台)发送到服务器(使用该信息运行的程序) 身体。
......@@ -782,7 +782,7 @@ prediction = traced_script(input)
要使用 Flask 创建简单的 Web API,请执行以下步骤:
1. Import the necessary libraries:
1. 导入必要的库:
```py
import flask
......@@ -791,7 +791,7 @@ prediction = traced_script(input)
import final_model
```
2. Initialize the Flask app:
2. 初始化Flask应用程序:
```py
app = flask.Flask(__name__)
......@@ -800,7 +800,7 @@ prediction = traced_script(input)
`DEBUG`配置在开发期间设置为`True`,但在生产中应设置为`False`。
3. Load a previously trained model:
3. 加载之前训练的模型。
```py
def load_model_checkpoint(path):
......@@ -811,13 +811,13 @@ prediction = traced_script(input)
model = load_model_checkpoint("checkpoint.pth
```
4. Define the route where the API will be accessible, as well as the method(s) that can be used for sending information to the API in order to perform an action. This syntax is called a decorator and should be located immediately before a function:
4. 定义可访问API的路径,以及可用于向API发送信息以执行操作的方法。 该语法称为装饰器,应位于函数之前:
```py
@app.route('/prediction', methods=['POST'])
```
5. Define a function that performs the desired action. In this case, the function will take the information that was sent to the API and feed it to the previously loaded model to perform a prediction. Once the prediction has been obtained, the function should return a response, which will be displayed as the result of the API request:
5. 定义一个执行所需动作的函数。在这种情况下,该函数将获取发送到API的信息,并将其反馈给之前加载的模型,以执行预测。一旦获得预测,该函数应返回一个响应,该响应将作为API请求的结果显示。
```py
def prediction():
......@@ -830,7 +830,7 @@ prediction = traced_script(input)
    return {"status":"ok", "result":int(top_class_test[0][0])}
```
6. Run the Flask app. The following command makes it possible to start making use of the web API:
6. 运行Flask应用。以下命令可以开始使用Web API。
```py
app.run(debug=True, use_reloader=False)
......@@ -842,21 +842,21 @@ prediction = traced_script(input)
使用 Flask,我们将创建一个 Web API,该 Web API 会在调用时接收一些数据,并返回一段显示在浏览器中的文本。 请按照以下步骤完成此练习:
1. In a Jupyter Notebook, import the required libraries:
1. 在Jupyter 笔记本中,导入所需的库。
```py
import flask
from flask import request
```
2. Initialize the Flask app:
2. 初始化Flask应用。
```py
app = flask.Flask(__name__)
app.config["DEBUG"] = True
```
3. Define the route of your API so that it's **/<name>**. Set the method to **GET**. Next, define a function that takes in an argument (**name**) and returns a string that contains an **h1** tag with the word **HELLO**, followed by the argument received by the function:
3. 定义API的路由,使其为`/<name>`。将方法设置为`GET`。接下来,定义一个函数,该函数接收一个参数(`name`)并返回一个字符串,该字符串包含一个`h1`标签,其中有`HELLO`字样,后面是函数接收的参数。
```py
@app.route('/<name>', methods=['GET'])
......@@ -864,7 +864,7 @@ prediction = traced_script(input)
    return "<h1>HELLO {}</h1>".format(name.upper())
```
4. Run the Flask app:
4. 运行Flask应用。
```py
app.run(debug=True, use_reloader=False)
......@@ -882,7 +882,7 @@ prediction = traced_script(input)
http://127.0.0.1:5000/
```
5. Copy the URL into a browser, followed by your name, as follows:
5. 将网址复制到浏览器中,后面加上你的名字,如下。
```py
http://127.0.0.1:5000/your_name
......@@ -916,7 +916,7 @@ prediction = traced_script(input)
4. 打开一个新的 Jupyter 笔记本。
5. 导入 PyTorch 以及我们在“步骤 2”中创建的 Python 文件。
6. 创建一个加载模型的函数。
7. Perform a prediction by inputting the following tensor into your model:
7. 通过将以下张量输入到你的模型中进行预测。
```py
torch.tensor([[0.0606, 0.5000, 0.3333, 0.4828, 0.4000, \
......
......@@ -361,11 +361,11 @@ Mean of highpass_waveform: 1.8138147234170177e-11
用户可能熟悉 [Kaldi](http://github.com/kaldi-asr/kaldi) (一种用于语音识别的工具包)。 `torchaudio`提供与`torchaudio.kaldi_io`中的兼容性。 实际上,它可以通过以下方式从 kaldi scp 或 ark 文件或流中读取:
* read_vec_int_ark
* read_vec_flt_scp
* read_vec_flt_arkfile /流
* read_mat_scp
* read_mat_ark
* `read_vec_int_ark`
* `read_vec_flt_scp`
* `read_vec_flt_arkfile`/流
* `read_mat_scp`
* `read_mat_ark`
`torchaudio``spectrogram``fbank``mfcc`[提供 Kaldi 兼容的转换。](#id2) resample_waveform 受益于 GPU 支持,有关更多信息,请参见[在此处](compliance.kaldi.html)
......
......@@ -309,7 +309,7 @@ def allreduce(send, recv):
如您所知,如果在 GPU 上放置`model`,我们的分布式 SGD 示例将无法正常工作。 为了使用多个 GPU,让我们还进行以下修改:
1. 使用`device = torch.device("cuda:{}".format(rank))`
2. `model = Net()` \(\ rightarrow \)`model = Net().to(device)`
2. `model = Net() => model = Net().to(device)`
3. 使用`data, target = data.to(device), target.to(device)`
经过上述修改,我们的模型现在可以在两个 GPU 上训练,您可以使用`watch nvidia-smi`监视其使用情况。
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册