分享

logistic 逻辑回归

 雪柳花明 2017-03-15


[python] view plain copy
在CODE上查看代码片派生到我的代码片
  1. #!/usr/bin/env python  
  2. # coding=utf-8  
  3.   
  4. import numpy as np  
  5.   
  6. num_points=100  
  7. vectors_set=[]  
  8.   
  9. for idx in range(num_points):  
  10.     x1=np.random.normal(0.01)  
  11.     y1=1 if x1*0.3+0.1+np.random.normal(0.0,0.3)>0 else 0  
  12.     vectors_set.append([x1,y1])  
  13.   
  14. x_data=[v[0for v in vectors_set]  
  15. y_data=[v[1for v in vectors_set]  
  16.   
  17. import matplotlib.pyplot as plt  
  18.   
  19. plt.plot(x_data,y_data, 'ro', label="Original data")  
  20. plt.legend()  
  21. plt.show()  
  22.   
  23. #optimize linear regression with tensorflow  
  24. import tensorflow as tf  
  25.   
  26. W=tf.Variable(tf.random_uniform([1], -1.01.0))  
  27. b=tf.Variable(tf.zeros([1]))  
  28.   
  29. y=tf.sigmoid(W*x_data+b)  
  30. print('y.get_shape()', y.get_shape())  
  31.   
  32. #print(y.get_shape()[0])  
  33. one=tf.ones(y.get_shape(), dtype=tf.float32)  
  34. print(one.get_shape())  
  35.   
  36. loss=-tf.reduce_mean(y_data*tf.log(y)+(one-y_data)*tf.log(one-y))  
  37.   
  38. optimizer=tf.train.GradientDescentOptimizer(0.5)  
  39. train=optimizer.minimize(loss)  
  40.   
  41. init=tf.initialize_all_variables()  
  42. sess=tf.Session()  
  43. sess.run(init)  
  44.   
  45. #print sess.run(one)  
  46.   
  47. print 'params-before-training', sess.run(W), sess.run(b), '\n'  
  48.   
  49. thresholdvec=tf.ones_like(one, dtype=tf.float32)*0.5  
  50. print sess.run(thresholdvec)  
  51.   
  52. correct_prediction=tf.equal(tf.cast(y_data, tf.int32), tf.cast(tf.greater(y, thresholdvec),tf.int32))  
  53. accuracy=tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
  54.   
  55. for step in xrange(200):  
  56.     sess.run(train)  
  57.     if step %10 ==0:  
  58.         print('accuracy:', sess.run(accuracy))  
  59.         print'params', step, sess.run(W), sess.run(b), '\n'  










    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多