9.8-over-fitting-and-under-fitting.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. """
  4. @author: HuRuiFeng
  5. @file: 9.8-over-fitting-and-under-fitting.py
  6. @time: 2020/2/25 21:14
  7. @desc: 9.8 过拟合问题实战的代码
  8. from mpl_toolkits.mplot3d import Axes3D 这个必须添加,解决3d报错问题
  9. """
  10. import matplotlib.pyplot as plt
  11. # 导入数据集生成工具
  12. import numpy as np
  13. import seaborn as sns
  14. from sklearn.datasets import make_moons
  15. from sklearn.model_selection import train_test_split
  16. from tensorflow.keras import layers, Sequential, regularizers
  17. from mpl_toolkits.mplot3d import Axes3D
  18. plt.rcParams['font.size'] = 16
  19. plt.rcParams['font.family'] = ['STKaiti']
  20. plt.rcParams['axes.unicode_minus'] = False
  21. OUTPUT_DIR = 'output_dir'
  22. N_EPOCHS = 500
  23. def load_dataset():
  24. # 采样点数
  25. N_SAMPLES = 1000
  26. # 测试数量比率
  27. TEST_SIZE = None
  28. # 从 moon 分布中随机采样 1000 个点,并切分为训练集-测试集
  29. X, y = make_moons(n_samples=N_SAMPLES, noise=0.25, random_state=100)
  30. X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=TEST_SIZE, random_state=42)
  31. return X, y, X_train, X_test, y_train, y_test
  32. def make_plot(X, y, plot_name, file_name, XX=None, YY=None, preds=None, dark=False, output_dir=OUTPUT_DIR):
  33. # 绘制数据集的分布, X 为 2D 坐标, y 为数据点的标签
  34. if dark:
  35. plt.style.use('dark_background')
  36. else:
  37. sns.set_style("whitegrid")
  38. axes = plt.gca()
  39. axes.set_xlim([-2, 3])
  40. axes.set_ylim([-1.5, 2])
  41. axes.set(xlabel="$x_1$", ylabel="$x_2$")
  42. plt.title(plot_name, fontsize=20, fontproperties='SimHei')
  43. plt.subplots_adjust(left=0.20)
  44. plt.subplots_adjust(right=0.80)
  45. if XX is not None and YY is not None and preds is not None:
  46. plt.contourf(XX, YY, preds.reshape(XX.shape), 25, alpha=0.08, cmap=plt.cm.Spectral)
  47. plt.contour(XX, YY, preds.reshape(XX.shape), levels=[.5], cmap="Greys", vmin=0, vmax=.6)
  48. # 绘制散点图,根据标签区分颜色m=markers
  49. markers = ['o' if i == 1 else 's' for i in y.ravel()]
  50. mscatter(X[:, 0], X[:, 1], c=y.ravel(), s=20, cmap=plt.cm.Spectral, edgecolors='none', m=markers, ax=axes)
  51. # 保存矢量图
  52. plt.savefig(output_dir + '/' + file_name)
  53. plt.close()
  54. def mscatter(x, y, ax=None, m=None, **kw):
  55. import matplotlib.markers as mmarkers
  56. if not ax: ax = plt.gca()
  57. sc = ax.scatter(x, y, **kw)
  58. if (m is not None) and (len(m) == len(x)):
  59. paths = []
  60. for marker in m:
  61. if isinstance(marker, mmarkers.MarkerStyle):
  62. marker_obj = marker
  63. else:
  64. marker_obj = mmarkers.MarkerStyle(marker)
  65. path = marker_obj.get_path().transformed(
  66. marker_obj.get_transform())
  67. paths.append(path)
  68. sc.set_paths(paths)
  69. return sc
  70. def network_layers_influence(X_train, y_train):
  71. # 构建 5 种不同层数的网络
  72. for n in range(5):
  73. # 创建容器
  74. model = Sequential()
  75. # 创建第一层
  76. model.add(layers.Dense(8, input_dim=2, activation='relu'))
  77. # 添加 n 层,共 n+2 层
  78. for _ in range(n):
  79. model.add(layers.Dense(32, activation='relu'))
  80. # 创建最末层
  81. model.add(layers.Dense(1, activation='sigmoid'))
  82. # 模型装配与训练
  83. model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
  84. model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
  85. # 绘制不同层数的网络决策边界曲线
  86. # 可视化的 x 坐标范围为[-2, 3]
  87. xx = np.arange(-2, 3, 0.01)
  88. # 可视化的 y 坐标范围为[-1.5, 2]
  89. yy = np.arange(-1.5, 2, 0.01)
  90. # 生成 x-y 平面采样网格点,方便可视化
  91. XX, YY = np.meshgrid(xx, yy)
  92. preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
  93. title = "网络层数:{0}".format(2 + n)
  94. file = "网络容量_%i.png" % (2 + n)
  95. make_plot(X_train, y_train, title, file, XX, YY, preds, output_dir=OUTPUT_DIR + '/network_layers')
  96. def dropout_influence(X_train, y_train):
  97. # 构建 5 种不同数量 Dropout 层的网络
  98. for n in range(5):
  99. # 创建容器
  100. model = Sequential()
  101. # 创建第一层
  102. model.add(layers.Dense(8, input_dim=2, activation='relu'))
  103. counter = 0
  104. # 网络层数固定为 5
  105. for _ in range(5):
  106. model.add(layers.Dense(64, activation='relu'))
  107. # 添加 n 个 Dropout 层
  108. if counter < n:
  109. counter += 1
  110. model.add(layers.Dropout(rate=0.5))
  111. # 输出层
  112. model.add(layers.Dense(1, activation='sigmoid'))
  113. # 模型装配
  114. model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
  115. # 训练
  116. model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
  117. # 绘制不同 Dropout 层数的决策边界曲线
  118. # 可视化的 x 坐标范围为[-2, 3]
  119. xx = np.arange(-2, 3, 0.01)
  120. # 可视化的 y 坐标范围为[-1.5, 2]
  121. yy = np.arange(-1.5, 2, 0.01)
  122. # 生成 x-y 平面采样网格点,方便可视化
  123. XX, YY = np.meshgrid(xx, yy)
  124. preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
  125. title = "无Dropout层" if n == 0 else "{0}层 Dropout层".format(n)
  126. file = "Dropout_%i.png" % n
  127. make_plot(X_train, y_train, title, file, XX, YY, preds, output_dir=OUTPUT_DIR + '/dropout')
  128. def build_model_with_regularization(_lambda):
  129. # 创建带正则化项的神经网络
  130. model = Sequential()
  131. model.add(layers.Dense(8, input_dim=2, activation='relu')) # 不带正则化项
  132. # 2-4层均是带 L2 正则化项
  133. model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(_lambda)))
  134. model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(_lambda)))
  135. model.add(layers.Dense(256, activation='relu', kernel_regularizer=regularizers.l2(_lambda)))
  136. # 输出层
  137. model.add(layers.Dense(1, activation='sigmoid'))
  138. model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # 模型装配
  139. return model
  140. def plot_weights_matrix(model, layer_index, plot_name, file_name, output_dir=OUTPUT_DIR):
  141. # 绘制权值范围函数
  142. # 提取指定层的权值矩阵
  143. weights = model.layers[layer_index].get_weights()[0]
  144. shape = weights.shape
  145. # 生成和权值矩阵等大小的网格坐标
  146. X = np.array(range(shape[1]))
  147. Y = np.array(range(shape[0]))
  148. X, Y = np.meshgrid(X, Y)
  149. # 绘制3D图
  150. fig = plt.figure()
  151. ax = fig.gca(projection='3d')
  152. ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
  153. ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
  154. ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
  155. plt.title(plot_name, fontsize=20, fontproperties='SimHei')
  156. # 绘制权值矩阵范围
  157. ax.plot_surface(X, Y, weights, cmap=plt.get_cmap('rainbow'), linewidth=0)
  158. # 设置坐标轴名
  159. ax.set_xlabel('网格x坐标', fontsize=16, rotation=0, fontproperties='SimHei')
  160. ax.set_ylabel('网格y坐标', fontsize=16, rotation=0, fontproperties='SimHei')
  161. ax.set_zlabel('权值', fontsize=16, rotation=90, fontproperties='SimHei')
  162. # 保存矩阵范围图
  163. plt.savefig(output_dir + "/" + file_name + ".svg")
  164. plt.close(fig)
  165. def regularizers_influence(X_train, y_train):
  166. for _lambda in [1e-5, 1e-3, 1e-1, 0.12, 0.13]: # 设置不同的正则化系数
  167. # 创建带正则化项的模型
  168. model = build_model_with_regularization(_lambda)
  169. # 模型训练
  170. model.fit(X_train, y_train, epochs=N_EPOCHS, verbose=1)
  171. # 绘制权值范围
  172. layer_index = 2
  173. plot_title = "正则化系数:{}".format(_lambda)
  174. file_name = "正则化网络权值_" + str(_lambda)
  175. # 绘制网络权值范围图
  176. plot_weights_matrix(model, layer_index, plot_title, file_name, output_dir=OUTPUT_DIR + '/regularizers')
  177. # 绘制不同正则化系数的决策边界线
  178. # 可视化的 x 坐标范围为[-2, 3]
  179. xx = np.arange(-2, 3, 0.01)
  180. # 可视化的 y 坐标范围为[-1.5, 2]
  181. yy = np.arange(-1.5, 2, 0.01)
  182. # 生成 x-y 平面采样网格点,方便可视化
  183. XX, YY = np.meshgrid(xx, yy)
  184. preds = model.predict_classes(np.c_[XX.ravel(), YY.ravel()])
  185. title = "正则化系数:{}".format(_lambda)
  186. file = "正则化_%g.svg" % _lambda
  187. make_plot(X_train, y_train, title, file, XX, YY, preds, output_dir=OUTPUT_DIR + '/regularizers')
  188. def main():
  189. X, y, X_train, X_test, y_train, y_test = load_dataset()
  190. # 绘制数据集分布
  191. make_plot(X, y, None, "月牙形状二分类数据集分布.svg")
  192. # 网络层数的影响
  193. network_layers_influence(X_train, y_train)
  194. # Dropout的影响
  195. dropout_influence(X_train, y_train)
  196. # 正则化的影响
  197. regularizers_influence(X_train, y_train)
  198. if __name__ == '__main__':
  199. main()