# 全连接神经网络的二分类问题

2 篇文章 0 订阅

## 生成数据集

from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import Sequential, layers
import matplotlib.pyplot as plt
X, y = make_moons(n_samples = 1000, noise=0.25, random_state=100)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)

plt.scatter(X[:,0], X[:, 1], c=y)
plt.show()

## 全连接神经网路

from tensorflow.keras import Sequential, layers
# 创建容器
model = Sequential()

model.add(layers.Dense(4, activation='sigmoid')) # 创建最末层
model.summary()

#运行的结果
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_19 (Dense)             (None, 4)                 12
_________________________________________________________________
dense_20 (Dense)             (None, 4)                 20
_________________________________________________________________
dense_21 (Dense)             (None, 4)                 20
=================================================================
Total params: 52
Trainable params: 52
Non-trainable params: 0
_________________________________________________________________

## 网络的训练及其可视化

import numpy as np
from matplotlib.colors import ListedColormap
for n in range(5):         # 构建 5 种不同层数的网络，网络层数分别为4，5，6，7，8
model = Sequential()   # 创建容器
for _ in range(n+2): # 添加 n+2 层，每个网络共 n+4 层
model.add(layers.Dense(1, activation='sigmoid')) # 输出为0，1之间的一个数，所以用sigmoid为激活函数。创建最末层

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # 模型装配与训练
history = model.fit(X_train, y_train, epochs=50, verbose=1)                       #网络模型的训练，迭代1000的数据50遍
# 绘制网络分类后的效果图
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.02), np.arange(y_min, y_max, 0.02))   #生成网格型二维数据对
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
# 创建颜色图
cmap_light = ListedColormap([(0,1,1), (1, 1,0)])
cmap_bold = ListedColormap(['g', 'r'])
#将预测的结果在平面坐标中画出其类别区域
Z = Z.reshape(xx.shape)
plt.figure(figsize=(16, 7))
plt.subplot(1,2,1)
plt.pcolormesh(xx, yy, Z, cmap=cmap_bold)
# 也画出所有的训练集数据
plt.scatter(X_train[:, 0], X_train[:, 1], c=y_train, cmap=cmap_light)
plt.subplot(1,2,2)
plt.pcolormesh(xx, yy, Z, cmap=cmap_bold)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
title = "The number of network layers is {}".format(n+4)
plt.title(title)
plt.show()

## 防止过拟合

Model: "sequential_2"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_340 (Dense)            (None, 8)                 24
_________________________________________________________________
dense_341 (Dense)            (None, 32)                288
_________________________________________________________________
dropout_15 (Dropout)         (None, 32)                0
_________________________________________________________________
dense_342 (Dense)            (None, 32)                1056
_________________________________________________________________
dropout_16 (Dropout)         (None, 32)                0
_________________________________________________________________
dense_343 (Dense)            (None, 32)                1056
_________________________________________________________________
dropout_17 (Dropout)         (None, 32)                0
_________________________________________________________________
dense_344 (Dense)            (None, 1)                 33
=================================================================
Total params: 2,457
Trainable params: 2,457
Non-trainable params: 0
_________________________________________________________________

• 3
点赞
• 0
评论
• 17
收藏
• 一键三连
• 扫一扫，分享海报

01-12 1855

12-06 1万+
11-02
01-01 1万+
11-05 1033
03-22 1万+
09-04 6423
07-31
06-09 383
02-13 507
©️2021 CSDN 皮肤主题: 1024 设计师:白松林

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。