tensorflow的入门的极简例子

hello word级别的例子

目标

使用一个简单的例子熟悉tensorflow的基本流程

步骤

导入必备的库文件

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

模拟一些数据

x= np.float32(np.linspace(-1,1,500))
y_data = x**2+np.random.random()
plt.plot(x,y_data,'*')
plt.plot(x,y,'-')
plt.show()

注意x= np.float32(np.linspace(-1,1,500)),numpy中的数是64位的,不转换的话,后续的tf计算会报错

定义权重和偏差

w = tf.Variable(tf.zeros([1]))
b = tf.Variable(tf.zeros([1]))
y = tf.multiply(x**2,w)+b

选择损失函数和优化方法

loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.1)
train = optimizer.minimize(loss)

初始化变量

init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)

变量要先初始化

训练数据

for step in range(1000):
    sess.run(train)
    if(step%20==0):
        print(step,sess.run(w),sess.run(b))

run的含义相当于取回数据

结果

0 [0.0616133] [0.13055559]
20 [0.44206506] [0.5177559]
40 [0.5964618] [0.46486416]
60 [0.7075886] [0.4244651]
80 [0.7881098] [0.39517784]
100 [0.8464579] [0.3739553]
120 [0.88873863] [0.3585768]
140 [0.9193767] [0.34743306]
160 [0.94157785] [0.33935794]
180 [0.95766556] [0.33350652]
200 [0.96932316] [0.3292664]
220 [0.9777706] [0.32619384]
240 [0.98389184] [0.3239674]
260 [0.98832756] [0.32235402]
280 [0.99154174] [0.32118496]
300 [0.99387085] [0.3203378]
320 [0.9955586] [0.31972393]
340 [0.99678165] [0.3192791]
360 [0.9976679] [0.31895673]
380 [0.9983101] [0.31872314]
400 [0.99877554] [0.31855386]
420 [0.99911284] [0.31843117]
440 [0.99935716] [0.31834233]
460 [0.9995342] [0.31827793]
480 [0.99966246] [0.31823128]
500 [0.99975544] [0.31819746]
520 [0.9998228] [0.31817296]
540 [0.9998716] [0.3181552]
560 [0.9999069] [0.31814235]
580 [0.9999326] [0.31813303]
600 [0.9999511] [0.31812626]
620 [0.99996454] [0.31812143]
640 [0.9999742] [0.3181179]
660 [0.9999812] [0.31811532]
680 [0.9999864] [0.31811342]
700 [0.99999017] [0.31811213]
720 [0.99999267] [0.31811118]
740 [0.99999464] [0.31811044]
760 [0.9999958] [0.31811]
780 [0.999997] [0.31810957]
800 [0.9999981] [0.31810918]
820 [0.99999815] [0.31810918]
840 [0.99999815] [0.31810918]
860 [0.99999815] [0.31810918]
880 [0.99999815] [0.31810918]
900 [0.99999815] [0.31810918]
920 [0.99999815] [0.31810918]
940 [0.99999815] [0.31810918]
960 [0.99999815] [0.31810918]
980 [0.99999815] [0.31810918]

随着训练最后的权重逐渐就稳定到1了,偏差结果根据随机的不同而不同。

发布了4 篇原创文章 · 获赞 0 · 访问量 21
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 1024 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览