Tensorflow快速入門 線性回歸

2021-10-01 21:36:50 字數 4146 閱讀 7313

#--*coding--:utf-8

import tensorflow as tf

import numpy

import matplotlib.pyplot as plt

rng = numpy.random

learning_rate =

0.01

training_epochs =

10000

display_step =

50

train_x = numpy.asarray(

[3.3

,4.4

,5.5

,6.71

,6.93

,4.168

,9.779

,6.182

,7.59

,2.167

,7.042

,10.791

,5.313

,7.997

,5.654

,9.27

,3.1])

train_y = numpy.asarray(

[1.7

,2.76

,2.09

,3.19

,1.694

,1.573

,3.366

,2.596

,2.53

,1.221

,2.827

,3.465

,1.65

,2.904

,2.42

,2.94

,1.3])

n_samples = train_x.shape[0]

print

("train_x:"

,train_x)

print

("train_y:"

,train_y)

train_x: [ 3.3 4.4 5.5 6.71 6.93 4.168 9.779 6.182 7.59 2.167

7.042 10.791 5.313 7.997 5.654 9.27 3.1 ]

train_y: [1.7 2.76 2.09 3.19 1.694 1.573 3.366 2.596 2.53 1.221 2.827 3.465

1.65 2.904 2.42 2.94 1.3 ]

設定placeholder
x = tf.placeholder(

"float"

)y = tf.placeholder(

"float"

)

設定模型的權重和偏置
w = tf.variable(rng.randn(

), name=

"weight"

)b = tf.variable(rng.randn(

), name=

"bias"

)

設定線性回歸的方程
pred = tf.add(tf.multiply(x, w)

, b)

設定cost為均方差
cost = tf.reduce_sum(tf.

pow(pred-y,2)

)/(2

*n_samples)

梯度下降
optimizer = tf.train.gradientdescentoptimizer(learning_rate)

.minimize(cost)

初始化所有variables
init = tf.global_variables_initializer(

)

with tf.session(

)as sess:

sess.run(init)

# 灌入所有訓練資料

for epoch in

range

(training_epochs)

:for

(x, y)

inzip

(train_x, train_y)

: sess.run(optimizer, feed_dict=

)# 列印出每次迭代的log日誌

if(epoch+1)

% display_step ==0:

c = sess.run(cost, feed_dict=

)print

("epoch:"

,'%04d'

%(epoch+1)

,"cost=",""

.format

(c), \

"w="

, sess.run(w)

,"b="

, sess.run(b)

)print

("optimization finished!"

) training_cost = sess.run(cost, feed_dict=

)print

("training cost="

, training_cost,

"w="

, sess.run(w)

,"b="

, sess.run(b)

,'\n'

)# 作圖

plt.plot(train_x, train_y,

'ro'

, label=

'original data'

) plt.plot(train_x, sess.run(w)

* train_x + sess.run(b)

, label=

'fitted line'

) plt.legend(

) plt.show(

)# 測試樣本

TensorFlow 介紹及快速入門

tensorflow 是乙個採用資料流圖,用於數值計算的開源軟體庫。正如其名字所訴,tensorflow 本質是乙個由張量組成的資料流圖。tensorflow 在圖中使用節點來表示數學操作,使用線來表示在節點之間相互聯絡的多維資料陣列,即張量。除了表示施加的數學操作之外,節點還可以表示資料輸入的起點...

Tensorflow 快速學習

tensorflow 快速學習 python python3 cookbook 1 tensorflow原始碼庫 2 tensorflow中文文件 3 tensorflow入門例子庫1,每個例子都有對應的notebook說明。4 tensorflow入門例子庫2 5 tensorflow入門例子庫3...

Tensorflow 入門記錄

tensor為張量,flow為流圖。tensorflow內含有很多寫好的工具,如梯度下降演算法,卷積操作等。在使用tensorflow時,先導入包import tensorflow as tf,在進行定義tensorflow變數時,使用tf.variable 引數 有趣的是乙個叫做佔位符的工具,tf...