在深度学习的实施中,我们的目标是预测某个银行的客户流失或流失数据 - 客户可能会离开此银行服务.使用的数据集相对较小,包含10000行,每列14列.我们正在使用Anaconda发行版,以及Theano,TensorFlow和Keras等框架. Keras建立在Tensorflow和Theano之上,作为其后端.
# Artificial Neural Network # Installing Theano pip install --upgrade theano # Installing Tensorflow pip install –upgrade tensorflow # Installing Keras pip install --upgrade keras
In[]: # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the database dataset = pd.read_csv('Churn_Modelling.csv')
我们创建了特征的矩阵数据集和目标变量,即第14列,标记为"已退出".
数据的初始外观如下所示 :
In[]: X = dataset.iloc[:, 3:13].values Y = dataset.iloc[:, 13].values X
Y
array([1,0,1,... ,1,1,0,dtype = int64)
我们通过编码使分析更简单字符串变量.我们使用ScikitLearn函数'LabelEncoder'自动编码列中不同的标签,其值介于0到n_classes-1之间.
from sklearn.preprocessing import LabelEncoder, OneHotEncoder labelencoder_X_1 = LabelEncoder() X[:,1] = labelencoder_X_1.fit_transform(X[:,1]) labelencoder_X_2 = LabelEncoder() X[:, 2] = labelencoder_X_2.fit_transform(X[:, 2]) X
在上面的输出中,国家名称被替换为0,1和2;男性和女性被0和1取代.
标记编码数据
我们使用相同的 ScikitLearn 库和另一个名为 OneHotEncoder 的函数来传递创建虚拟变量的列号.
onehotencoder = OneHotEncoder(categorical features = [1]) X = onehotencoder.fit_transform(X).toarray() X = X[:, 1:] X
现在,前2列代表国家,第4列代表性别.
我们总是划分我们的数据进入培训和测试部分;我们在训练数据上训练模型,然后检查模型在测试数据上的准确性,这有助于评估模型的效率.
我们正在使用ScikitLearn的 train_test_split 函数将我们的数据分成训练集和测试集.我们将列车 - 测试分流比保持在80:20.
#Splitting the dataset into the Training set and the Test Set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)
一些变量具有数千的值,而有些具有数十或数千的值.我们缩放数据以使它们更具代表性.
在此代码中,我们使用<匹配和转换训练数据 StandardScaler 功能.我们标准化我们的缩放比例,以便我们使用相同的拟合方法来转换/缩放测试数据.
# Feature Scaling
fromsklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test)
现在可以正确缩放数据.最后,我们完成了数据预处理.现在,我们将从我们的模型开始.
我们在此处导入所需的模块.我们需要Sequential模块来初始化神经网络和密集模块来添加隐藏层.
# Importing the Keras libraries and packages import keras from keras.models import Sequential from keras.layers import Dense
我们将模型命名为Classifier,因为我们的目标是对客户流失进行分类.然后我们使用Sequential模块进行初始化.
#Initializing Neural Network classifier = Sequential()
我们使用密集函数逐个添加隐藏层.在下面的代码中,我们将看到许多参数.
我们的第一个参数是 output_dim .它是我们添加到该层的节点数. init 是Stochastic Gradient Decent的初始化.在神经网络中,我们为每个节点分配权重.在初始化时,权重应接近零,我们使用统一函数随机初始化权重. input_dim 参数仅适用于第一层,因为模型不知道输入变量的数量.这里输入变量的总数是11.在第二层,模型自动知道第一个隐藏层的输入变量数.
执行以下代码行添加输入图层和第一个隐藏图层 :
classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11))
执行以下代码行添加第二个隐藏图层 :
classifier.add(Dense(units = 6,kernel_initializer ='uniform', activation ='relu'))
执行以下代码行添加输出图层 :
classifier.add(Dense(units = 1,kernel_initializer ='uniform', activation ='sigmoid'))
编译ANN
我们添加了m到目前为止,我们的分类器有多层.我们现在将使用 compile 方法编译它们.在最终编译控件中添加的参数完成了神经网络.因此,我们需要在这一步中小心.
以下是对参数的简要说明.
第一个参数是优化器.这是一种用于查找最佳权重集的算法.该算法称为随机梯度下降(SGD).这里我们使用几种类型中的一种,称为"亚当优化器".新元取决于损失,因此我们的第二个参数是损失.如果我们的因变量是二元的,我们使用称为'binary_crossentropy'的对数损失函数,如果我们的因变量在输出中有两个以上的类别,那么我们使用'categorical_crossentropy' .我们希望基于准确度来提高神经网络的性能,因此我们将指标添加为准确度.
#编译神经网络 classifier.compile(optimizer ='adam',loss ='binary_crossentropy',metrics = ['accuracy'])
在此步骤中需要执行许多代码.
我们现在在训练数据上训练我们的模型.我们使用 fit 方法来拟合我们的模型.我们还优化了重量以提高模型效率.为此,我们必须更新权重. 批量大小是我们更新权重后的观察数量. Epoch 是迭代的总数.批量大小和时期的值通过试错法选择.
classifier.fit(X_train,y_train,batch_size = 10,epochs = 50)
#Predicting测试集结果 y_pred = classifier.predict(X_test) y_pred =(y_pred> 0.5)
# Predicting a single new observation """Our goal is to predict if the customer with the following data will leave the bank: Geography: Spain Credit Score: 500 Gender: Female Age: 40 Tenure: 3 Balance: 50000 Number of Products: 2 Has Credit Card: Yes Is Active Member: Yes
预测测试集结果
预测结果将为您提供客户离开的概率他公司.我们将该概率转换为二进制0和1.
#预测测试集结果 y_pred = classifier.predict(X_test) y_pred =(y_pred> 0.5)
new_prediction = classifier.predict(sc.transform (np.array([[0.0,0,500,1,40,3,500,2,1,1,40000]]))) new_prediction =(new_prediction> 0.5)
这是我们评估模型性能的最后一步.我们已经有了原始结果,因此我们可以构建混淆矩阵来检查模型的准确性.
制作混淆矩阵
from sklearn.metrics import confusion_matrix cm = confusion_matrix(y_test, y_pred) print (cm)
loss: 0.3384 acc: 0.8605 [ [1541 54] [230 175] ]
从混淆矩阵中,我们模型的精度可以计算为 :
Accuracy = 1541+175/2000=0.858
我们达到了85.8%的准确率,这是好的.
在本节中,我们将学习如何编写代码来进行简单神经的前向传播(预测) network :
每个数据点都是客户.第一个输入是他们有多少个帐户,第二个输入是他们有多少个孩子.该模型将预测用户在明年进行的交易数量.
输入数据作为输入数据预先加载,权重在称为权重的字典中.隐藏层中第一个节点的权重数组为权重['node_0'],隐藏层中的第二个节点权重分别为权重['node_1'].
输入到输出节点的权重可用于权重.
"激活函数"是一个有效的函数在每个节点.它将节点的输入转换为某个输出.
经过纠正的线性激活函数(称为 ReLU )广泛用于高性能网络.此函数将一个数字作为输入,如果输入为负,则返回0;如果输入为正,则输入为输出.
以下是一些示例 :
relu(4)= 4
relu(-2)= 0
我们填写relu()函数的定义 :
我们使用max()函数计算relu()输出的值.
我们将relu()函数应用于node_0_input来计算node_0_output.
我们将relu()函数应用于node_1_input以计算node_1_output.
import numpy as np input_data = np.array([-1, 2]) weights = { 'node_0': np.array([3, 3]), 'node_1': np.array([1, 5]), 'output': np.array([2, -1]) } node_0_input = (input_data * weights['node_0']).sum() node_0_output = np.tanh(node_0_input) node_1_input = (input_data * weights['node_1']).sum() node_1_output = np.tanh(node_1_input) hidden_layer_output = np.array(node_0_output, node_1_output) output =(hidden_layer_output * weights['output']).sum() print(output) def relu(input): '''Define your relu activation function here''' # Calculate the value for the output of the relu function: output output = max(input,0) # Return the value just calculated return(output) # Calculate node 0 value: node_0_output node_0_input = (input_data * weights['node_0']).sum() node_0_output = relu(node_0_input) # Calculate node 1 value: node_1_output node_1_input = (input_data * weights['node_1']).sum() node_1_output = relu(node_1_input) # Put node values into array: hidden_layer_outputs hidden_layer_outputs = np.array([node_0_output, node_1_output]) # Calculate model output (do not apply relu) odel_output = (hidden_layer_outputs * weights['output']).sum() print(model_output)# Print model output
0.9950547536867305 -3
在本节中,我们将学习如何定义一个名为predict_with_network()的函数.此函数将生成多个数据观测的预测,从上面的网络中获取input_data.正在使用上述网络中给出的权重.还使用了relu()函数定义.
让我们定义一个名为predict_with_network()的函数,它接受两个参数 - input_data_row和weights - 并从网络返回一个预测作为输出.
我们计算每个节点的输入和输出值,将它们存储为:node_0_input,node_0_output,node_1_input和node_1_output.
计算输入一个节点的值,我们将相关的数组相乘并计算它们的总和.
要计算节点的输出值,我们将relu()函数应用于输入值节点.我们使用'for循环'迭代input_data :
我们还使用predict_with_network()为input_data的每一行生成预测 - input_data_row.我们还将每个预测附加到结果.
# Define predict_with_network() def predict_with_network(input_data_row, weights): # Calculate node 0 value node_0_input = (input_data_row * weights['node_0']).sum() node_0_output = relu(node_0_input) # Calculate node 1 value node_1_input = (input_data_row * weights['node_1']).sum() node_1_output = relu(node_1_input) # Put node values into array: hidden_layer_outputs hidden_layer_outputs = np.array([node_0_output, node_1_output]) # Calculate model output input_to_final_layer = (hidden_layer_outputs*weights['output']).sum() model_output = relu(input_to_final_layer) # Return model output return(model_output) # Create empty list to store prediction results results = [] for input_data_row in input_data: # Append prediction to results results.append(predict_with_network(input_data_row, weights)) print(results)# Print results
[0,12]
这里我们使用relu函数relu( 26)= 26并且relu(-13)= 0等等.
这里我们正在编写代码为具有两个隐藏层的神经网络进行前向传播.每个隐藏层都有两个节点.输入数据已预加载为 input_data .第一个隐藏层中的节点称为node_0_0和node_0_1.
它们的权重分别作为权重['node_0_0']和权重['node_0_1']预先加载.
第二个隐藏层中的节点称为 node_1_0和node_1_1 .它们的权重预先加载为权重['node_1_0'] 和权重['node_1_1'] .
然后我们创建使用预加载为权重['输出'] 的权重从隐藏节点输出模型.
我们使用权重权重['node_0_0']和给定的input_data来计算node_0_0_input.然后应用relu()函数获取node_0_0_output.
我们对node_0_1_input执行与上述相同的操作以获取node_0_1_output.
我们使用其计算node_1_0_input权重['node_1_0']和第一个隐藏层的输出 - hidden_0_outputs.然后我们应用relu()函数来获取node_1_0_output.
我们对node_1_1_input执行与上述相同的操作来获取node_1_1_output.
我们使用re_()计算model_output权重['output']和第二个隐藏层hidden_1_outputs数组的输出.我们不将relu()函数应用于此输出.
import numpy as np input_data = np.array([3, 5]) weights = { 'node_0_0': np.array([2, 4]), 'node_0_1': np.array([4, -5]), 'node_1_0': np.array([-1, 1]), 'node_1_1': np.array([2, 2]), 'output': np.array([2, 7]) } def predict_with_network(input_data): # Calculate node 0 in the first hidden layer node_0_0_input = (input_data * weights['node_0_0']).sum() node_0_0_output = relu(node_0_0_input) # Calculate node 1 in the first hidden layer node_0_1_input = (input_data*weights['node_0_1']).sum() node_0_1_output = relu(node_0_1_input) # Put node values into array: hidden_0_outputs hidden_0_outputs = np.array([node_0_0_output, node_0_1_output]) # Calculate node 0 in the second hidden layer node_1_0_input = (hidden_0_outputs*weights['node_1_0']).sum() node_1_0_output = relu(node_1_0_input) # Calculate node 1 in the second hidden layer node_1_1_input = (hidden_0_outputs*weights['node_1_1']).sum() node_1_1_output = relu(node_1_1_input) # Put node values into array: hidden_1_outputs hidden_1_outputs = np.array([node_1_0_output, node_1_1_output]) # Calculate model output: model_output model_output = (hidden_1_outputs*weights['output']).sum() # Return model_output return(model_output) output = predict_with_network(input_data) print(output)
364