神经网络

python

浏览数:410

2019-1-8


神经网络

import tensorflow as tf
import numpy as np

def add_layer(inputs,in_size,out_size,activation_function=None):
    w = tf.Variable(tf.random_normal([in_size,out_size]))
    b = tf.Variable(tf.random_normal([1,out_size])+0.1)
    aly = tf.matmul(inputs, w)
    if activation_function is None:
        outputs = aly
    else:
        outputs = activation_function(aly)
    return outputs

x_data = np.linspace(--1,1,300)[:,np.newaxis] #增加一个维度
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data)-0.5 + noise

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

li = add_layer(xs,1,10,activation_function=tf.nn.relu)
p = add_layer(li,10,1,activation_function=None)

loss =tf.reduce_mean(tf.reduce_sum(tf.square(ys-p), reduction_indices=[1]) ) #求和reduce_sum,平均值reduce_mean
train = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

with tf.Session() as sess:
    inits= tf.initialize_all_variables()
    sess.run(inits)
    STEPS = 50000
    step = 0
    for i in range(STEPS):
        sess.run(train ,feed_dict={xs: x_data, ys: y_data})
        step += 1
        if step == STEPS:
            print(sess.run(loss,feed_dict={xs: x_data, ys: y_data}))