反向传播算法实战

1.神经网络公式推导

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
2.代码实现
实现一个4 层的全连接网络,来完成二分类任务。网络输入节点数为2,隐层的节点数设计为:25、50和25,输出层两个节点,分别表示属于类别1 的概率和类别的概率,如图 7.13 所示。这里并没有采用Softmax 函数将网络输出概率值之和进行约束而是直接利用均方误差函数计算与One-hot 编码的真实标签之间的误差,所有的网络激函数全部采用Sigmoid 函数,这些设计都是为了能直接利用我们的梯度传播公式。

在这里插入图片描述

X,y=datasets.make_moons(n_samples=2000,noise=0.2,random_state=100)
X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.3, random_state=42)
print(y_train.shape, y_test.shape)
print(y_train)
def make_plot(X, y, plot_name, file_name=None, XX=None, YY=None, preds=None,dark=False):
    if (dark):
        plt.style.use('dark_background')
    else:
        sns.set_style("whitegrid")
        plt.figure(figsize=(16,12))
        axes = plt.gca()
        axes.set(xlabel="$x_1$", ylabel="$x_2$")
        plt.title(plot_name, fontsize=30)
        plt.subplots_adjust(left=0.20)
        plt.subplots_adjust(right=0.80)
    if(XX is not None and YY is not None and preds is not None):
        plt.contourf(XX, YY, preds.reshape(XX.shape), 25, alpha = 1,cmap=cm.Spectral)
        plt.contour(XX, YY, preds.reshape(XX.shape), levels=[.5],cmap="Greys", vmin=0, vmax=.6)
        # 绘制散点图,根据标签区分颜色
    plt.scatter(X[:, 0], X[:, 1], c=y.ravel(), s=40, cmap=plt.cm.Spectral,
    edgecolors='none')
    plt.savefig('dataset.svg')
    plt.show()
class Layer:
    def __init__(self,input,out,activation=None,weights=None,bias=None):
        '''
        :param input: 输入
        :param out: 输出
        :param activation: 激活函数
        :param weights: 权重
        :param bias: 偏置
        '''
        self.weights = weights if weights is not None else np.random.randn(input,out)*np.sqrt(1/out)
        self.bias = bias if bias is not None else np.random.randn((out))*0.1
        self.activation = activation
        self.last_activation = None  # 激活函数的输出值o
        self.error = None  # 用于计算当前层的delta 变量的中间变量
        self.delta = None   # 记录当前层的delta 变量,用于计算梯度

    #实现前向传播
    def activate(self,x):
        h = np.dot(x,self.weights)+self.bias    #X@W+b
        self.last_activation = self._apply_activation(h)
        return self.last_activation
    #激活函数
    def _apply_activation(self, h):
        if self.activation == None:
            return h
        elif self.activation == 'relu':
            return np.maximum(h,0)
        elif self.activation == 'tanh':
            return np.tanh(h)
        elif self.activation == 'sigmoid':
            return 1/(1+np.exp(-h))
        return h
     #激活函数导数
    def apply_activation(self,h):
        if self.activation == None:
            return np.ones_like(h)
        elif self.activation == 'relu':
            grad = np.array(h,copy=True)
            grad[h>0] = 1
            grad[h<0] = 0
            return grad
        elif self.activation == 'tanh':
             return 1 - h ** 2
        elif self.activation == 'sigmoid':
            return h * (1 - h)
        return  h

class Network:
    def __init__(self):
        self.layers=[]
    def add_layer(self,layer):
        self.layers.append(layer)
    # 前向传播
    def feed_foward(self,x):
        for layer in self.layers:
            # 依次通过各个网络层
            x = layer.activate(x)
        return x

    # 反向传播算法实现
    def backpropagation(self,x,y,leraning_rate):
        out = self.feed_foward(x) #前向计算,得到输出值
        for i in reversed(range(len(self.layers))): # 反向循环
            layer=self.layers[i] # 获取当前层对象
            if layer == self.layers[-1]: #输出层
                layer.error = y- out
                # 关键步骤:计算最后一层的delta,参考输出层的梯度公式
                layer.delta = layer.error * layer.apply_activation(out)
            else: # 隐藏层
                next_layer = self.layers[i+1]
                # 关键步骤:计算隐藏层的delta,参考隐藏层的梯度公式
                layer.error = np.dot(next_layer.weights,next_layer.delta)
                layer.delta = layer.error * layer.apply_activation(layer.last_activation)
        for j in range(len(self.layers)):
            layer = self.layers[j]
            if j == 0:
                o_i = np.atleast_2d(x)
            else:
                o_i = np.atleast_2d(self.layers[j-1].last_activation)
            layer.weights += layer.delta * o_i.T *leraning_rate


    def train(self,x_train,x_test,y_train,y_test,learing_rate,max_epoch):
        y_onehot = np.zeros((y_train.shape[0], 2))
        y_onehot[np.arange(y_train.shape[0]), y_train] = 1
        # y_onehot = tf.one_hot(y_onehot, depth=2)
        mses = []
        accuracys = []
        for  i in range(max_epoch+1):
            for j in range(len(x_train)):
                self.backpropagation(x_train[j],y_onehot[j],learing_rate)
            if i %10 == 0:
                mse = np.mean(np.square(y_onehot - self.feed_foward(x_train)))
                mses.append(mse)
                accuracy = self.accuracy(self.predict(x_test), y_test.flatten())
                accuracys.append(accuracy)
                print('Epoch: #%s, MSE: %f' % (i, float(mse)))
                # 统计并打印准确率
                print('Accuracy: %.2f%%' % (accuracy * 100))
        return mses , accuracys

    def predict(self,x):
       return  self.feed_foward(x)
    def accuracy(self,x,y)
         # 计算精确度,统计每一轮所有概率为1的个数
        return np.sum(np.equal(np.argmax(x, axis=1), y)) /  y.shape[0]


nn=Network()
nn.add_layer(Layer(2, 25, 'sigmoid')) # 隐藏层1, 2=>25
nn.add_layer(Layer(25, 50, 'sigmoid')) # 隐藏层2, 25=>50
nn.add_layer(Layer(50, 25, 'sigmoid')) # 隐藏层3, 50=>25
nn.add_layer(Layer(25, 2, 'sigmoid')) # 输出层, 25=>2
# 调用make_plot 函数绘制数据的分布,其中X 为2D 坐标,y 为标签
make_plot(X, y, "Classification Dataset Visualization ")

mse,accuracy = nn.train(X_train,X_test,y_train,y_test,0.01,1000)
x = [i for i in range(0, 101, 10)]
# 绘制MES曲线
plt.title("MES Loss")
plt.plot(x, mse[:11], color='blue')
plt.xlabel('Epoch')
plt.ylabel('MSE')
plt.show()
# 绘制Accuracy曲线
plt.title("Accuracy")
plt.plot(x, accuracy[:11], color='blue')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.show()

3.训练效果
在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值