机器学习1:线性回归模型解决波士顿房价预测和研究生入学率问题

Python机器学习实战1:使用线性回归模型来解决波士顿房价预测和研究生入学率问题

在这里插入图片描述

boston房价预测

导入库

from  sklearn.linear_model import LinearRegression
from  sklearn.datasets import load_boston
import matplotlib.pyplot as plt
%matplotlib inline

获取数据集

bosten = load_boston()

线性回归

  • 模型训练
clf = LinearRegression()
clf.fit(bosten.data[:,5:6],bosten.target)  #模型训练
x = bosten.data[:,5:6]
  • 回归系数
clf.coef_  
array([9.10210898])
  • 预测值
y_pre = clf.predict(bosten.data[:,5:6])  #模型的输出值
  • 可视化
plt.scatter(x,bosten.target)
plt.plot(x,y_pre)
plt.show()

在这里插入图片描述

研究生入学率

导入库

import pandas as pd
from sklearn.linear_model import LogisticRegression  #逻辑回归
from sklearn.model_selection import train_test_split  #测试集训练集分割
from sklearn.metrics import classification_report

导入数据

data = pd.read_csv(r"LogisticRegression.csv")
data_tr,data_te,label_tr,label_te = train_test_split(data.iloc[:,1:],data["admit"],test_size = 0.2)
data.iloc[:,1:]
gregparank
03803.613
16603.673
28004.001
36403.194
45202.934
............
3956204.002
3965603.043
3974602.632
3987003.652
3996003.893

400 rows × 3 columns

data_tr.head()
gregparank
2525204.002
946603.442
415803.322
28004.001
2076403.631
data_te.head()
gregparank
454603.453
3116603.672
3916603.882
3577203.311
1177003.722

模型训练

clf = LogisticRegression()
clf.fit(data_tr,label_tr)  #模型训练
pre = clf.predict(data_te) #模型预测
  • 预测出来的标签,label_te实际值
pre  
array([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int64)
  • sklearn中的classification_report函数用于显示主要分类指标的文本报告.在报告中显示每个类的精确度,召回率,F1值等信息。
res = classification_report(label_te,pre)
print(res)
              precision    recall  f1-score   support

           0       0.71      0.89      0.79        56
           1       0.40      0.17      0.24        24

    accuracy                           0.68        80
   macro avg       0.56      0.53      0.51        80
weighted avg       0.62      0.68      0.63        80

推荐阅读

  1. 使用Python完成时间序列分析基础
  2. SPSS建立时间序列乘法季节模型实战案例
  3. Python建立时间序列ARIMA模型实战案例

到这里就结束了,如果对你有帮助你,欢迎点赞关注,你的点赞对我很重要

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
波士顿房价数据集是一个经典的数据集,用于线性回归模型的训练和评估。下面是使用Python和Scikit-learn库来实现波士顿房价预测的步骤: 1. 导入所需库和数据集 ```python import numpy as np import pandas as pd from sklearn.datasets import load_boston boston = load_boston() X = pd.DataFrame(boston.data, columns=boston.feature_names) y = pd.DataFrame(boston.target, columns=['MEDV']) ``` 2. 数据预处理 ```python # 查看数据集信息 print(X.info()) # 查看数据集统计信息 print(X.describe()) # 查看缺失值情况 print(X.isnull().sum()) # 将数据集分为训练集和测试集 from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 对训练集和测试集进行标准化处理 from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train) X_test_scaled = scaler.transform(X_test) ``` 3. 构建线性回归模型 ```python from sklearn.linear_model import LinearRegression lr = LinearRegression() lr.fit(X_train_scaled, y_train) ``` 4. 模型评估 ```python # 计算训练集和测试集上的R2得分 print('Training R2 score:', lr.score(X_train_scaled, y_train)) print('Testing R2 score:', lr.score(X_test_scaled, y_test)) # 计算训练集和测试集上的均方误差 from sklearn.metrics import mean_squared_error y_train_pred = lr.predict(X_train_scaled) y_test_pred = lr.predict(X_test_scaled) print('Training Mean Squared Error:', mean_squared_error(y_train, y_train_pred)) print('Testing Mean Squared Error:', mean_squared_error(y_test, y_test_pred)) ``` 5. 使用模型进行预测 ```python # 构造一组新的房屋属性数据 new_house = np.array([6.320e-03, 1.800e+01, 2.310e+00, 0.000e+00, 5.380e-01, 6.575e+00, 6.520e+01, 4.090e+00, 1.000e+00, 2.960e+02, 1.530e+01, 3.969e+02, 4.980e+00]).reshape(1, -1) new_house_scaled = scaler.transform(new_house) # 使用模型进行预测 price_pred = lr.predict(new_house_scaled) print('Predicted price:', price_pred[0]) ``` 以上就是使用线性回归模型进行波士顿房价预测的完整代码。注意,这只是一个简单的示例,实际应用中可能需要更复杂的特征工程和模型调参。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北山啦

这个功能还没人试过呢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值