美文网首页
波士顿房价预测 基础用法

波士顿房价预测 基础用法

作者: ss_6bda | 来源:发表于2018-07-13 23:14 被阅读33次

    1.导入模块

    import numpy as np

    import pandas as pd

    from pandas import Series,DataFrame

    import matplotlib.pyplot as plt

    %matplotlib inline

    import sklearn.datasets as datasets

    #机器算法模型

    from sklearn.neighbors import KNeighborsRegressor

    from sklearn.linear_model import LinearRegression

    from sklearn.linear_model import Ridge

    from sklearn.linear_model import Lasso

    from sklearn.tree import DecisionTreeRegressor

    from sklearn.svm import SVR

    #切割训练数据和样本数据

    from sklearn.model_selection import train_test_split

    #用于模型评分

    from sklearn.metrics import r2_score

    2.生成训练数据和测试数据

    boston = datasets.load_boston()

    train = boston.data

    target = boston.target

    #切割数据样本集合测试集

    X_train,x_test,y_train,y_true = train_test_split(train,target,test_size=0.2)

    3.创建学习模型

    knn = KNeighborsRegressor()

    linear = LinearRegression()

    ridge = Ridge()

    lasso = Lasso()

    decision = DecisionTreeRegressor()

    svr = SVR()

    4.训练模型

    knn.fit(X_train,y_train)

    linear.fit(X_train,y_train)

    ridge.fit(X_train,y_train)

    lasso.fit(X_train,y_train)

    decision.fit(X_train,y_train)

    svr.fit(X_train,y_train)

    5.预测数据

    y_pre_knn = knn.predict(x_test)

    y_pre_linear = linear.predict(x_test)

    y_pre_ridge = ridge.predict(x_test)

    y_pre_lasso = lasso.predict(x_test)

    y_pre_decision = decision.predict(x_test)

    y_pre_svr = svr.predict(x_test)

    6.评分

    knn_score = r2_score(y_true,y_pre_knn)

    linear_score=r2_score(y_true,y_pre_linear)

    ridge_score=r2_score(y_true,y_pre_ridge)

    lasso_score=r2_score(y_true,y_pre_lasso)

    decision_score=r2_score(y_true,y_pre_decision)

    svr_score=r2_score(y_true,y_pre_svr)

    display(knn_score,linear_score,ridge_score,lasso_score,decision_score,svr_score)

    7.绘图

    #KNN

    plt.plot(y_true,label='true')

    plt.plot(y_pre_knn,label='knn')

    plt.legend()

    #Linear

    plt.plot(y_true,label='true')

    plt.plot(y_pre_linear,label='linear')

    plt.legend()

    #Ridge

    plt.plot(y_true,label='true')

    plt.plot(y_pre_ridge,label='ridge')

    plt.legend()

    #lasso

    plt.plot(y_true,label='true')

    plt.plot(y_pre_lasso,label='lasso')

    plt.legend()

    #decision

    plt.plot(y_true,label='true')

    plt.plot(y_pre_decision,label='decision')

    plt.legend()

    #SVR

    plt.plot(y_true,label='true')

    plt.plot(y_pre_svr,label='svr')

    plt.legend()

    相关文章

      网友评论

          本文标题:波士顿房价预测 基础用法

          本文链接:https://www.haomeiwen.com/subject/hiqepftx.html