tensorflow简单的Demo

使用tensorflow来进行拟合

import tensorflow.compat.v1 as tf
import numpy as np

#适应tensorflow2.0版本
tf.compat.v1.disable_eager_execution()
#使用numpy生成100个点
x_data = np.random.rand(100)
#相当于一条线目标的k为0.1 目标b为0.2 相当于样本
y_data = x_data*0.1 + 0.2

#构造一个线性模型,b和k为小数 优化b和k使创建的模型接近于样本
b = tf.Variable(0.)
k = tf.Variable(0.)
y = k*x_data + b

#二次代价函数  reduce_mean:平均值
loss =  tf.reduce_mean(tf.square(y_data-y))
#定义一个梯度下降法来训练的优化器 使用梯度下降法学习率为0.2
optimizer = tf.train.GradientDescentOptimizer(0.2)
#最小化代价函数
train = optimizer.minimize(loss)
#初始化变量
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    for step in  range(201):#200次
        sess.run(train)
        if step%20  == 0:#每20次打印k和b的值
            print(step,sess.run([k,b]))

最后的输出结果为
 

0 [0.05232435, 0.099724516]
20 [0.102392495, 0.19874147]
40 [0.10144185, 0.1992416]
60 [0.10086892, 0.19954295]
80 [0.10052364, 0.19972457]
100 [0.10031557, 0.19983402]
120 [0.10019017, 0.19989997]
140 [0.100114614, 0.19993971]
160 [0.10006907, 0.19996367]
180 [0.10004162, 0.19997811]
200 [0.10002508, 0.19998682]

下面写一个简单的线性回归,以二次的为例

import tensorflow.compat.v1 as tf
import numpy as np
import matplotlib.pyplot as plt
tf.compat.v1.disable_eager_execution()
#使用numpy生成200个随机点  [:np.newaxis]:加一个维度200行1列
x_data = np.linspace(-0.5,0.5,200)[:,np.newaxis]
#生成噪音,形状和x_data一样
noise = np.random.normal(0,0.02,x_data.shape)
y_data = np.square(x_data)+noise

#定义两个placeholder
x = tf.placeholder(tf.float32,[None,1])
y = tf.placeholder(tf.float32,[None,1])

#定义神经网络中间层
Weight_L1 = tf.Variable(tf.random_normal([1,10]))
biases_L1 = tf.Variable(tf.zeros([1,10]))
Wx_plus_b_L1 = tf.matmul(x,Weight_L1) + biases_L1
#定义激活函数
L1 = tf.nn.tanh(Wx_plus_b_L1)

#定义输出层
Weight_L2 = tf.Variable(tf.random_normal([10,1]))
biases_L2 = tf.Variable(tf.random_normal([1,1]))
Wx_plus_b_L2 = tf.matmul(L1,Weight_L2) + biases_L2
prediction = tf.nn.tanh(Wx_plus_b_L2)

#二次代价函数
loss = tf.reduce_mean(tf.square(y-prediction))
#梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

#定义会话
with tf.Session() as sess:
    #变量初始化
    sess.run(tf.global_variables_initializer())
    for _ in range(2000):
        sess.run(train_step,feed_dict={x:x_data,y:y_data})
    #查看训练结果 训练后的w和b值进行计算的
    prediction_value = sess.run(prediction,feed_dict={x:x_data})
    plt.figure()
    plt.scatter(x_data,y_data)
    plt.plot(x_data,prediction_value,'r-',lw=2)
    plt.show()

最后运行的结果为:

多内容请扫描下方二维码关注小编公众号:程序员大管

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章