tensorflow实现线下回归、softmax回归、bp神经网络

先入门做简单的线下回归,最小二乘化利用tensorflow来实现,代码原理如下:

 
    
  1. #encoding:utf-8
  2. import sys
  3. import tensorflow as tf
  4. import numpy as np
  5. x_data=np.random.rand(100).astype(np.float32)
  6. y_data=x_data*0.1+0.55
  7. #create tensortdlow strctru start
  8. Weights=tf.Variable(tf.random_uniform([1],-1.0,1.0))
  9. biases=tf.Variable(tf.zeros([1]))
  10. y=Weights*x_data+biases
  11. loss=tf.reduce_mean(tf.square(y-y_data))
  12. op=tf.train.GradientDescentOptimizer(0.5)
  13. train=op.minimize(loss)
  14. init=tf.initialize_all_variables()
  15. sess=tf.Session()
  16. sess.run(init)
  17. for i in xrange(250):
  18. sess.run(train)
  19. if i%20==0:
  20. print(i,sess.run(Weights),sess.run(biases))
结果是:
('0', array([-0.17141712], dtype=float32), array([ 0.96016634], dtype=float32))
('20', array([-0.00157562], dtype=float32), array([ 0.60436034], dtype=float32))
('40', array([ 0.07296405], dtype=float32), array([ 0.56446886], dtype=float32))
('60', array([ 0.09280396], dtype=float32), array([ 0.55385113], dtype=float32))
('80', array([ 0.09808466], dtype=float32), array([ 0.55102503], dtype=float32))
('100', array([ 0.09949023], dtype=float32), array([ 0.55027282], dtype=float32))
('120', array([ 0.09986429], dtype=float32), array([ 0.55007261], dtype=float32))
('140', array([ 0.09996392], dtype=float32), array([ 0.55001932], dtype=float32))
('160', array([ 0.09999041], dtype=float32), array([ 0.55000514], dtype=float32))
('180', array([ 0.09999743], dtype=float32), array([ 0.55000138], dtype=float32))
('200', array([ 0.09999929], dtype=float32), array([ 0.55000037], dtype=float32))
('220', array([ 0.0999998], dtype=float32), array([ 0.55000013], dtype=float32))
('240', array([ 0.09999982], dtype=float32), array([ 0.55000013], dtype=float32))


softmax情况如下:

 
    
  1. from tensorflow.examples.tutorials.mnist import input_data
  2. import tensorflow as tf
  3. mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)
  4. x=tf.placeholder("float",[None,784])
  5. w=tf.Variable(tf.zeros([784,10]))
  6. b=tf.Variable(tf.zeros([10]))
  7. y=tf.nn.softmax(tf.matmul(x,w)+b) #模型拟合值
  8. y_=tf.placeholder("float",[None,10]) #实际值
  9. cross_entropy=-tf.reduce_sum(y_*tf.log(y))
  10. train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
  11. init = tf.global_variables_initializer()
  12. sess=tf.Session()
  13. sess.run(init)
  14. for i in range(10000):
  15. batch_xs,batch_ys=mnist.train.next_batch(100)
  16. sess.run(train_step,feed_dict={x:batch_xs,y_:batch_ys})
  17. if i%1000==0:
  18. # 评估模型,tf.argmax能给出某个tensor对象在某一维上数据最大值的索引。因为标签是由0,1组成了one-hot vector,返回的索引就是数值为1的位置
  19. correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  20. # 计算正确预测项的比例,因为tf.equal返回的是布尔值,使用tf.cast可以把布尔值转换成浮点数,tf.reduce_mean是求平均值
  21. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  22. # 在session中启动accuracy,输入是MNIST中的测试集
  23. print("第"+str(i)+"步骤为:",sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))


结果为:

 
    
  1. 0步骤为: 0.4124
  2. 1000步骤为: 0.917
  3. 2000步骤为: 0.9198
  4. 3000步骤为: 0.9206
  5. 4000步骤为: 0.9228
  6. 5000步骤为: 0.9198
  7. 6000步骤为: 0.9119
  8. 7000步骤为: 0.9199
  9. 8000步骤为: 0.9232
  10. 9000步骤为: 0.9218



bp神经网络:

 
    
  1. import tensorflow as tf
  2. import numpy as np
  3. def add_layer(inputs,in_size,out_size,activation_function=None):
  4. Weights=tf.Variable(tf.random_normal([in_size,out_size]))
  5. biases=tf.Variable(tf.zeros([1,out_size])+0.1)
  6. Wx_plus_b=tf.matmul(inputs,Weights)+biases
  7. if activation_function==None:
  8. outputs=Wx_plus_b
  9. else:
  10. outputs=activation_function(Wx_plus_b)
  11. return outputs
  12. x_data=np.linspace(-1,1,300)[:,np.newaxis] #300*1,输入只有一个神经元
  13. noise=np.random.normal(0,0.05,x_data.shape)
  14. y_data=np.square(x_data)-0.5+noise
  15. xs=tf.placeholder(tf.float32,[None,1])
  16. ys=tf.placeholder(tf.float32,[None,1])
  17. #定义隐含层,隐含层有10个神经元
  18. l1=add_layer(xs,1,10,activation_function=tf.nn.relu)
  19. #定义输出层,假设没有任何激活函数
  20. prediction=add_layer(l1,10,1,activation_function=None)
  21. loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
  22. train_step=tf.train.GradientDescentOptimizer(0.1).minimize(loss)
  23. init=tf.global_variables_initializer()
  24. with tf.Session() as sess:
  25. sess.run(init)
  26. for i in range(3000):
  27. sess.run(train_step,feed_dict={
  28. xs:x_data,ys:y_data
  29. })
  30. if i%100==0:
  31. print(sess.run(loss,feed_dict={
  32. xs:x_data,ys:y_data
  33. }))


结果:

 
    
  1. 0.898771
  2. 0.00805174
  3. 0.00672437
  4. 0.00613227
  5. 0.00571695
  6. 0.00533702
  7. 0.00494347
  8. 0.00450889
  9. 0.00418779
  10. 0.00394219
  11. 0.00373838

你可能感兴趣的:(python编程,机器学习)