加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

tensorflow-非线性回归

发布时间:2020-12-14 04:30:10 所属栏目:大数据 来源:网络整理
导读:#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Sep 15 10:54:53 2018 @author: myhaspl @email:[email?protected] 非线性回归 单样本 """ import tensorflow as tf import numpy as np trainCount=50 g=tf.Graph() with g.as_default(
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Sep 15 10:54:53 2018 @author: myhaspl @email:[email?protected] 非线性回归 单样本 """ import tensorflow as tf import numpy as np trainCount=50 g=tf.Graph() with g.as_default(): with tf.name_scope("variables"): w=tf.Variable(tf.zeros([2,1]),name="w",dtype=tf.float32) b=tf.Variable(0.,dtype=tf.float32,name="b") with tf.name_scope("inputDatas"): x=tf.placeholder(dtype=tf.float32,shape=[None,2],name="input_x") y=tf.placeholder(dtype=tf.float32,shape=[None],name="input_y") def inference(x): result=tf.add(tf.matmul(tf.pow(x,2),w),b) return result def loss(x,y): yp=inference(x) return tf.reduce_sum(tf.squared_difference(y,yp)) def train(learningRate,trainLoss): trainOp=tf.train.GradientDescentOptimizer(learningRate).minimize(trainLoss) return trainOp def evaluate(x): return inference(x) def accuracy(x,y): yp=inference(x) return tf.subtract(1.0,tf.reduce_mean(tf.divide(tf.abs(yp-y),y))) def inputs(n): sampleX=np.array(np.random.rand(n,dtype=np.float32) sampleb1=5. samplew=np.array([0.5,0.9],dtype=np.float32) b2=np.array(np.random.rand(n),dtype=np.float32) sampleY=np.matmul(pow(sampleX,samplew)+sampleb1+b2 return (sampleX,sampleY) init=tf.global_variables_initializer() with tf.Session(graph=g) as sess: sess.run(init) sampleX,sampleY=inputs(100) sampleCount=sampleX.shape[0] testX,testY=inputs(5) testCount=testX.shape[0] trainLoss=loss(x,y) trainOp=train(0.25,trainLoss) accuracyOp=accuracy(sampleX,sampleY) inputX=sampleX inputY=sampleY print inputX.shape print inputY.shape for trainStep in xrange(trainCount): if trainStep%5==0: validate_acc=sess.run(accuracyOp) print "%d次后=>正确率%g"%(trainStep,validate_acc) for i in xrange(sampleCount): inputX=np.array([sampleX[i]],dtype=np.float32) inputY=np.array([sampleY[i]],dtype=np.float32) sess.run(trainOp,feed_dict={x:inputX,y:inputY}) print "w:",sess.run(w) print "b:",sess.run(b) print "测试样本正确率%g"%sess.run(accuracy(testX,testY))
(100,2)
(100,)
0次后=>正确率0
5次后=>正确率0.927204
10次后=>正确率0.927204
15次后=>正确率0.927204
20次后=>正确率0.927204
25次后=>正确率0.927204
30次后=>正确率0.927204
35次后=>正确率0.927204
40次后=>正确率0.927204
45次后=>正确率0.927204
w: [[0.4828106 ]
 [0.82115054]]
b: 5.412575
测试样本正确率0.956847
单样本训练

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读