Structure

import tensorflow as tf
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()# 由于部分代码含有版本不同,此将v2版本禁用使用v1版本
# create data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1 + 0.3
#create tensorflow structure start
Weights = tf.Variable(tf.random.uniform([1], -1.0, 1.0)) #tf.random_uniform随机均匀分布,一维,初始值为-1到1
biases = tf.Variable(tf.zeros([1])) 

y = Weights*x_data + biases
#compute the loss
loss = tf.reduce_mean(tf.square(y-y_data))
#反向传递误差的工作就教给optimizer
#使用的误差传递方法是梯度下降法: Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
#初始化所有之前定义的Variable
init = tf.compat.v1.global_variables_initializer()
sess = tf.compat.v1.Session()
sess.run(init)          # Very important

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

 

 
posted @ 2022-07-18 21:18  是冰美式诶  阅读(148)  评论(0)    收藏  举报