tensorflow搭建神经网络(一)

最近在b站上学习tensorflow链接在下面~~~
课程链接

代码

#import tensorflow as tf
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

#creat data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1 + 0.3

###creat tensorflow structure start ###
Weights = tf.Variable(tf.random.uniform([1], -1.0,1.0))#随机生成一维数组,范围是-11
biases = tf.Variable(tf.zeros([1]))

y = Weights*x_data +biases

loss = tf.reduce_mean(tf.square(y-y_data))
#tf.compat.v1.disable_v2_behavior()
optimizer = tf.train.GradientDescentOptimizer(0.5)#优化器 用梯度下降法,初始步长为0.5 用来优化减小损失
train = optimizer.minimize(loss)

init = tf.global_variables_initializer()# 初始化
###creat tensorflow structure end###


sess = tf.Session()
sess.run(init) #激活tf

for step in range(201):
    sess.run(train)
    if step%20 == 0:
        print(step, sess.run(Weights), sess.run(biases))
0 [0.795222] [-0.09041236]
20 [0.26115763] [0.21646309]
40 [0.13670945] [0.28097147]
60 [0.1083619] [0.29566556]
80 [0.10190472] [0.2990127]
100 [0.10043386] [0.29977512]
120 [0.10009883] [0.29994878]
140 [0.10002252] [0.29998833]
160 [0.10000513] [0.29999736]
180 [0.10000116] [0.29999942]
200 [0.10000027] [0.29999986]

猜你喜欢

转载自blog.csdn.net/qq_45392109/article/details/113803300