BP算法 && 第一次遇到TensorFlow2.0的大坑 &&没有完全搞懂

Back Propagation algorithm

 

首先在编程的时候遇到了tensorflow版本过低的问题,使用不了sigmoid激发函数。

因此使用

python

import tensorflow as tf

tf.__version__

查看tensorflow版本。

tf.__path__查看tensorflow的位置 

 

 

pip uninstall tensorflow

会自动卸载与其相关包

pip install --no-cache-dir tensorflow==x.xx

安装某版本

 

我这里直接安装了2.00的版本。

 

 

但是好像这样直接把我的tensorflow搞崩了。

输入tf.__path__直接是D:\Anaconda\envs\tensorflow\Lib\site-packages\tensorflow

而vscode的环境是D:\Anaconda\envs\tensorflow。。。

直接以前的代码也运行不了了。

这个工程问题之后再解决。

 

https://www.cnblogs.com/ping2yingshi/p/12913589.html

 

直接在vscode里面运行发现也是2.0.0版本python,那么应该就不是这个问题。

 

最终发现原因是tf2.0  这个大坑,直接不支持tutorials了,直接用Keras了。

在github上面的TensorFlow的example里也找不到tutorials,直接就不能用了。

那咋办?

 

直接装回去了。pip install --no-cache-dir tensorflow==1.11.0

 

然后再次遇到了module 'tensorflow' has no attribute 'sigmod'这个报错。

 

...最终发现只是因为sigmoid打成了sigmod才报错了。。。。无语了。

 

 

#BPN
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data


#读取mnist数据集的方法和第一次读取的方法一样
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

n_input=784 #像素数目
n_classes=10  #显然数据集中的图片有10种

max_epochs=10000
learning_rate=0.5
batch_size=10
seed=0

n_hidden=30  #隐藏层的神经元数目


#sigmoid函数的导函数
def sigmaprime(x):
    return tf.multiply(tf.sigmoid(x),tf.subtract(tf.constant(1.0),tf.sigmoid(x)))


x_in= tf.placeholder(tf.float32,[None,n_input])
y=tf.placeholder(tf.float32,[None,n_classes])


def multilayer_perceptron(x,weights,biases):
    h_layer_1=tf.add(tf.matmul(x,weights['h1']),biases['h1'])
    out_layer_1=tf.sigmoid(h_layer_1)

    h_out=tf.matmul(out_layer_1,weights['out'])+biases['out']
    return tf.sigmoid(h_out),h_out,out_layer_1,h_layer_1

#权重和偏置变量
weights={
    'h1':tf.Variable(tf.random_normal([n_input,n_hidden],seed=seed)),
    'out':tf.Variable(tf.random_normal([n_hidden,n_classes],seed=seed))
}

biases={
    'h1':tf.Variable(tf.random_normal([1,n_hidden],seed=seed)),
    'out':tf.Variable(tf.random_normal([1,n_classes],seed=seed))
}

#正向传播
y_hat,h_2,o_1,h_1=multilayer_perceptron(x_in,weights,biases)

err=y_hat-y

#反向传播
delta_2=tf.multiply(err,sigmaprime(h_2))
delta_w_2=tf.matmul(tf.transpose(o_1),delta_2)

wtd_error=tf.matmul(delta_2,tf.transpose(weights['out']))
delta_1=tf.multiply(wtd_error,sigmaprime(h_1))
delta_w_1=tf.matmul(tf.transpose(x_in),delta_1)

eta=tf.constant(learning_rate)

#更新
step=[
    tf.assign(weights['h1'],tf.subtract(weights['h1'],
tf.multiply(eta,delta_w_1)))
    ,tf.assign(biases['h1'],tf.subtract(biases['h1'],
tf.multiply(eta,tf.reduce_mean(delta_1,axis=[0]))))
    ,tf.assign(weights['out'],tf.subtract(weights['out'],
tf.multiply(eta,delta_w_2)))
    ,tf.assign(biases['out'],tf.subtract(biases['out'],
tf.multiply(eta,tf.reduce_mean(delta_2,axis=[0]))))
]


acct_mat=tf.equal(tf.argmax(y_hat,1),tf.argmax(y,1))
accuracy=tf.reduce_sum(tf.cast(acct_mat,tf.float32))

init=tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(max_epochs):
        batch_xs,batch_ys=mnist.train.next_batch(batch_size)
        sess.run(step,feed_dict={x_in:batch_xs,y:batch_ys})
        if epoch%1000 ==0:
            acc_test=sess.run(accuracy,feed_dict=
                {x_in:mnist.test.images,y:mnist.test.labels})
            acc_train=sess.run(accuracy,feed_dict=
                {x_in:mnist.train.images,y:mnist.train.labels})
           print('Epoch:{0} Accuracy Train%:{1}' \
            'Accuracy Test%:{2}'.format(epoch,acc_train/600,(acc_test/100)))

 

先看看这个https://blog.csdn.net/weixin_40355324/article/details/80543391
感觉和TensorFlow实现反向传播算法详解 (biancheng.net)不太一样。

 

不管结构如何,现在总算是对于隐藏层,偏导数,反向传播有了一个大概的了解。

需要一篇正确的论文来指导我的学习。

 

posted @ 2021-09-23 13:30  TheDa  阅读(113)  评论(0编辑  收藏  举报