Tensorflow 实例
全部基于Tensorflow=1.14.0
一个简单的线性回归用于入门。
import tensorflow as tf
import numpy as np
# create data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1 + 0.3
# print(x_data,y_data)
### create tensorflow strcture start ###
Weight = tf.Variable(tf.random_uniform([1],-1,1))
Bias = tf.Variable(tf.zeros([1]))
y = x_data*Weight + Bias
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.initialize_all_variables()
### create tensorflow structure end ###
with tf.Session() as sess:
sess.run(init)
for step in range(201):
sess.run(train)
if step%20==0:
print(step,sess.run(Weight),sess.run(Bias))
0 [0.06235075] [0.44886294]
20 [0.07994999] [0.3109886]
40 [0.0956158] [0.30240282]
60 [0.09904134] [0.30052543]
80 [0.09979039] [0.3001149]
100 [0.09995418] [0.30002514]
120 [0.09998999] [0.3000055]
140 [0.0999978] [0.3000012]
160 [0.09999952] [0.30000028]
180 [0.0999999] [0.30000007]
200 [0.09999996] [0.30000004]
Placeholder 干啥用?
import tensorflow as tf
input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1,input2)
with tf.Session() as sess:
print(sess.run(output,feed_dict={input1:[7.1,3.0],input2 :[0.9,0.1]}))
[6.39 0.3 ]
网友评论