import numpy as np
import pandas as pd
from Udacity.model_check.boston_house_price import visuals as vs # Supplementary code
from sklearn.model_selection import ShuffleSplit # Pretty display for notebooks
# 让结果在notebook中显示 # Load the Boston housing dataset
# 载入波士顿房屋的数据集
data = pd.read_csv('housing.csv')
prices = data['MEDV']
features = data.drop('MEDV', axis=1)
# print(data.describe())
# Success
# 完成
print("Boston housing dataset has {} data points with {} variables each.".format(*data.shape))
# 目标:计算价值的最小值
minimum_price = np.min(data['MEDV']) # 目标:计算价值的最大值
maximum_price = np.max(data['MEDV']) # 目标:计算价值的平均值
mean_price = np.mean(data['MEDV']) # 目标:计算价值的中值
median_price = np.median(data['MEDV']) # 目标:计算价值的标准差
std_price = np.std(data['MEDV']) # 目标:输出计算的结果
print("Statistics for Boston housing dataset:\n")
print("Minimum price: ${:,.2f}".format(minimum_price))
print("Maximum price: ${:,.2f}".format(maximum_price))
print("Mean price: ${:,.2f}".format(mean_price))
print("Median price ${:,.2f}".format(median_price))
print("Standard deviation of prices: ${:,.2f}".format(std_price))
# RM,LSTAT,PTRATIO,MEDV
"""
初步分析结果是
1.RM越大MEDV越大
2.LSTATA越大MEDV越小
3.PTRATIO越大MEDV越小
""" # TODO: Import 'r2_score'
def performance_metric(y_true, y_predict):
""" Calculates and returns the performance score between
true and predicted values based on the metric chosen. """
from sklearn.metrics import r2_score
# TODO: Calculate the performance score between 'y_true' and 'y_predict' score = r2_score(y_true,y_predict) # Return the score
return score # score = performance_metric([3, -0.5, 2, 7, 4.2], [2.5, 0.0, 2.1, 7.8, 5.3])
# print ("Model has a coefficient of determination, R^2, of {:.3f}.".format(score)) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(features, prices, test_size=0.80, random_state=1) # Success
print ("Training and testing split was successful.")
# vs.ModelLearning(features, prices) def fit_model(X, y):
""" Performs grid search over the 'max_depth' parameter for a
decision tree regressor trained on the input data [X, y]. """
from sklearn.tree import DecisionTreeRegressor from sklearn.model_selection import KFold
# Create cross-validation sets from the training data
cross_validator = KFold(10)
# cv_sets = ShuffleSplit(X.shape[0], test_size=0.20, random_state=0) # TODO: Create a decision tree regressor object
regressor = DecisionTreeRegressor() # TODO: Create a dictionary for the parameter 'max_depth' with a range from 1 to 10
max_depth = [1,2,3,4,5,6,7,8,9,10]
params = {"max_depth":max_depth}
from sklearn.metrics import make_scorer
# TODO: Transform 'performance_metric' into a scoring function using 'make_scorer'
scoring_fnc = make_scorer(performance_metric)
from sklearn.model_selection import GridSearchCV
# TODO: Create the grid search object
grid = GridSearchCV(regressor,params,scoring_fnc,cv=cross_validator) # Fit the grid search object to the data to compute the optimal model
grid = grid.fit(X, y) # Return the optimal model after fitting the data
return grid.best_estimator_ reg = fit_model(X_train, y_train) # Produce the value for 'max_depth'
print ("Parameter 'max_depth' is {} for the optimal model.".format(reg.get_params()['max_depth'])) client_data = [[5, 17, 15], # Client 1
[4, 32, 22], # Client 2
[8, 3, 12]] # Client 3 # Show predictions
for i, price in enumerate(reg.predict(client_data)):
print ("Predicted selling price for Client {}'s home: ${:,.2f}".format(i+1, price))

【udacity】机器学习-波士顿房价预测的更多相关文章

  1. 【udacity】机器学习-波士顿房价预测小结

    Evernote Export 机器学习的运行步骤 1.导入数据 没什么注意的,成功导入数据集就可以了,打印看下数据的标准格式就行 用个info和describe 2.分析数据 这里要详细分析数据的内 ...

  2. 波士顿房价预测 - 最简单入门机器学习 - Jupyter

    机器学习入门项目分享 - 波士顿房价预测 该分享源于Udacity机器学习进阶中的一个mini作业项目,用于入门非常合适,刨除了繁琐的部分,保留了最关键.基本的步骤,能够对机器学习基本流程有一个最清晰 ...

  3. 机器学习实战二:波士顿房价预测 Boston Housing

    波士顿房价预测 Boston housing 这是一个波士顿房价预测的一个实战,上一次的Titantic是生存预测,其实本质上是一个分类问题,就是根据数据分为1或为0,这次的波士顿房价预测更像是预测一 ...

  4. Python之机器学习-波斯顿房价预测

    目录 波士顿房价预测 导入模块 获取数据 打印数据 特征选择 散点图矩阵 关联矩阵 训练模型 可视化 波士顿房价预测 导入模块 import pandas as pd import numpy as ...

  5. Tensorflow之多元线性回归问题(以波士顿房价预测为例)

    一.根据波士顿房价信息进行预测,多元线性回归+特征数据归一化 #读取数据 %matplotlib notebook import tensorflow as tf import matplotlib. ...

  6. 《用Python玩转数据》项目—线性回归分析入门之波士顿房价预测(二)

    接上一部分,此篇将用tensorflow建立神经网络,对波士顿房价数据进行简单建模预测. 二.使用tensorflow拟合boston房价datasets 1.数据处理依然利用sklearn来分训练集 ...

  7. chapter02 回归模型在''美国波士顿房价预测''问题中实践

    #coding=utf8 # 从sklearn.datasets导入波士顿房价数据读取器. from sklearn.datasets import load_boston # 从sklearn.mo ...

  8. 基于sklearn的波士顿房价预测_线性回归学习笔记

    > 以下内容是我在学习https://blog.csdn.net/mingxiaod/article/details/85938251 教程时遇到不懂的问题自己查询并理解的笔记,由于sklear ...

  9. 02-11 RANSAC算法线性回归(波斯顿房价预测)

    目录 RANSAC算法线性回归(波斯顿房价预测) 一.RANSAC算法流程 二.导入模块 三.获取数据 四.训练模型 五.可视化 更新.更全的<机器学习>的更新网站,更有python.go ...

随机推荐

  1. 基于Mysql-Proxy 实现MariaDB 读写分离

    一.Mysql-Proxy 简单介绍 MySQL-Proxy是一个处于你的client端和MySQL server端之间的简单程序,它可以监测.分析或改变它们的通信.它使用灵活,没有限制,常见的用途包 ...

  2. 对Django框架中Cookie的简单理解

    概念的理解:首先Cookie和Session一样,是django中用于视图保持状态的方案之一.为什么要进行视图保留呢,这是因为浏览器在向服务器发出请求时,服务器不会像人一样,有记忆,服务器像鱼一样,在 ...

  3. n!最末尾非0数

    最小周期串:如果s是ss的周期串,那么ss就可以表示成几个周期的s,如果s是ss的最小周期串,那么s就是ss的周期串中最小的一个.例,ZgxZgxZgxZgx的最小周期串是Zgx.{很好理解} 给你一 ...

  4. 关于double类型数字相加位数发生变化的问题

     因为计算机内部存贮本身的缺陷,导致double类型的数字相加.得到的结果有非常多位,比方 774.23 750.0 2638.66 4162.889999999999 看到这个是不是非常晕 当然 ...

  5. Codeforces Round #256 (Div. 2) B

    B. Suffix Structures Bizon the Champion isn't just a bison. He also is a favorite of the "Bizon ...

  6. 逻辑运算0==x和x==0具体解释

    看很多大牛写的程序经常看到if(0==x){运行体},而自己写的程序常用if(x==0){运行体}.刚開始的时候我还非常自信的觉得这样的表达方式是等价的,大牛们仅仅是为了显摆下与众不同的格调.当读到C ...

  7. mybits 操作指南

    第一.一对一: <resultMap type="com.zktx.platform.entity.tb.Module" id="BaseResultMap&quo ...

  8. linux udev 机制【转】

    本文转载自:http://blog.csdn.net/yyt8yyt8/article/details/8020154 1. Linux的热插拔事件由kernel通过中断发现(比如,USB设备插入系统 ...

  9. Test Doubles - Fakes, Mocks and Stubs.

    https://dev.to/milipski/test-doubles---fakes-mocks-and-stubs This text was originally posted at Prag ...

  10. 现代英特尔® 架构上的 TensorFlow* 优化——正如去年参加Intel AI会议一样,Intel自己提供了对接自己AI CPU优化版本的Tensorflow,下载链接见后,同时可以基于谷歌官方的tf版本直接编译生成安装包

    现代英特尔® 架构上的 TensorFlow* 优化 转自:https://software.intel.com/zh-cn/articles/tensorflow-optimizations-on- ...