Tensorflow之神经网络

# 1.构建神经网络

import tensorflow as tf
import numpy as np
BATCH_SIZE=8
SEED=23455

rdm=np.random.RandomState(SEED)
X=rdm.rand(32,2)
Y=[[x1+x2+(rdm.rand()/10.0-0.05)] for (x1,x2) in X]

# None表示传入多组值
x=tf.placeholder(tf.float32,shape=[None,2])
y=tf.placeholder(tf.float32,shape=[None,1])

w1=tf.Variable(tf.random_normal([2,1],seed=1))
result=tf.matmul(x,w1)

# 2.激活函数(将线性转为非线性)

本例子没有激活函数,激活函数加在得到的y值上

1.relu
tf.nn.relu()
2.sigmoid
tf.nn.sigmoid()
3.tanh         
tf.nn.tanh()

 

# 3.求损失函数

 

1.均方误差

 

loos_mse=tf.reduce_mean(tf.square(y-result))

 

2.自定义

# PROFIT=9
# COST=1
# loss=tf.reduce_sum(tf.where(tf.greater(result,y),(result-y)*COST,(y-result)*PROFIT))
# loss=tf.reduce_sum(tf.where(tf.greater(result,y),(result-y)*COST,(y-result)*PROFIT))

 

3.交叉熵(表示两个概率分布之间的距离)

# y_真实值,y预测值
-tf.reduce_mean(y_*tf.log(tf.clip_by_value(y,1e-12,1.0)))
实际中通过softmax函数
ce=tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y,labels=tf.argmax(y_,1))
cem=tf.reduce_mean(ce)

 

# 4.学习率

 

 

# 5.反向传播(减小loss)

# 参数优化

1.滑动平均(优化W和b)

2.正则化

 

posted @ 2019-11-03 20:22  lujiacheng-python  阅读(262)  评论(0编辑  收藏  举报