美文网首页
【Tensorflow】regression练习

【Tensorflow】regression练习

作者: 唯师默蓝 | 来源:发表于2019-04-11 17:04 被阅读0次
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

tf.set_random_seed(1)
np.random.seed(1)

x = np.linspace(-1, 1, 100)[:, np.newaxis]    # shape (100, 1)
# 生成高斯分布的概率密度随机数
noise = np.random.normal(0, 0.1, size=x.shape)
# numpy.power() 函数将第一个输入数组中的元素作为底数,计算它与第二个输入数组中相应元素的幂
y = np.power(x, 2) + noise
plt.scatter(x, y)
plt.show()

tf_x = tf.placeholder(tf.float32, x.shape)     # input x
tf_y = tf.placeholder(tf.float32, y.shape)     # input y

# neural network layers
# dense :全连接层  相当于添加一个层
# tf.layers.dense(
#
#     inputs,
#
#     units,
#
#     activation=None,
#
#     use_bias=True,
#
#     kernel_initializer=None,  ##卷积核的初始化器
#
#     bias_initializer=tf.zeros_initializer(),  ##偏置项的初始化器,默认初始化为0
#
#     kernel_regularizer=None,    ##卷积核的正则化,可选
#
#     bias_regularizer=None,    ##偏置项的正则化,可选
#
#     activity_regularizer=None,   ##输出的正则化函数
#
#     kernel_constraint=None,
#
#     bias_constraint=None,
#
#     trainable=True,
#
#     name=None,  ##层的名字
#
#     reuse=None  ##是否重复使用参数
#
# )
# 部分参数解释:
#
# inputs:输入该网络层的数据
#
# units:输出的维度大小,改变inputs的最后一维
#
# activation:激活函数,即神经网络的非线性变化
#
# use_bias:使用bias为True(默认使用),不用bias改成False即可,是否使用偏置项

l1 = tf.layers.dense(tf_x, 10, tf.nn.relu)          # hidden layer
output = tf.layers.dense(l1, 1) # output layer
# tf.losses.mean_squared_error(labels:真实的输出张量,与“predictions”相同 , predictions:预测的输出)
loss = tf.losses.mean_squared_error(tf_y, output)   # compute cost
# 梯度下降优化,最小化损失
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.5)
train_op = optimizer.minimize(loss)

sess = tf.Session()                                 # control training and others
sess.run(tf.global_variables_initializer()) # initialize var in graph
plt.ion() # something about plotting
for step in range(100):
    # train and net output
    _, l, pred = sess.run([train_op, loss, output], {tf_x: x, tf_y: y})
    if step % 5 == 0:
        # plot and show learning process
        plt.cla()
        plt.scatter(x, y)
        plt.plot(x, pred, 'r-', lw=5)
        plt.text(0.5, 0, 'Loss=%.4f' % l, fontdict={'size': 20, 'color': 'red'})
plt.pause(0.1)

plt.ioff()
plt.show()

相关文章

网友评论

      本文标题:【Tensorflow】regression练习

      本文链接:https://www.haomeiwen.com/subject/sflxwqtx.html