数据:fetch_california_housing(加利福尼亚的房价数据)

1、解析解法

  1. import tensorflow as tf
  2. import numpy as np
  3. from sklearn.datasets import fetch_california_housing
  4.  
  5. # 立刻下载数据集
  6. housing = fetch_california_housing(data_home="./datasets", download_if_missing=True)
  7. # 获得X数据行数和列数
  8. m, n = housing.data.shape
  9. # 这里添加一个额外的bias输入特征(x0=1)到所有的训练数据上面,因为使用的numpy所有会立即执行
  10. housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
  11. # 创建两个TensorFlow常量节点X和y,去持有数据和标签
  12. X = tf.constant(housing_data_plus_bias, dtype=tf.float32, name='X')
  13. y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name='y')
  14. # 使用一些TensorFlow框架提供的矩阵操作去求theta
  15. XT = tf.transpose(X)
  16. # 解析解一步计算出最优解
  17. theta = tf.matmul(tf.matmul(tf.matrix_inverse(tf.matmul(XT, X)), XT), y)
  18. with tf.Session() as sess:
  19. theta_value = theta.eval() # sess.run(theta)
  20. print(theta_value)

2、梯度下降法(BSD)

  1. import tensorflow as tf
  2. import numpy as np
  3. from sklearn.datasets import fetch_california_housing
  4. from sklearn.preprocessing import StandardScaler
  5.  
  6. n_epochs = 10000
  7. learning_rate = 0.01
  8.  
  9. housing = fetch_california_housing(data_home="./datasets", download_if_missing=False)
  10. m, n = housing.data.shape
  11. housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
  12. # 可以使用TensorFlow或者Numpy或者sklearn的StandardScaler去进行归一化
  13. # StandardScaler默认就做了方差归一化,和均值归一化,这两个归一化的目的都是为了更快的进行梯度下降
  14. # 你如何构建你的训练集,你训练除了的模型,就具备什么样的功能!
  15. scaler = StandardScaler().fit(housing_data_plus_bias)
  16. scaled_housing_data_plus_bias = scaler.transform(housing_data_plus_bias)
  17.  
  18. X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name='X')
  19. y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name='y')
  20.  
  21. # random_uniform函数创建图里一个节点包含随机数值,给定它的形状和取值范围,就像numpy里面rand()函数
  22. theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0), name='theta')
  23. y_pred = tf.matmul(X, theta, name="predictions")
  24. error = y_pred - y
  25. mse = tf.reduce_mean(tf.square(error), name="mse")
  26. # 梯度的公式:(y_pred - y) * xj
  27. gradients = 2/m * tf.matmul(tf.transpose(X), error)
  28. # 赋值函数对于BGD来说就是 theta_new = theta - (learning_rate * gradients)
  29. training_op = tf.assign(theta, theta - learning_rate * gradients)
  30.  
  31. init = tf.global_variables_initializer()
  32.  
  33. with tf.Session() as sess:
  34. sess.run(init)
  35.  
  36. for epoch in range(n_epochs):
  37. if epoch % 100 == 0:
  38. print("Epoch", epoch, "MSE = ", mse.eval())
  39. sess.run(training_op)
  40.  
  41. best_theta = theta.eval()
  42. print(best_theta)

3、TensorFlow内部封装迭代

  1. import tensorflow as tf
  2. import numpy as np
  3. from sklearn.datasets import fetch_california_housing
  4. from sklearn.preprocessing import StandardScaler
  5.  
  6. # 前面的代码执行的不错,但是它需要数学上通过损失函数MSE来求导梯度
  7. # 在线性回归的例子中,这样是可以的,看起来通过数学公式去求解不难
  8. # 但是如果是深度学习,我们很难这样去做,会比较头疼,会很容易出错
  9. # 幸运的是,TensorFlow提供的autodiff特性可以自动的并有效的计算梯度为我们
  10. # reverse-mode autodiff
  11.  
  12. n_epochs = 1000
  13. learning_rate = 0.01
  14.  
  15. housing = fetch_california_housing()
  16. m, n = housing.data.shape
  17. housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
  18. # 可以使用TensorFlow或者Numpy或者sklearn的StandardScaler去进行归一化
  19. scaler = StandardScaler().fit(housing_data_plus_bias)
  20. scaled_housing_data_plus_bias = scaler.transform(housing_data_plus_bias)
  21.  
  22. X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name='X')
  23. y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name='y')
  24.  
  25. # random_uniform函数创建图里一个节点包含随机数值,给定它的形状和取值范围,就像numpy里面rand()函数
  26. theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0), name='theta')
  27. y_pred = tf.matmul(X, theta, name="predictions")
  28. error = y_pred - y
  29. mse = tf.reduce_mean(tf.square(error), name="mse")
  30. # 梯度的公式:(y_pred - y) * xj
  31. # gradients = 2/m * tf.matmul(tf.transpose(X), error)
  32. gradients = tf.gradients(mse, [theta])[0]
  33. # 赋值函数对于BGD来说就是 theta_new = theta - (learning_rate * gradients)
  34. training_op = tf.assign(theta, theta - learning_rate * gradients)
  35.  
  36. init = tf.global_variables_initializer()
  37.  
  38. with tf.Session() as sess:
  39. sess.run(init)
  40.  
  41. for epoch in range(n_epochs):
  42. if epoch % 100 == 0:
  43. print("Epoch", epoch, "MSE = ", mse.eval())
  44. sess.run(training_op)
  45.  
  46. best_theta = theta.eval()
  47. print(best_theta)

4、使用优化器

  1. import tensorflow as tf
  2. import numpy as np
  3. from sklearn.datasets import fetch_california_housing
  4. from sklearn.preprocessing import StandardScaler
  5.  
  6. # TensorFlow为我们去计算梯度,但是同时也给了我们更方便的求解方式
  7. # 它提供给我们与众不同的,有创意的一些优化器,包括梯度下降优化器
  8. # 替换前面代码相应的行,并且一切工作正常
  9.  
  10. # 设定超参数,Grid Search进行栅格搜索,其实说白了就是排列组合找到Loss Function最小的时刻
  11. # 的那组超参数结果
  12. n_epochs = 1000
  13. learning_rate = 0.01
  14.  
  15. # 读取数据,这里读取数据是一下子就把所有数据交给X,Y节点,所以下面去做梯度下降的时候
  16. # BGD = Batch Gradient Decrease ,如果面向数据集比较大的时候,我们倾向与 Mini GD
  17. housing = fetch_california_housing(data_home="./datasets", download_if_missing=False)
  18. m, n = housing.data.shape
  19. housing_data_plus_bias = np.c_[np.ones((m, 1)), housing.data]
  20. # 可以使用TensorFlow或者Numpy或者sklearn的StandardScaler去进行归一化
  21. scaler = StandardScaler().fit(housing_data_plus_bias)
  22. scaled_housing_data_plus_bias = scaler.transform(housing_data_plus_bias)
  23.  
  24. # 下面部分X,Y最后用placeholder可以改成使用Mini BGD
  25. # 构建计算的图
  26. X = tf.constant(scaled_housing_data_plus_bias, dtype=tf.float32, name='X')
  27. y = tf.constant(housing.target.reshape(-1, 1), dtype=tf.float32, name='y')
  28.  
  29. # random_uniform函数创建图里一个节点包含随机数值,给定它的形状和取值范围,就像numpy里面rand()函数
  30. theta = tf.Variable(tf.random_uniform([n + 1, 1], -1.0, 1.0), name='theta')
  31. y_pred = tf.matmul(X, theta, name="predictions")
  32. error = y_pred - y
  33. mse = tf.reduce_mean(tf.square(error), name="mse")
  34. # 梯度的公式:(y_pred - y) * xj
  35. # gradients = 2/m * tf.matmul(tf.transpose(X), error)
  36. # gradients = tf.gradients(mse, [theta])[0]
  37. # 赋值函数对于BGD来说就是 theta_new = theta - (learning_rate * gradients)
  38. # training_op = tf.assign(theta, theta - learning_rate * gradients)
  39.  
  40. optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
  41. # MomentumOptimizer收敛会比梯度下降更快
  42. # optimizer = tf.train.MomentumOptimizer(learning_rate=learning_rate, momentum=0.9)
  43. training_op = optimizer.minimize(mse)
  44.  
  45. init = tf.global_variables_initializer()
  46.  
  47. # 下面是开始训练
  48. with tf.Session() as sess:
  49. sess.run(init)
  50.  
  51. for epoch in range(n_epochs):
  52. if epoch % 100 == 0:
  53. print("Epoch", epoch, "MSE = ", mse.eval())
  54. sess.run(training_op)
  55.  
  56. best_theta = theta.eval()
  57. print(best_theta)
  58.  
  59. # 最后还要进行模型的测试,防止过拟合

5、placeholder的使用

  1. import tensorflow as tf
  2.  
  3. # 让我们修改前面的代码去实现Mini-Batch梯度下降
  4. # 为了去实现这个,我们需要一种方式去取代X和y在每一次迭代中,使用一小批数据
  5. # 最简单的方式去做到这个是去使用placeholder节点
  6. # 这些节点特点是它们不真正的计算,它们只是在执行过程中你要它们输出数据的时候去输出数据
  7. # 它们会传输训练数据给TensorFlow在训练的时候
  8. # 如果在运行过程中你不给它们指定数据,你会得到一个异常
  9.  
  10. # 需要做的是使用placeholder()并且给输出的tensor指定数据类型,也可以选择指定形状
  11. # 如果你指定None对于某一个维度,它的意思代表任意大小
  12. A = tf.placeholder(tf.float32, shape=(None, 3))
  13. B = A + 5
  14.  
  15. with tf.Session() as sess:
  16. B_val_1 = B.eval(feed_dict={A: [[1, 2, 3]]})
  17. B_val_2 = B.eval(feed_dict={A: [[", 5, 6], [7, 8, 9]]})
  18.  
  19. print(B_val_1)
  20. print(B_val_2)

TensorFlow实现回归的更多相关文章

  1. 10分钟搞懂Tensorflow 逻辑回归实现手写识别

    1. Tensorflow 逻辑回归实现手写识别 1.1. 逻辑回归原理 1.1.1. 逻辑回归 1.1.2. 损失函数 1.2. 实例:手写识别系统 1.1. 逻辑回归原理 1.1.1. 逻辑回归 ...

  2. 使用Tensorflow搭建回归预测模型之一:环境安装

    方法1:快速包安装 一.安装Anaconda 1.官网地址:https://www.anaconda.com/distribution/,选择其中一个版本下载即可,最好安装3.7版本,因为2.7版本2 ...

  3. 使用Tensorflow搭建回归预测模型之二:数据准备与预处理

    前言: 在前一篇中,已经搭建好了Tensorflow环境,本文将介绍如何准备数据与预处理数据. 正文: 在机器学习中,数据是非常关键的一个环节,在模型训练前对数据进行准备也预处理是非常必要的. 一.数 ...

  4. 吴裕雄 python 神经网络——TensorFlow实现回归模型训练预测MNIST手写数据集

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_dat ...

  5. TensorFlow从0到1之TensorFlow逻辑回归处理MNIST数据集(17)

    本节基于回归学习对 MNIST 数据集进行处理,但将添加一些 TensorBoard 总结以便更好地理解 MNIST 数据集. MNIST由https://www.tensorflow.org/get ...

  6. 2.tensorflow——Softmax回归

    import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from tensorflow.examples. ...

  7. 利用Tensorflow实现逻辑回归模型

    官方mnist代码: #下载Mnist数据集 import tensorflow.examples.tutorials.mnist.input_data mnist = input_data.read ...

  8. 第24月第30天 scrapy《TensorFlow机器学习项目实战》项目记录

    1.Scrapy https://www.imooc.com/learn/1017 https://github.com/pythonsite/spider/tree/master/jobboleSp ...

  9. 用Tensorflow完成简单的线性回归模型

    思路:在数据上选择一条直线y=Wx+b,在这条直线上附件随机生成一些数据点如下图,让TensorFlow建立回归模型,去学习什么样的W和b能更好去拟合这些数据点. 1)随机生成1000个数据点,围绕在 ...

随机推荐

  1. 【消息中间件之RabbitMQ学习】-开篇-001

    写在前面的话 项目中因为要用到消息中间件,当初极力推荐RabbitMq.但因为种种原因,最终选型为java+mongodb自实现一套分布式的消.没有用RabbitMq工作过,实属遗憾.因为个人来说实在 ...

  2. 07_mysql常用sql语句

    一.数据库相关 1.创建数据库: mysql> create database test default character set utf8 collate utf8_general_ci;Q ...

  3. Vue中添加新的路由并访问

    1.搭建好Vue脚手架(这里使用的版本是Vue2.0) 2.在代码编辑器(这里使用的是Sublime Text)打开项目文件夹 3.在文件目录src中的component下创建一个新的vue页面,写入 ...

  4. docker3

    Docker容器的设置资源(cpu,内存)限制: #docker  run –memory=200M xxxx-image  --vm 1 –verbose #docker  run  --cpu-s ...

  5. android 事件绑定

    layout布局设计了页面,如何绑定事件,与用户进行交互需要在Activity中进行处理. 下面的layout,有两个按钮. <LinearLayout android:layout_width ...

  6. InstallShield 软件打包完整教程(含添加自定义依赖环境)

    任务说明:公司一个绿色版的软件,为安装部署是需要很多的环境依赖,如 DevExpress..net4.5.WinRAR等,客户提出安装复杂,并且有漏装后无法启动等情况,现将绿色版转安装版,并将依赖环境 ...

  7. SQL练习题-50道SQL练习题及答案与详细分析

    网上流传较广的50道SQL训练,奋斗了不知道多久终于写完了.前18道题的难度依次递增,从19题开始的后半部分算是循环练习和额外function的附加练习,难度恢复到普通状态.第9题非常难,我反正没有写 ...

  8. Codeforces 1105B:Zuhair and Strings(字符串水题)

    time limit per test: 1 second memory limit per test: 256 megabytes input: standard input output: sta ...

  9. xlistview长按

    //XListView的长摁事件 xlistview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @O ...

  10. P2257 莫比乌斯+整除分块

    #include<bits/stdc++.h> #define ll long long using namespace std; ; int vis[maxn]; int mu[maxn ...