工具:
Anaconda激活深度学习的命令:
Deep learning介绍
线性回归 (Linear Regression)
y=ax+b, a is slope(斜率), b is intercept(截距)
逻辑回归(Logistic Regression)
y = f(ax+b), f是激活函数(Activation Function)
Perceptron(感知机)
感知机公式:

w称为权重,b称为偏好,f为激活函数
人工神经网络(Artificial Neural Network, ANN)
向量:ANN中的数据一般会用向量表示
采样,目标,特性:ANN中的一组数据称为采样,这个概念应该来自统计学。采样中,通常有一维数据是我们关注的最终结果,这一维称为目标。其余维度的数据称为特性。即可以理解为:在一组采样中,多个特性数据对应一个目标数据。
输入层
输入预处理
特性需要被转化为数字表示
| 输出类型 | 所需的处理 |
| 数字的 | 中心化和定标(centering and scaling) |
| 类别的 | 整数编码(integer encoding),独热编码(one-hot encoding) |
| 文本 | TF-IDF(词频-逆文本频率),嵌入(embedding) |
| 图像 | 像素-RGB表示(Pixels-RGB representation) |
| 语音 | 数字的时间序列(Time series of numbers) |
隐藏层
输入层和输出层中间的层都称为隐藏层
权重和偏好
计算权重和偏好的个数:如果前一层的结点数为A,当前层的结点数为B,则这两层之间的权重个数为:A * B;偏好个数为B。
激活函数
流行的激活函数
| 激活函数 | 输出 |
| Sigmoid | 0~1 |
| Tanh | -1~1 |
| Rectified Linear Unit(ReLU) | 0当x <0; 否则为x |
| Softmax | 概率向量,其和为1 |
输出层
初始化
数据被分为训练(Training),测试(Test),验证(Validation)三类
权重(weights)和偏好(bias)
方法:
前向传播(forward propagation)
预测值(Predication, y hat)是通过前向传播得到的

测量精确度和误差
损失和成本函数
成本函数
| 成本函数 | 应用 |
| 均方差(MSE) | 回归 |
| 根均方差(RMSE) | 回归 |
| 二进制交叉熵(Binary Cross Entropy) | 二分类 |
| 范畴交叉熵(Categorical Cross Entropy) | 多分类 |
怎样测量精确度
反向传播(Back Propagation)
反向传播怎样工作

梯度下降(Gradient Descent)
在前面的模型中,通过不断地循环,使得权重和偏好被不断地优化,误差不断地减小,这个过程称为梯度下降。即不断重复下面的步骤:
会存在误差停止减少的情况,此时会有一些额外的超参数(Hyper Parameters)用于这种情况,超参数也可以用于加速或减速这个过程。
批和期(Batches and Epoch)
什么是批(Batch)
批的大小
什么是期
注意:批的大小和期的大小都是超参数,可以通过调整来优化训练过程
例子:训练集中总共有1000个采样,批的大小为128,期的大小为50。请问期是多少?训练过程总共循环几次?
- 期: ceiling(1000/128) = 8
- 循环次数:8 * 50 = 400
验证和测试(Validation and Testing)
一个ANN模型
ANN模型是由一些参数表示的:
ANN模型也由一些超参数表示的:
预测过程
重用已有的网络架构
大多数神经网络(NN)并非是从零开始创建的(created from scratch)。设计一个具有合适的层数和结点的NN是一个乏味的、重复的、耗时的过程。社区共享了很多知识和经验,可以拿来使用。
流行的网络架构:
使用可用的开源模型
开源模型
选择开源模型
示例项目:Iris data set
Iris flower数据集是一个经典的用于分类问题的数据集,详见以下链接:
https://en.wikipedia.org/wiki/Iris_flower_data_set
由于sklearn提供了load_iris(),因此我们使用这个方法直接导入Iris数据集。
运行环境:google notebook(用法见初识Google Colab Jupyter Notebook),程序如下:
1. 加载数据和预处理
- import pandas as pd
- import os
- import tensorflow as tf
- import numpy as np
- from sklearn.model_selection import train_test_split
- from sklearn.preprocessing import StandardScaler
- from sklearn.datasets import load_iris
-
- #Number of data to show
- NB_TO_SHOW=5
-
- # Use load_iris in sklearn to load Iris Flower Data Set directly
- iris_data = load_iris()
- print("\nLoaded Data:\n-------------------------------")
- print(iris_data.data.shape)
-
- #from sklearn import preprocessing
- #label_encoder = preprocessing.LabelEncoder()
-
- # Separate feature and target variables
- X_data = iris_data.data
- Y_data = iris_data.target
- print("\nFeatures before scaling:\n-------------------------------")
- print(X_data[0:NB_TO_SHOW])
- print("\nTarget before scaling:\n-------------------------------")
- print(Y_data[0:NB_TO_SHOW])
-
- # Create a scaler model that is fit on the input data
- scaler = StandardScaler().fit(X_data)
-
- # Scale the numeric feature variables
- X_data = scaler.transform(X_data)
-
- # Convert target variable as a one-hot-encoding array
- Y_data = tf.keras.utils.to_categorical(Y_data, 3)
-
- print("\nFeatures after scaling:\n-------------------------------")
- print(X_data[0:NB_TO_SHOW])
- print("\nTarget after scaling:\n-------------------------------")
- print(Y_data[0:NB_TO_SHOW])
-
- # Split the training and test data
- X_train,X_test,Y_train,Y_test = train_test_split(X_data, Y_data, test_size=0.10)
- print(X_train.shape, Y_train.shape, X_test.shape, Y_test.shape)
2. 创建模型
- from tensorflow import keras
-
- NB_CLASSES=3
-
- #Create a sequential model in Keras
- model = keras.models.Sequential()
-
- #Add the first hidden layer
- model.add(keras.layers.Dense(128, #Number of nodes
- input_shape=(4,), #Number of input variables
- name="Hidden-Layer-1", #Logical name
- activation='relu')) #activation function
-
- #Add the second hidden layer
- model.add(keras.layers.Dense(128, #Number of nodes
- name="Hidden-Layer-2", #Logical name
- activation='relu')) #activation function
-
- #Add an output layer with softmax
- model.add(keras.layers.Dense(NB_CLASSES, #Number of nodes
- name="Output-Layer", #Logical name
- activation='softmax')) #activation function
-
- #Compile the model with loss & metrics
- model.compile(loss='categorical_crossentropy',
- metrics=['accuracy'])
-
- #Print the model meta-data
- model.summary()
3. 训练模型
- # Make it verbose so we can see the progress
- VERBOSE=1
-
- # Setup Hyper Parameters for training
-
- # Set Batch size
- BATCH_SIZE=16
- # Set number of epochs
- EPOCHS=10
- # Set validataion split. 20% of the training data will be used for validation
- # after each epoch
- VALIDATION_SPLIT=0.2
-
- print("\nTraining Progress:\n-------------------------------")
-
- # Fit the model.
- history=model.fit(X_train,
- Y_train,
- batch_size=BATCH_SIZE,
- epochs=EPOCHS,
- verbose=VERBOSE,
- validation_split=VALIDATION_SPLIT)
-
- print("\nAccuracy during Training:\n-------------------------------")
- import matplotlib.pyplot as plt
-
- # Plot accuracy of the model after each epoch
- pd.DataFrame(history.history)["accuracy"].plot(figsize=(8,5))
- plt.title("Accuracy improvements with Epoch")
- plt.show()
-
- # Evaluate the model
- print("\nEvalulation against Test Dataset:\n-------------------------------")
- model.evaluate(X_test, Y_test)
4. 保存模型
使用google notebook,不需要保存模型;如果自己安装Jupyter Notebook,可以保存这个模型到本地。
- # Saveing a model
- #model.save("iris_save")
-
- # Loading a Model
- #loaded_model = keras.models.load_model("iris_save")
-
- # Print Model Summary
- #loaded_model.summary()
5. 使用训练好的模型预测新数据
- # Raw prediction data
- prediction_input=[[6.6, 3, 4.4, 1.4]]
-
- #Scale prediction data with the same scaling model
- scaled_input = scaler.transform(prediction_input)
-
- # Get raw prediction probabilities
- raw_prediction = model.predict(scaled_input)
- print("Raw Prediction Output (Probabilities): ", raw_prediction)
-
- # Find prediction
- prediction = np.argmax(raw_prediction)
- #print("Prediction is ", label_encoder.inverse_transform([prediction]))
- print("Prediction is: ", iris_data.target_names[prediction])