TensorFlow 房价预测
TensorFlow 房价预测
以下资料来源于极客时间学习资料
• 房价预测模型介绍
• 使用 TensorFlow 实现房价预测模型
数据分析库:Pandas
测试代码:
单变量房价预测 import pandas as pd import seaborn as sns sns.set(context="notebook", style="whitegrid", palette="dark")df0 = pd.read_csv('data0.csv', names=['square', 'price']) sns.lmplot('square', 'price', df0, height=6, fit_reg=True)
df0.info() df0 ''' <class 'pandas.core.frame.DataFrame'> RangeIndex: 47 entries, 0 to 46 Data columns (total 2 columns): square 47 non-null int64 price 47 non-null int64 dtypes: int64(2) memory usage: 832.0 bytes '''
多变量房价预测 import matplotlib.pyplot as pltfrom mpl_toolkits import mplot3ddf1 = pd.read_csv('data1.csv', names=['square', 'bedrooms', 'price']) df1.head()
fig = plt.figure() # 创建一个 Axes3D object ax = plt.axes(projection='3d') # 设置 3 个坐标轴的名称 ax.set_xlabel('square') ax.set_ylabel('bedrooms') ax.set_zlabel('price') # 绘制 3D 散点图 # 通过字典的方式取 DataFrame 的列 # 参数 c 表示随着 price 值越大点的颜色越深,cmap即为颜色 ax.scatter3D(df1['square'], df1['bedrooms'], df1['price'], c=df1['price'], cmap='Greens')
数据规范化 def normalize_feature(df):return df.apply(lambda column: (column - column.mean()) / column.std())df = normalize_feature(df1) df.head()
ax = plt.axes(projection='3d') ax.set_xlabel('square') ax.set_ylabel('bedrooms') ax.set_zlabel('price') ax.scatter3D(df['square'], df['bedrooms'], df['price'], c=df['price'], cmap='Reds')
df.info() ''' <class 'pandas.core.frame.DataFrame'> RangeIndex: 47 entries, 0 to 46 Data columns (total 3 columns): square 47 non-null float64 bedrooms 47 non-null float64 price 47 non-null float64 dtypes: float64(3) memory usage: 1.2 KB '''数据处理:添加 ones 列(x0) import numpy as np ones = pd.DataFrame({'ones': np.ones(len(df))})# ones是n行1列的数据框,表示x0恒为1 ones.info() ''' <class 'pandas.core.frame.DataFrame'> RangeIndex: 47 entries, 0 to 46 Data columns (total 1 columns): ones 47 non-null float64 dtypes: float64(1) memory usage: 456.0 bytes '''df = pd.concat([ones, df], axis=1) # 根据列合并数据
df.head()
df.info()''' <class 'pandas.core.frame.DataFrame'> RangeIndex: 47 entries, 0 to 46 Data columns (total 4 columns): ones 47 non-null float64 square 47 non-null float64 bedrooms 47 non-null float64 price 47 non-null float64 dtypes: float64(4) memory usage: 1.5 KB '''
import pandas as pd import numpy as npdef normalize_feature(df):return df.apply(lambda column: (column - column.mean()) / column.std())df = normalize_feature(pd.read_csv('data1.csv',names=['square', 'bedrooms', 'price']))ones = pd.DataFrame({'ones': np.ones(len(df))})# ones是n行1列的数据框,表示x0恒为1 df = pd.concat([ones, df], axis=1) # 根据列合并数据 df.head()
数据处理:获取 X 和 y X_data = np.array(df[df.columns[0:3]]) y_data = np.array(df[df.columns[-1]]).reshape(len(df), 1)print(X_data.shape, type(X_data)) print(y_data.shape, type(y_data)) ''' (47, 3) <class 'numpy.ndarray'> (47, 1) <class 'numpy.ndarray'> '''创建线性回归模型(数据流图) import tensorflow as tfalpha = 0.01 # 学习率 alpha epoch = 500 # 训练全量数据集的轮数# 输入 X,形状[47, 3] X = tf.placeholder(tf.float32, X_data.shape) # 输出 y,形状[47, 1] y = tf.placeholder(tf.float32, y_data.shape)# 权重变量 W,形状[3,1] W = tf.get_variable("weights", (X_data.shape[1], 1), initializer=tf.constant_initializer())# 假设函数 h(x) = w0*x0+w1*x1+w2*x2, 其中x0恒为1 # 推理值 y_pred 形状[47,1] y_pred = tf.matmul(X, W)# 损失函数采用最小二乘法,y_pred - y 是形如[47, 1]的向量。 # tf.matmul(a,b,transpose_a=True) 表示:矩阵a的转置乘矩阵b,即 [1,47] X [47,1] # 损失函数操作 loss loss_op = 1 / (2 * len(X_data)) * tf.matmul((y_pred - y), (y_pred - y), transpose_a=True) # 随机梯度下降优化器 opt opt = tf.train.GradientDescentOptimizer(learning_rate=alpha) # 单轮训练操作 train_op train_op = opt.minimize(loss_op)创建会话(运行环境) with tf.Session() as sess:# 初始化全局变量 sess.run(tf.global_variables_initializer())# 开始训练模型,# 因为训练集较小,所以每轮都使用全量数据训练for e in range(1, epoch + 1):sess.run(train_op, feed_dict={X: X_data, y: y_data})if e % 10 == 0:loss, w = sess.run([loss_op, W], feed_dict={X: X_data, y: y_data})log_str = "Epoch %d \t Loss=%.4g \t Model: y = %.4gx1 + %.4gx2 + %.4g"print(log_str % (e, loss, w[1], w[2], w[0]))''' Epoch 10 Loss=0.4116 Model: y = 0.0791x1 + 0.03948x2 + 3.353e-10 Epoch 20 Loss=0.353 Model: y = 0.1489x1 + 0.07135x2 + -5.588e-11 Epoch 30 Loss=0.3087 Model: y = 0.2107x1 + 0.09676x2 + 3.912e-10 Epoch 40 Loss=0.2748 Model: y = 0.2655x1 + 0.1167x2 + -1.863e-11 Epoch 50 Loss=0.2489 Model: y = 0.3142x1 + 0.1321x2 + 1.77e-10 Epoch 60 Loss=0.2288 Model: y = 0.3576x1 + 0.1436x2 + -4.47e-10 Epoch 70 Loss=0.2131 Model: y = 0.3965x1 + 0.1519x2 + -8.103e-10 Epoch 80 Loss=0.2007 Model: y = 0.4313x1 + 0.1574x2 + -6.985e-10 Epoch 90 Loss=0.1908 Model: y = 0.4626x1 + 0.1607x2 + -4.936e-10 Epoch 100 Loss=0.1828 Model: y = 0.4909x1 + 0.1621x2 + -6.147e-10 Epoch 110 Loss=0.1763 Model: y = 0.5165x1 + 0.162x2 + -7.87e-10 Epoch 120 Loss=0.1709 Model: y = 0.5397x1 + 0.1606x2 + -5.821e-10 Epoch 130 Loss=0.1664 Model: y = 0.5609x1 + 0.1581x2 + -9.08e-10 Epoch 140 Loss=0.1625 Model: y = 0.5802x1 + 0.1549x2 + -9.965e-10 Epoch 150 Loss=0.1592 Model: y = 0.5979x1 + 0.1509x2 + -9.756e-10 Epoch 160 Loss=0.1564 Model: y = 0.6142x1 + 0.1465x2 + -4.144e-10 Epoch 170 Loss=0.1539 Model: y = 0.6292x1 + 0.1416x2 + -1.001e-10 Epoch 180 Loss=0.1518 Model: y = 0.643x1 + 0.1364x2 + -3.236e-10 Epoch 190 Loss=0.1498 Model: y = 0.6559x1 + 0.131x2 + -6.286e-11 Epoch 200 Loss=0.1481 Model: y = 0.6678x1 + 0.1255x2 + 2.119e-10 Epoch 210 Loss=0.1466 Model: y = 0.6789x1 + 0.1199x2 + -1.956e-10 Epoch 220 Loss=0.1452 Model: y = 0.6892x1 + 0.1142x2 + -1.758e-10 Epoch 230 Loss=0.1439 Model: y = 0.6989x1 + 0.1085x2 + -4.307e-11 Epoch 240 Loss=0.1428 Model: y = 0.708x1 + 0.1029x2 + 3.376e-10 Epoch 250 Loss=0.1418 Model: y = 0.7165x1 + 0.09736x2 + 2.841e-10 Epoch 260 Loss=0.1408 Model: y = 0.7245x1 + 0.09189x2 + 3.295e-10 Epoch 270 Loss=0.14 Model: y = 0.732x1 + 0.08653x2 + -8.033e-11 Epoch 280 Loss=0.1392 Model: y = 0.7391x1 + 0.08128x2 + 1.141e-10 Epoch 290 Loss=0.1385 Model: y = 0.7458x1 + 0.07616x2 + 1.321e-10 Epoch 300 Loss=0.1378 Model: y = 0.7522x1 + 0.07118x2 + 5.087e-10 Epoch 310 Loss=0.1372 Model: y = 0.7582x1 + 0.06634x2 + 7.398e-10 Epoch 320 Loss=0.1367 Model: y = 0.7639x1 + 0.06165x2 + 6.845e-10 Epoch 330 Loss=0.1362 Model: y = 0.7693x1 + 0.0571x2 + 8.423e-10 Epoch 340 Loss=0.1357 Model: y = 0.7744x1 + 0.0527x2 + 9.252e-10 Epoch 350 Loss=0.1353 Model: y = 0.7793x1 + 0.04845x2 + 1.104e-09 Epoch 360 Loss=0.1349 Model: y = 0.784x1 + 0.04435x2 + 1.145e-09 Epoch 370 Loss=0.1346 Model: y = 0.7884x1 + 0.0404x2 + 1.631e-09 Epoch 380 Loss=0.1343 Model: y = 0.7926x1 + 0.03658x2 + 1.446e-09 Epoch 390 Loss=0.134 Model: y = 0.7966x1 + 0.03291x2 + 1.429e-09 Epoch 400 Loss=0.1337 Model: y = 0.8004x1 + 0.02938x2 + 1.694e-09 Epoch 410 Loss=0.1334 Model: y = 0.8041x1 + 0.02598x2 + 1.697e-09 Epoch 420 Loss=0.1332 Model: y = 0.8076x1 + 0.02271x2 + 2.125e-09 Epoch 430 Loss=0.133 Model: y = 0.8109x1 + 0.01957x2 + 2.292e-09 Epoch 440 Loss=0.1328 Model: y = 0.8141x1 + 0.01655x2 + 2.913e-09 Epoch 450 Loss=0.1326 Model: y = 0.8171x1 + 0.01366x2 + 3.412e-09 Epoch 460 Loss=0.1325 Model: y = 0.82x1 + 0.01087x2 + 3.749e-09 Epoch 470 Loss=0.1323 Model: y = 0.8228x1 + 0.008204x2 + 3.499e-09 Epoch 480 Loss=0.1322 Model: y = 0.8254x1 + 0.005641x2 + 3.663e-09 Epoch 490 Loss=0.1321 Model: y = 0.828x1 + 0.003183x2 + 4.2e-09 Epoch 500 Loss=0.132 Model: y = 0.8304x1 + 0.0008239x2 + 4.138e-09 '''
• 使用 TensorBoard 可视化模型数据流图
D:\Program Files\jupyter notebook\TensorFlow\TensorFlowTest\chapter-4\summary>tensorboard --logdir ./ --host localhost
import pandas as pd import numpy as npdef normalize_feature(df):return df.apply(lambda column: (column - column.mean()) / column.std())df = normalize_feature(pd.read_csv('data1.csv',names=['square', 'bedrooms', 'price']))ones = pd.DataFrame({'ones': np.ones(len(df))})# ones是n行1列的数据框,表示x0恒为1 df = pd.concat([ones, df], axis=1) # 根据列合并数据 X_data = np.array(df[df.columns[0:3]]) y_data = np.array(df[df.columns[-1]]).reshape(len(df), 1)print(X_data.shape, type(X_data)) print(y_data.shape, type(y_data))''' (47, 3) <class 'numpy.ndarray'> (47, 1) <class 'numpy.ndarray'> '''创建线性回归模型(数据流图) import tensorflow as tfalpha = 0.01 # 学习率 alpha epoch = 500 # 训练全量数据集的轮数 with tf.name_scope('input'):# 输入 X,形状[47, 3]X = tf.placeholder(tf.float32, X_data.shape, name='X')# 输出 y,形状[47, 1]y = tf.placeholder(tf.float32, y_data.shape, name='y')with tf.name_scope('hypothesis'):# 权重变量 W,形状[3,1]W = tf.get_variable("weights",(X_data.shape[1], 1),initializer=tf.constant_initializer())# 假设函数 h(x) = w0*x0+w1*x1+w2*x2, 其中x0恒为1# 推理值 y_pred 形状[47,1]y_pred = tf.matmul(X, W, name='y_pred')with tf.name_scope('loss'):# 损失函数采用最小二乘法,y_pred - y 是形如[47, 1]的向量。# tf.matmul(a,b,transpose_a=True) 表示:矩阵a的转置乘矩阵b,即 [1,47] X [47,1]# 损失函数操作 lossloss_op = 1 / (2 * len(X_data)) * tf.matmul((y_pred - y), (y_pred - y), transpose_a=True) with tf.name_scope('train'):# 随机梯度下降优化器 opttrain_op = tf.train.GradientDescentOptimizer(learning_rate=alpha).minimize(loss_op)创建会话(运行环境) with tf.Session() as sess:# 初始化全局变量 sess.run(tf.global_variables_initializer())# 创建FileWriter实例,并传入当前会话加载的数据流图writer = tf.summary.FileWriter('./summary/linear-regression-1', sess.graph)# 开始训练模型# 因为训练集较小,所以每轮都使用全量数据训练for e in range(1, epoch + 1):sess.run(train_op, feed_dict={X: X_data, y: y_data})if e % 10 == 0:loss, w = sess.run([loss_op, W], feed_dict={X: X_data, y: y_data})log_str = "Epoch %d \t Loss=%.4g \t Model: y = %.4gx1 + %.4gx2 + %.4g"print(log_str % (e, loss, w[1], w[2], w[0]))# 关闭FileWriter的输出流 writer.close()''' Epoch 100 Loss=0.1835 Model: y = 0.4909x1 + 0.1621x2 + -6.147e-10 Epoch 200 Loss=0.1483 Model: y = 0.6678x1 + 0.1255x2 + 2.119e-10 Epoch 300 Loss=0.1379 Model: y = 0.7522x1 + 0.07118x2 + 5.087e-10 Epoch 400 Loss=0.1337 Model: y = 0.8004x1 + 0.02938x2 + 1.694e-09 Epoch 500 Loss=0.132 Model: y = 0.8304x1 + 0.0008239x2 + 4.138e-09 '''可视化损失值 print(len(loss_data)) ''' 500 '''import matplotlib.pyplot as plt import seaborn as sns sns.set(context="notebook", style="whitegrid", palette="dark")ax = sns.lineplot(x='epoch', y='loss', data=pd.DataFrame({'loss': loss_data, 'epoch': np.arange(epoch)})) ax.set_xlabel('epoch') ax.set_ylabel('loss') plt.show()
转载于:https://www.cnblogs.com/LXL616/p/11241847.html
TensorFlow 房价预测相关推荐
- 实战五:手把手教你用TensorFlow进行房价预测
实战TensorFlow房价预测 github地址 目录 房价预测模型介绍 使用TensorFlow实现房价预测模型 使用TensorBoard可视化模型数据流图 一.房价预测模型介绍 1.前置知识 ...
- sklearn中lstm_分别用sklearn和tensorflow做房价预测
原标题:分别用sklearn和tensorflow做房价预测 本篇是后面用tensorflow做回归时的一个参照,忍不住要说的是sklearn真是简单好用,要不是他没有卷积cnn等时髦模型,真是不想用 ...
- MOOC网深度学习应用开发1——Tensorflow基础、多元线性回归:波士顿房价预测问题Tensorflow实战、MNIST手写数字识别:分类应用入门、泰坦尼克生存预测
Tensorflow基础 tensor基础 当数据类型不同时,程序做相加等运算会报错,可以通过隐式转换的方式避免此类报错. 单变量线性回归 监督式机器学习的基本术语 线性回归的Tensorflow实战 ...
- 教你使用百度深度学习框架PaddlePaddle完成波士顿房价预测(新手向)
首先,本文是一篇纯新手向文章,我自己也只能算是入门,有说错的地方欢迎大家批评讨论 目录 一.人工智能.机器学习.深度学习 二.PaddlePaddle(飞桨) 三.波士顿房价预测模型 数据处理 模型设 ...
- 数据挖掘竞赛-美国King County房价预测训练赛
美国King County房价预测训练赛 简介 DC上的一个回归题(正经的回归题). 比较简单. 时间原因(暂时没什么时间看国内旧赛),看了一下网上的解答,改善了一下神经网络就提交了. 过程 数据获取 ...
- PaddlePaddle 波斯顿房价预测训练结果
paddlepaddle是百度提出来的深度学习的框架,个人感觉其实和tensorflow差不多(语法上面),因为本人也是初学者,也不是很懂tensorflow,所以,这些都是个人观点. 百度的padd ...
- 大数据毕业设计 LSTM时间序列预测算法 - 股票预测 天气预测 房价预测
文章目录 0 简介 1 基于 Keras 用 LSTM 网络做时间序列预测 2 长短记忆网络 3 LSTM 网络结构和原理 3.1 LSTM核心思想 3.2 遗忘门 3.3 输入门 3.4 输出门 4 ...
- 毕业设计 LSTM的预测算法 - 股票预测 天气预测 房价预测
文章目录 0 简介 1 基于 Keras 用 LSTM 网络做时间序列预测 2 长短记忆网络 3 LSTM 网络结构和原理 3.1 LSTM核心思想 3.2 遗忘门 3.3 输入门 3.4 输出门 4 ...
- LSTM预测算法(股票预测 天气预测 房价预测)
文章目录 0 简介 1 基于 Keras 用 LSTM 网络做时间序列预测 2 长短记忆网络 3 LSTM 网络结构和原理 3.1 LSTM核心思想 3.2 遗忘门 3.3 输入门 3.4 输出门 4 ...
最新文章
- oracle 两层table of,ORACLE中嵌套表的基本知识
- int*p[ ]与int(*p)[ ]的不同
- linux密码修改时间,linux 查看、修改用户及密码过期时间(示例代码)
- 旋转函数_一招搞定高中数学函数平移旋转问题
- Go如何按行读取文本
- linux非阻塞的socket EAGAIN的错误处理【转】
- cmd输入pip报错_使用Pip管理Python的包
- 苹果cms v10模板 蓝色简洁大气手机端模板
- 大话存储pdf 百度网盘_学用系列|亲身体验百度网盘内测在线文档,有遗憾也有期待...
- jQuery系列之目录汇总
- nginx的安装及简单负载均衡配置
- 适用于Windows的Xcode:在PC上安装Xcode的5种方法
- CentOS7自动发送邮件配置
- 7种大屏设计与布局思路,你不知道就亏了
- html-css10 过渡/米兔练习/动画/动画练习/小球动画/平移和小米移动图
- 用scrapy进行网页抓取
- MySQL 命令窗口
- winserver-记录共享文件夹操作日志
- java 开发用到网络爬虫,抓取汽车之家网站全部数据经历
- 西安电子科大计算机考研调剂,西安电子科技大学电子工程学院2020考研调剂信息...