需要TensorFlow基础,见TensorFlow(一)

原理默认了解不赘述

实例:

模型创建:

#!/usr/bin/python
# -*- coding: utf-8 -*
import tensorflow as tf
import numpy as np class linearRegressionModel: def __init__(self,x_dimen):
self.x_dimen = x_dimen
self._index_in_epoch = 0
self.constructModel()
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer()) #权重初始化
def weight_variable(self,shape):
initial = tf.truncated_normal(shape,stddev = 0.1)
return tf.Variable(initial) #偏置项初始化
def bias_variable(self,shape):
initial = tf.constant(0.1,shape = shape)
return tf.Variable(initial) #每次选取100个样本,如果选完,重新打乱
def next_batch(self,batch_size):
start = self._index_in_epoch
self._index_in_epoch += batch_size
if self._index_in_epoch > self._num_datas:
perm = np.arange(self._num_datas)
np.random.shuffle(perm)
self._datas = self._datas[perm]
self._labels = self._labels[perm]
start = 0
self._index_in_epoch = batch_size
assert batch_size <= self._num_datas
end = self._index_in_epoch
return self._datas[start:end],self._labels[start:end] def constructModel(self):
self.x = tf.placeholder(tf.float32, [None,self.x_dimen])
self.y = tf.placeholder(tf.float32,[None,1])
self.w = self.weight_variable([self.x_dimen,1])
self.b = self.bias_variable([1])
self.y_prec = tf.nn.bias_add(tf.matmul(self.x, self.w), self.b) mse = tf.reduce_mean(tf.squared_difference(self.y_prec, self.y))
l2 = tf.reduce_mean(tf.square(self.w))
self.loss = mse + 0.15*l2
self.train_step = tf.train.AdamOptimizer(0.1).minimize(self.loss) def train(self,x_train,y_train,x_test,y_test):
self._datas = x_train
self._labels = y_train
self._num_datas = x_train.shape[0]
for i in range(5000):
batch = self.next_batch(100)
self.sess.run(self.train_step,feed_dict={self.x:batch[0],self.y:batch[1]})
if i%10 == 0:
train_loss = self.sess.run(self.loss,feed_dict={self.x:batch[0],self.y:batch[1]})
print('step %d,test_loss %f' % (i,train_loss)) def predict_batch(self,arr,batch_size):
for i in range(0,len(arr),batch_size):
yield arr[i:i + batch_size] def predict(self, x_predict):
pred_list = []
for x_test_batch in self.predict_batch(x_predict,100):
pred = self.sess.run(self.y_prec, {self.x:x_test_batch})
pred_list.append(pred)
return np.vstack(pred_list)

训练模型并和 sklearn 库线性回归模型对比

#!/usr/bin/python
# -*- coding: utf-8 -* from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from sklearn.datasets import make_regression
from sklearn.linear_model import LinearRegression
from linear_regression_model import linearRegressionModel as lrm if __name__ == '__main__':
x, y = make_regression(7000)
x_train,x_test,y_train, y_test = train_test_split(x, y, test_size=0.5)
y_lrm_train = y_train.reshape(-1, 1)
y_lrm_test = y_test.reshape(-1, 1) linear = lrm(x.shape[1])
linear.train(x_train, y_lrm_train,x_test,y_lrm_test)
y_predict = linear.predict(x_test)
print("Tensorflow R2: ", r2_score(y_predict.ravel(), y_lrm_test.ravel())) lr = LinearRegression()
y_predict = lr.fit(x_train, y_train).predict(x_test)
print("Sklearn R2: ", r2_score(y_predict, y_test)) #采用r2_score评分函数

执行结果:

step 2410,test_loss 26.531937
step 2420,test_loss 26.542793
step 2430,test_loss 26.533974
step 2440,test_loss 26.530540
step 2450,test_loss 26.551474
step 2460,test_loss 26.541542
step 2470,test_loss 26.560783
step 2480,test_loss 26.538080
step 2490,test_loss 26.535666
('Tensorflow R2: ', 0.99999612588302389)
('Sklearn R2: ', 1.0)

tensorFlow(二)线性回归的更多相关文章

  1. tensorflow实现线性回归、以及模型保存与加载

    内容:包含tensorflow变量作用域.tensorboard收集.模型保存与加载.自定义命令行参数 1.知识点 """ 1.训练过程: 1.准备好特征和目标值 2.建 ...

  2. TensorFlow简单线性回归

    TensorFlow简单线性回归 将针对波士顿房价数据集的房间数量(RM)采用简单线性回归,目标是预测在最后一列(MEDV)给出的房价. 波士顿房价数据集可从http://lib.stat.cmu.e ...

  3. 深度学习入门实战(二)-用TensorFlow训练线性回归

    欢迎大家关注腾讯云技术社区-博客园官方主页,我们将持续在博客园为大家推荐技术精品文章哦~ 作者 :董超 上一篇文章我们介绍了 MxNet 的安装,但 MxNet 有个缺点,那就是文档不太全,用起来可能 ...

  4. 学习TensorFlow,线性回归模型

    学习TensorFlow,在MNIST数据集上建立softmax回归模型并测试 一.代码 <span style="font-size:18px;">from tens ...

  5. 利用TensorFlow实现线性回归模型

    准备数据: import numpy as np import tensorflow as tf import matplotlib.pylot as plt # 随机生成1000个点,围绕在y=0. ...

  6. tensorflow(二)----线程队列与io操作

    一.队列和线程 1.队列: 1).tf.FIFOQueue(capacity, dtypes, name='fifo_queue') 创建一个以先进先出的顺序对元素进行排队的队列 参数: capaci ...

  7. TensorFlow(二):基本概念以及练习

    一:基本概念 1.使用图(graphs)来表示计算任务 2.在被称之为会话(Session)的上下文(context)中执行图 3.使用tensor表示数据 4.通过变量(Variable)维护状态 ...

  8. tensorflow实现线性回归总结

    1.知识点 """ 模拟一个y = 0.7x+0.8的案例 报警: 1.initialize_all_variables (from tensorflow.python. ...

  9. [Python]机器学习:Tensorflow实现线性回归

    源码 #> tutorial:https://www.cnblogs.com/xianhan/p/9090426.html # 步骤一:构建模型 # 1.TensorFlow 中的线性模型 ## ...

  10. TensorFlow 多元线性回归【波士顿房价】

    1数据读取 1.1数据集解读 1.2引入包 %matplotlib notebook import tensorflow as tf import matplotlib.pyplot as plt i ...

随机推荐

  1. pyCharm添加自己的快捷代码

    1.首先打开pyCharm 2.打开Settings 3.输入live点击打开 Templates 4.选中python点击"+"号 5.选择Live Template 6.以打开 ...

  2. Thinkphp----------Thinkphp3.2的目录结构介绍

    ThinkPHP框架目录结构\index.php      入口文件\Application    应用目录\Public            资源文件目录\ThinkPHP      框架核心目录 ...

  3. lua 特殊时间格式转换

    [1]时间格式转换需求 工作中,因业务需要将时间格式进行转换.需求内容如下: 原格式:17:04:49.475  UTC Mon Mar 04 2019 转换格式:2019-03-04 17:04:4 ...

  4. PTA第三个编程题总结

    7-1 抓老鼠啊~亏了还是赚了? (20 分) 某地老鼠成灾,现悬赏抓老鼠,每抓到一只奖励10元,于是开始跟老鼠斗智斗勇:每天在墙角可选择以下三个操作:放置一个带有一块奶酪的捕鼠夹(T),或者放置一块 ...

  5. LinkedHashMap和HashTable

    LinkedHashMap: 继承了HashMap: 其中,key不允许重复是Map接口就有的性质: HashTable: 同步的,意味着是单线程,意味着线程安全的,但是速度慢,和List接口集合的子 ...

  6. oracle导出导入指定表

    从源数据库导出: exp user1/pwd@server1/orcl file=c:\temp\exp.dmp tables=(table1, table2) 导入到目标数据库: imp user2 ...

  7. vue 坑 checked 和v-model共用

    input type=checkbox 当使用v-model绑定某个变量了 ,只能通过绑定的这个变量来控制改input的value, 当:checked同时存在时 后者将无效: html <in ...

  8. Redis初探-Redis安装

    官网地址:https://redis.io/download 最新版本是4.0,在这里本人下的是3.2 使用rz命令可以将Redis上传到Linux系统 首先要确定Linux上是否安装了gcc,没有则 ...

  9. Linux操作oracle——关闭、停止、重启

    基础命令: 在此之前,先介绍一下切换到oracle用户的命令 su - oracle (注意空格) 一.启动监听.启动数据库1.1启动监听1.切换到oracle用户下 2.启动监听: lsnrctl ...

  10. WebApi 后台获取token值

    前台传递一个token,后台不知道怎么获取那么不是很悲剧吗. $(function () { $.ajax({ url: "/api/TokensTest/FirstCode", ...