1、机器学习、深度学习简介
上面这张图形象的表达了机器学习与深度学习的关系,机器学习是实现人工智能的方法,深度学习是实现机器学习算法的技术。
机器学习是将无序数据转化为价值的方法,机器学习的价值是从数据中抽取规律,并用来预测未来。
2、神经元-logistic回归模型
神经元是最小的神经网络,如下图所示
计算方法举例:(未考虑偏置b)
偏置b的物理含义(截距):
3、神经元多输出
由2的基础,现在讨论神经元的多输出情况:
计算举例说明:(未考虑偏置b)
4、目标函数
目标函数就是损失函数,它用来衡量对数据的拟合程度。
常用目标函数有两种:平方差损失函数与交叉熵损失函数,公式如下:
神经网络的训练过程就是:调整参数使模型在训练集上的损失函数最小的过程。
5、梯度下降
是找到的“下山”的方向
α是沿着方向走的“那一步”的大小
下面介绍学习率α过大或过小对神经网络训练的影响:
如果α过小,如图所示,它可能需要很长时间的迭代才可能达到最优值
如果α过大,则可能永远在最优值周围“徘徊”而无法取到最优值
1、Minni-Batch存在震荡问题:由于随机采样不够多,可能存在震荡问题,这个问题在单个样本上会反应更明显,Minni-Batch的size越大,这个问题就越不明显。
2、局部极值问题:目标函数可能存在多个最优解。如果Learning-rate太小,会导致整个参数停在局部极值点的位置。鞍点,导数为0,参数变化为0,无论采用全部数据集,还是mini-batch还是一个样本都会存在这种问题。
为了解决刚才提出的这两个问题,提出动量梯度下降的算法。
核心:积累值与当前梯度的加法。不仅体现在大小上,还体现在方向上。
6、神经元的Tensorflow1.14.0实现
数据集:cifar10
网址:https://xilesou.hk.gg363.site/search?q=cifar10+download
下载Python版本的数据集
代码:
import tensorflow as tf
import os
import pickle
import numpy as np
CIFAR_DIR = "./cifar-10-batches-py"
print(os.listdir(CIFAR_DIR))
physical_devices = tf.config.experimental.list_physical_devices('GPU')
assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
tf.config.experimental.set_memory_growth(physical_devices[0], True)
def load_data(filename):
"""read data from data file."""
with open(filename, 'rb') as f:
data = pickle.load(f, encoding='bytes')
return data[b'data'], data[b'labels']
# tensorflow.Dataset.
class CifarData:
def __init__(self, filenames, need_shuffle):
all_data = []
all_labels = []
for filename in filenames:
data, labels = load_data(filename)
for item, label in zip(data, labels):
if label in [0, 1]:
all_data.append(item)
all_labels.append(label)
self._data = np.vstack(all_data) #将numpy向量纵向合并在一起,形成矩阵。
self._data = self._data / 127.5 - 1 #[-1,1]之间的数,相当于做一个归一化。
self._labels = np.hstack(all_labels)#横向合并,一维向量
print(self._data.shape)
print(self._labels.shape)
self._num_examples = self._data.shape[0] #有多少个example
print(self._num_examples)
self._need_shuffle = need_shuffle
self._indicator = 0 #记录数据集遍历到那个位置上了
if self._need_shuffle:
self._shuffle_data()
def _shuffle_data(self):
# [0,1,2,3,4,5] -> [5,3,2,4,0,1]
p = np.random.permutation(self._num_examples)
self._data = self._data[p]
self._labels = self._labels[p]
def next_batch(self, batch_size):
"""return batch_size examples as a batch."""
end_indicator = self._indicator + batch_size
if end_indicator > self._num_examples:
if self._need_shuffle:
self._shuffle_data()
self._indicator = 0
end_indicator = batch_size
else:
raise Exception("have no more examples")
if end_indicator > self._num_examples:
raise Exception("batch size is larger than all examples")
batch_data = self._data[self._indicator: end_indicator]
batch_labels = self._labels[self._indicator: end_indicator]
self._indicator = end_indicator
return batch_data, batch_labels
train_filenames = [os.path.join(CIFAR_DIR, 'data_batch_%d' % i) for i in range(1, 6)]
test_filenames = [os.path.join(CIFAR_DIR, 'test_batch')]
train_data = CifarData(train_filenames, True)
#test_data = CifarData(test_filenames, False)
x = tf.placeholder(tf.float32, [None, 3072])
# [None], 第一维样本数不确定,为了应对batch_size的可变性。
y = tf.placeholder(tf.int64, [None])
# (3072, 1)
w = tf.get_variable('w', [x.get_shape()[-1], 1],#单个神经元是二分类器
initializer=tf.random_normal_initializer(0, 1))
# (1, )
b = tf.get_variable('b', [1],
initializer=tf.constant_initializer(0.0))
# [None, 3072] * [3072, 1] = [None, 1]
y_ = tf.matmul(x, w) + b
#[None, 1]
p_y_1 = tf.nn.sigmoid(y_) #内积值->概率值,输入到sigmoid中去,得到y=1的概率值。
# y:[None] -> [None, 1]
y_reshaped = tf.reshape(y, (-1, 1))
y_reshaped_float = tf.cast(y_reshaped, tf.float32)
loss = tf.reduce_mean(tf.square(y_reshaped_float - p_y_1))
# bool
predict = p_y_1 > 0.5
# [1,0,1,1,1,0,0,0]
correct_prediction = tf.equal(tf.cast(predict, tf.int64), y_reshaped)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))
with tf.name_scope('train_op'):
train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)
init = tf.global_variables_initializer()
#初始化变量
batch_size = 20
train_steps = 100000
test_steps = 100
#打开一个会话,可以执行计算图。
with tf.Session() as sess:
sess.run(init)
for i in range(train_steps):
batch_data, batch_labels = train_data.next_batch(batch_size)
loss_val, acc_val, _ = sess.run(
[loss, accuracy, train_op],
feed_dict={
x: batch_data,
y: batch_labels})
if (i+1) % 500 == 0:
print('[Train] Step: %d, loss: %4.5f, acc: %4.5f' % (i+1, loss_val, acc_val))
if (i+1) % 5000 == 0:
test_data = CifarData(test_filenames, False)
all_test_acc_val = []
for j in range(test_steps): #正好完整遍历一次测试集
test_batch_data, test_batch_labels \
= test_data.next_batch(batch_size)
test_acc_val = sess.run(
[accuracy],
feed_dict = {
x: test_batch_data,
y: test_batch_labels
})
all_test_acc_val.append(test_acc_val)
test_acc = np.mean(all_test_acc_val)
print('[Test ] Step: %d, acc: %4.5f' % (i+1, test_acc))
7、神经网络
多层神经元构成了神经网络,如下图是具有一个隐含层的神经网络。
用梯度下降的方式对神经网络进行训练,用损失函数对每一个参数求偏导,再乘以α,用这个结果更新所有的参数,一步一步迭代,得到比较好的神经网络。
求损失函数对各个参数的偏导数,先看最后一层,假设h采用sigmoid激活函数,则图中L为使用了平方差损失函数的损失函数。参数w存在于h21,h22,h23的权重,x是h21,h22,h23的输出 and +1,可以直接求L对w的导数。
8、神经网络(多分类logistic回归模型)的Tensorflow1.14.0实现
多分类是在第6部分的单个神经元二分类代码的基础上修改的。
import tensorflow as tf
import os
import pickle
import numpy as np
CIFAR_DIR = "./cifar-10-batches-py"
print(os.listdir(CIFAR_DIR))
print(tf.__version__)
def load_data(filename):
"""read data from data file."""
with open(filename, 'rb') as f:
data = pickle.load(f, encoding='bytes')
return data[b'data'], data[b'labels']
# tensorflow.Dataset.
class CifarData:
def __init__(self, filenames, need_shuffle):
all_data = []
all_labels = []
for filename in filenames:
data, labels = load_data(filename)
all_data.append(data)
all_labels.append(labels)
self._data = np.vstack(all_data)
self._data = self._data / 127.5 - 1
self._labels = np.hstack(all_labels)
print(self._data.shape)
print(self._labels.shape)
self._num_examples = self._data.shape[0]
self._need_shuffle = need_shuffle
self._indicator = 0
if self._need_shuffle:
self._shuffle_data()
def _shuffle_data(self):
# [0,1,2,3,4,5] -> [5,3,2,4,0,1]
p = np.random.permutation(self._num_examples)
self._data = self._data[p]
self._labels = self._labels[p]
def next_batch(self, batch_size):
"""return batch_size examples as a batch."""
end_indicator = self._indicator + batch_size
if end_indicator > self._num_examples:
if self._need_shuffle:
self._shuffle_data()
self._indicator = 0
end_indicator = batch_size
else:
raise Exception("have no more examples")
if end_indicator > self._num_examples:
raise Exception("batch size is larger than all examples")
batch_data = self._data[self._indicator: end_indicator]
batch_labels = self._labels[self._indicator: end_indicator]
self._indicator = end_indicator
return batch_data, batch_labels
train_filenames = [os.path.join(CIFAR_DIR, 'data_batch_%d' % i) for i in range(1, 6)]
test_filenames = [os.path.join(CIFAR_DIR, 'test_batch')]
train_data = CifarData(train_filenames, True)
test_data = CifarData(test_filenames, False)
x = tf.placeholder(tf.float32, [None, 3072])
# [None], eg: [0,5,6,3]
y = tf.placeholder(tf.int64, [None])
# (3072, 10)
w = tf.get_variable('w', [x.get_shape()[-1], 10], #10个神经元,没有隐含层的神经网络
initializer=tf.random_normal_initializer(0, 1))
# (10, )
b = tf.get_variable('b', [10],
initializer=tf.constant_initializer(0.0))
# [None, 3072] * [3072, 10] = [None, 10]
y_ = tf.matmul(x, w) + b
# mean square loss
"""
# course: 1 + e^x
# api: e^x / sum(e^x)
# [[0.01, 0.9, ..., 0.03], []]
p_y = tf.nn.softmax(y_)
# 5 -> [0,0,0,0,0,1,0,0,0,0]
y_one_hot = tf.one_hot(y, 10, dtype=tf.float32)
loss = tf.reduce_mean(tf.square(y_one_hot - p_y))
"""
loss = tf.losses.sparse_softmax_cross_entropy(labels=y, logits=y_)
# y_ -> sofmax
# y -> one_hot
# loss = ylogy_
# indices
predict = tf.argmax(y_, 1)#对每个样本求最大值
# [1,0,1,1,1,0,0,0]
correct_prediction = tf.equal(predict, y)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float64))
with tf.name_scope('train_op'):
train_op = tf.train.AdamOptimizer(1e-3).minimize(loss)
init = tf.global_variables_initializer()
batch_size = 20
train_steps = 100000
test_steps = 100
# run 100k: 30.95%
with tf.Session() as sess:
sess.run(init)
for i in range(train_steps):
batch_data, batch_labels = train_data.next_batch(batch_size)
loss_val, acc_val, _ = sess.run(
[loss, accuracy, train_op],
feed_dict={
x: batch_data,
y: batch_labels})
if (i+1) % 500 == 0:
print('[Train] Step: %d, loss: %4.5f, acc: %4.5f'
% (i+1, loss_val, acc_val))
if (i+1) % 5000 == 0:
test_data = CifarData(test_filenames, False)
all_test_acc_val = []
for j in range(test_steps):
test_batch_data, test_batch_labels \
= test_data.next_batch(batch_size)
test_acc_val = sess.run(
[accuracy],
feed_dict = {
x: test_batch_data,
y: test_batch_labels
})
all_test_acc_val.append(test_acc_val)
test_acc = np.mean(all_test_acc_val)
print('[Test ] Step: %d, acc: %4.5f' % (i+1, test_acc))
TF2.0(多分类):
import matplotlib as mpl
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
import sklearn
import pandas as pd
import pickle
import os
import sys
import time
import tensorflow as tf
from tensorflow import keras
print(tf.__version__)
print(sys.version_info)
for module in mpl, np, pd, sklearn, tf, keras:
print(module.__name__, module.__version__)
physical_devices = tf.config.experimental.list_physical_devices('GPU')
assert len(physical_devices) > 0, "Not enough GPU hardware devices available"
tf.config.experimental.set_memory_growth(physical_devices[0], True)
def load_data(filename):
"""read data from data file."""
with open(filename, 'rb') as f:
data = pickle.load(f, encoding='bytes')
return data[b'data'], data[b'labels']
CIFAR_DIR = "./cifar-10-batches-py"
train_all_data = []
train_all_labels = []
train_filenames = [os.path.join(CIFAR_DIR, 'data_batch_%d' % i) for i in range(1, 6)]
for train_filename in train_filenames:
data, labels = load_data(train_filename)
train_all_data.append(data)
train_all_labels.append(labels)
train_data = np.vstack(train_all_data)
train_labels = np.hstack(train_all_labels)
test_filenames = os.path.join(CIFAR_DIR, 'test_batch')
test_data, test_labels = load_data(test_filenames)
test_labels = np.array(test_labels)
print(train_data.shape)
print(train_labels.shape)
print(test_data.shape)
print(test_labels.shape)
#数据归一化
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
x_train_scaled = scaler.fit_transform(train_data)
x_valid_scaled = scaler.transform(test_data)
model = keras.models.Sequential()
model.add(keras.layers.Dense(10, activation = "softmax"))
model.compile(loss = "sparse_categorical_crossentropy",
optimizer = "sgd",
metrics = ["accuracy"])
history = model.fit(x_train_scaled,train_labels,epochs = 10,
validation_data = (x_valid_scaled, test_labels))
def plot_learning_curves(history):
pd.DataFrame(history.history).plot(figsize=(8, 5))
plt.grid(True)
plt.gca().set_ylim(0, 3)
plt.show()
plot_learning_curves(history)