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. Spring Boot-全局异常处理(八)

    SpringBoot默认异常默认处理机制 Spring boot错误异常时通过BasicErrorController来处理的 通过判断是浏览器请求还是ajax请求响应页面或者json BasicEr ...

  2. JVM学习-jvm结构(一)

    java是跨平台的语言.一次编译多端使用.究竟是如何实现的呢 1.首先编译器会将java 文件编译成class文件.然后在不同的平台使用对应的虚拟机.不同虚拟机的内装载系统将class文件转换平台能执 ...

  3. 运行npm run watch时报:events.js:182 throw er; // Unhandled 'error' event

    I had this issue i did the following steps and i have no issues anymore: Delete node_modules directo ...

  4. ISAP 算法的学习

    http://www.renfei.org/blog/isap.html 算法与数学 网络流-最大流问题 ISAP 算法解释 2013-08-07Renfei Song 2 条评论 内容提要 [隐藏] ...

  5. spring-logback

    <?xml version="1.0" encoding="UTF-8"?><!-- 说明: 1.日志级别及文件 日志记录采用分级记录,级别与 ...

  6. Linux 3.14 待机流程分析

    1:待机节点创建 static int __init pm_init(void) { int error = pm_start_workqueue(); if (error) return error ...

  7. CodeForces 131C C (组合)

    There are n boys and m girls attending a theatre club. To set a play "The Big Bang Theory" ...

  8. 二重积分的计算 —— 交换积分顺序(exchange the order of integration)

    交换积分顺序的诀窍在数形结合: 1. 几句顺口溜 后积先定限,限内穿条线,先交下限写,后交上限见 先积 x,画横线(平行于 x 轴),右减左: 先积 y,画竖线(平行于 y 轴),上减下: 2. 简单 ...

  9. redis配置文件参数详解

    配置文件参数说明: 1. Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程 daemonize no 2. 当Redis以守护进程方式运行时,Redis默认会把pi ...

  10. mfs使用指引

    客户端工具集 mfsgetgoal #设定副本数 mfssetgoal #获取副本数 mfscopygoal # mfsgetsclass mfssetsclass mfscopysclass mfs ...