# -*- coding: utf-8 -*-
"""
@Time : 2021/8/14 上午1:42
@Auth : 陈伟峰
@File :tensorflow_01.py
@phone: 15882085601
@IDE :PyCharm
@Motto:ABC(Always Be Coding)
"""
import tensorflow as tf
import numpy as np
# 构造300个点
x_data = np.linspace(-1,1,300)[:,np.newaxis]
# print(x_data)
# 随机噪声
noise = np.random.normal(0,0.05,x_data.shape)
# print(noise.shape)
y_data = np.square(x_data)-0.5+noise
# print(y_data.shape)
# 占位符
xs= tf.placeholder(tf.float32,[None,1])
ys = tf.placeholder(tf.float32,[None,1])
def add_layer(inputs,in_size,out_size,activation_function=None):
'''
:param inputs:输入数据
:param in_size: 输入大小
:param out_size: 输出大小
:param activation_function:激活函数
:return:
'''
# 构建权重
weights = tf.Variable(tf.random_normal([in_size,out_size]))
# 构建bias
biases = tf.Variable(tf.zeros([1,out_size])+0.1)
# 矩阵乘法
wx_plus_b = tf.matmul(inputs,weights)+biases
if activation_function is None:
outputs = wx_plus_b
else:
outputs = activation_function(wx_plus_b)
return outputs
# 构建隐藏层
h1 = add_layer(xs,1,20,activation_function=tf.nn.relu)
# 构建输出层
predict = add_layer(h1,20,1,activation_function=None)
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-predict),reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(learning_rate=0.01).minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for i in range(1000):
sess.run(train_step,feed_dict={
xs:x_data,
ys:y_data
})
if i%50==0:
print("loss=",sess.run(loss,feed_dict={
xs:x_data,
ys:y_data
}))