代码:

import tensorflow as tf
import numpy as np
import xlrd
import matplotlib.pyplot as plt DATA_FILE = 'fire_theft.xls' # 1.read from data file
book=xlrd.open_workbook(DATA_FILE,encoding_override="utf-8")
sheet=book.sheet_by_index(0)
data=np.asarray([sheet.row_values(i) for i in range(1,sheet.nrows)])
n_samples=sheet.nrows-1 # 2.creat placeholders for input x(number of file) and label Y(number of theft)
X=tf.placeholder(tf.float32,name='X')
Y=tf.placeholder(tf.float32,name='Y') # 3.creat weight and bias ,init to 0
w=tf.Variable(0.0,name='weights')
b=tf.Variable(0.0,name='bias') # 4.build model to predict Y
Y_predicted = X* w +b # 5.use square error as the lose function
loss=tf.square(Y-Y_predicted,name='loss') # 6.using gradient descent with learning rate 0.01 to minimize loss
optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss) with tf.Session() as sess:
# 7.init necessary variables (w and b)
sess.run(tf.global_variables_initializer()) writer=tf.summary.FileWriter('./my_graph/linear_reg',sess.graph) # 8.train the model 100 times
for i in range(100):
total_loss =0
for x,y in data:
#session runs train_op and fetch values of loss
_,l=sess.run([optimizer,loss],feed_dict={X:x,Y:y})
total_loss +=l
print('Epoch {0}:{1}'.format(i,total_loss/n_samples)) # close the writer
writer.close() # 9.output the value of w and b
w_value,b_value=sess.run([w,b]) # plot the result
X,Y=data.T[0],data.T[1]
plt.plot(X,Y,'bo',label='Real data')
plt.plot(X,X*w_value+b_value,'r',label='Predected data')
plt.legend()
plt.show()
fire_theft.xls

                                                         

图例:

TFboard:                                  tensorboard --logdir="./my_graph/linear_reg" --port 6006

												

最新文章

  1. [EF2]Sneak Preview: Persistence Ignorance and POCO in Entity Framework 4.0
  2. Nginx模块之———— RTMP 模块的在线统计功能 stat 数据流数据的获取(不同节点则获取的方式不同)
  3. lecture3-线性神经元和算法
  4. Mac xcode 编译产生app的路径
  5. Mysql log_slave_updates 参数
  6. VC6兼容性及打开文件崩溃问题解决
  7. 3月25日 javascript练习
  8. bloom filter与dawgdic(一种trie树)
  9. Activiti工作流框架——快速上手
  10. Linux下设置MySql自动启动
  11. C/C++中 # 的神奇作用:把宏参数字符串化/贴合宏参数
  12. 编译和运行dubbo-admin管理平台
  13. 【转载】Xpath定位方法深入探讨及元素定位失败常见情况
  14. Jenkins系列之三——centos7.4+GitLab+Jenkins部署
  15. 18位身份证验证(Java)
  16. Python实现随机读取文本N行数据
  17. 怎样让HTML 表格中内容自动换行??
  18. java代码中实现android背景选择的selector-StateListDrawable的应用
  19. 几个shell程序设计小知识(shell常识部分)
  20. MUI事件管理

热门文章

  1. docker安装中附带安装的其他软件
  2. Java学习之字符串类
  3. 爬虫:Scrapy6 - Item Loaders
  4. Spring整合hibernate -SessionFactory
  5. 【转】DontDestroyOnLoad(Unity3D开发之五)
  6. Mysql架构之主从复制
  7. 【05】react 之 组件state
  8. duilib入门简明教程 -- XML配置界面(6) (转)
  9. 学习good taste代码
  10. DCP port