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

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