欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

tensorflow实现一个简单的神经网络

程序员文章站 2022-05-22 13:07:02
...
import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation

# add a layer to nerual network
def add_layers(inputs, in_size, out_size, activation_function=None):
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.01)

    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs

# create data
x = np.linspace(-1, 1, 300)[:, np.newaxis]
noise = np.random.normal(0, 0.05, x.shape)
y = np.square(x)-0.5 + noise

# plot data
# plt.scatter(x,y)
# plt.show()

xs = tf.placeholder(tf.float32, [None,1])
ys = tf.placeholder(tf.float32, [None,1])

# neural network layers
hidden1 = add_layers(xs, 1, 10, activation_function=tf.nn.relu)
output = add_layers(hidden1, 10, 1, activation_function=None)

# define loss
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-output), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

with tf.Session() as sess:
    # initializer
    sess.run(tf.global_variables_initializer())
    # visualize
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    ax.scatter(x, y)
    plt.ion()#程序不暂停,连续画图
    plt.show()

    for i in range(1000):
        # _, l, pre = sess.run([train_step,loss, output],{xs:x,ys:y})
        sess.run(train_step, feed_dict={xs:x,ys:y})
        if i % 50 == 0:
            print(sess.run(loss, feed_dict={xs:x,ys:y}))
            try:
                ax.lines.remove(lines[0])
            except Exception:
                pass
            pre = sess.run(output, feed_dict={xs: x, ys: y})
            lines = ax.plot(x, pre, 'r-', lw=5)
            # plt.savefig("%d.png"% i)
            plt.pause(0.1)

    plt.ioff()
    plt.show()

最后得到的效果如下:
tensorflow实现一个简单的神经网络

以上gif实现的效果代码,首先保存图片,然后基于保存的图像进行gif图片的制作,代码如下

import matplotlib.pyplot as plt
import imageio,os
images = []
filenames=sorted((fn for fn in os.listdir('.') if fn.endswith('.png')))
for filename in filenames:
    images.append(imageio.imread(filename))
imageio.mimsave('gif.gif', images,duration=0.5)