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()

最後運行的結果爲:

多內容請掃描下方二維碼關注小編公衆號:程序員大管

 

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