import tensorflow as tf
#在2.X版本的tensorflow使用1.x版本的tenorflow
import numpy as np
#在2.X版本的tensorflow使用1.x版本的tenorflow
#activation_function=None为Linear线性函数
#添加神经层函数
def add_layer(inputs,in_size,out_size,activation_function=None):
with tf.name_scope('layer'): # 创建layer框架
with tf.name_scope('weights'): # 创建Weights框架
Weights=tf.Variable(tf.random_normal([in_size,out_size]),name='W')
#生成随机变量矩阵有in_size行out_size列
with tf.name_scope('biases'):
biases=tf.Variable(tf.zeros([1,out_size])+0.1,name='b')
#1行out_size列的数值为0.1
with tf.name_scope('Wx_plus_b'):
#矩阵乘法
Wx_plus_b=tf.matmul(tf.cast(inputs,tf.float32),Weights)+biases
if activation_function is None:
outputs=Wx_plus_b
else:
outputs=activation_function(Wx_plus_b)
return outputs
#[-1,1]区间有300个单位 功能:在指定的间隔内返回均匀间隔的数字。
##x_data 输入层
x_data=np.linspace(-1,1,300)[:,np.newaxis]
#np.newaxis 插入新维度
#np.random.normal(均值,方差,输出size)正态分布
noise=np.random.normal(0,0.05,x_data.shape)
y_data=np.square(x_data)-0.5+noise
#x的值
with tf.name_scope('inputs'):#创建inputs框架
xs=tf.placeholder(tf.float32,[None,1],name='x_input')#行不定列为1
#tf.placeholder(dtype,shape=None,name=None)
#y的值
ys=tf.placeholder(tf.float32,[None,1],name='y_input')
##隐藏层l1 input=1 output=10
l1=add_layer(x_data,1,10,activation_function=tf.nn.relu)
##输出层predition
prediction=add_layer(l1,10,1,activation_function=None)
#square平方reduce_sum求和之后reduce_mean求平均值
#reduction_indices=[1]维度为1
with tf.name_scope('loss'):
loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
with tf.name_scope('train'):
train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss)#学习效率为0.1(<1) minimize(loss)减小误差
init=tf.global_variables_initializer()
sess=tf.Session()
writer=tf.summary.FileWriter('logs/',sess.graph)#graph是全部框架
sess.run(init)
#生成文件在pycharm目录下
#右键文件logsopen in terminal cd.. 返回logs的上级
# C:\Users\yanqi\PycharmProjects\tensorflow1.0>tensorboard --logdir=logs --host=127.0.0.1
首次尝试tensorboard1
最新推荐文章于 2024-08-09 17:10:42 发布