【机器学习】线性回归预测

前言

回归分析就是用于预测输入变量(自变量)和输出变量(因变量)之间的关系,特别当输入的值发生变化时,输出变量值也发生改变!回归简单来说就是对数据进行拟合。线性回归就是通过线性的函数对数据进行拟合。机器学习并不能实现预言,只能实现简单的预测。我们这次对房价关于其他因素的关系。

波士顿房价预测

下载相关数据集

  • 数据集是506行14列的波士顿房价数据集,数据集是开源的。
wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data',out= 'housing.data')
wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.names',out='housing.names')
wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/Index',out='Index')

对数据集进行处理


feature_names = ['CRIM','ZN','INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT','MEDV']
feature_num = len(feature_names)
print(feature_num)

把7084 变为506*14
housing_data = housing_data.reshape(housing_data.shape[0]//feature_num,feature_num)
print(housing_data.shape[0])
打印第一行数据
print(housing_data[:1])

## 归一化

feature_max = housing_data.max(axis=0)
feature_min = housing_data.min(axis=0)
feature_avg = housing_data.sum(axis=0)/housing_data.shape[0]

模型定义

## 实例化模型
def Model():
    model = linear_model.LinearRegression()
    return model

拟合模型
def train(model,x,y):
    model.fit(x,y)

可视化模型效果

def draw_infer_result(groud_truths,infer_results):
    title = 'Boston'
    plt.title(title,fontsize=24)
    x = np.arange(1,40)
    y = x
    plt.plot(x,y)
    plt.xlabel('groud_truth')
    plt.ylabel('infer_results')
    plt.scatter(groud_truths,infer_results,edgecolors='green',label='training cost')
    plt.grid()
    plt.show()

整体代码

## 基于线性回归实现房价预测
## 拟合函数模型
## 梯度下降方法

## 开源房价策略数据集

import wget
import numpy as np
import os
import matplotlib
import matplotlib.pyplot as plt

import pandas as pd

from sklearn import  linear_model

## 下载之后注释掉
'''
wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data',out= 'housing.data')
wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.names',out='housing.names')
wget.download(url='https://archive.ics.uci.edu/ml/machine-learning-databases/housing/Index',out='Index')
'''
'''
    1. CRIM      per capita crime rate by town
    2. ZN        proportion of residential land zoned for lots over
                 25,000 sq.ft.

    3. INDUS     proportion of non-retail business acres per town
    4. CHAS      Charles River dummy variable (= 1 if tract bounds
                 river; 0 otherwise)
    5. NOX       nitric oxides concentration (parts per 10 million)
    6. RM        average number of rooms per dwelling
    7. AGE       proportion of owner-occupied units built prior to 1940
    8. DIS       weighted distances to five Boston employment centres
    9. RAD       index of accessibility to radial highways
    10. TAX      full-value property-tax rate per $10,000
    11. PTRATIO  pupil-teacher ratio by town
    12. B        1000(Bk - 0.63)^2 where Bk is the proportion of blacks
                 by town
    13. LSTAT    % lower status of the population
    14. MEDV     Median value of owner-occupied homes in $1000's
'''
## 数据加载

datafile = './housing.data'

housing_data = np.fromfile(datafile,sep=' ')

print(housing_data.shape)

feature_names = ['CRIM','ZN','INDUS','CHAS','NOX','RM','AGE','DIS','RAD','TAX','PTRATIO','B','LSTAT','MEDV']
feature_num = len(feature_names)
print(feature_num)

把7084 变为506*14
housing_data = housing_data.reshape(housing_data.shape[0]//feature_num,feature_num)
print(housing_data.shape[0])
打印第一行数据
print(housing_data[:1])

## 归一化

feature_max = housing_data.max(axis=0)
feature_min = housing_data.min(axis=0)
feature_avg = housing_data.sum(axis=0)/housing_data.shape[0]

def feature_norm(input):
    f_size = input.shape
    output_features = np.zeros(f_size,np.float32)
    for batch_id in range(f_size[0]):
        for index in range(13):
            output_features[batch_id][index] = (input[batch_id][index]-feature_avg[index])/(feature_max[index]-feature_min[index])

    return output_features

housing_features = feature_norm(housing_data[:,:13])

housing_data = np.c_[housing_features,housing_data[:,-1]].astype(np.float32)

## 划分数据集  8:2
ratio =0.8

offset = int(housing_data.shape[0]*ratio)

train_data = housing_data[:offset]
test_data = housing_data[offset:]

print(train_data[:2])

## 模型配置
## 线性回归

## 实例化模型
def Model():
    model = linear_model.LinearRegression()
    return model

拟合模型
def train(model,x,y):
    model.fit(x,y)

## 模型训练

X, y = train_data[:,:13], train_data[:,-1:]

model = Model()
train(model,X,y)

x_test, y_test = test_data[:,:13], test_data[:,-1:]
prefict = model.predict(x_test)

## 模型评估

infer_results = []
groud_truths = []

def draw_infer_result(groud_truths,infer_results):
    title = 'Boston'
    plt.title(title,fontsize=24)
    x = np.arange(1,40)
    y = x
    plt.plot(x,y)
    plt.xlabel('groud_truth')
    plt.ylabel('infer_results')
    plt.scatter(groud_truths,infer_results,edgecolors='green',label='training cost')
    plt.grid()
    plt.show()

draw_infer_result(y_test,prefict)

效果展示

【机器学习】线性回归预测

总结

线性回归预测还是比较简单的,可以简单理解为函数拟合,数据集是使用的开源的波士顿房价的数据集,算法也是打包好的包,方便我们引用。

Original: https://www.cnblogs.com/hjk-airl/p/16405474.html
Author: hjk-airl
Title: 【机器学习】线性回归预测

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/810092/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • Scrapy笔记,基本的流程与方法介绍

    安装 pip install scrapy有时候会有错误,cryptograph库存在问题 进入rust网站,下载自己的系统版本https://www.rust-lang.org/…

    Python 2023年10月3日
    054
  • 纯numpy实现多标签多分类进行验证码识别

    在我之前的两篇博客中,讲解了使用纯numpy实现手写数字识别以及采用keras的多标签多分类进行验证码识别,建议阅读这篇文章之前提前看下另外两篇博客。 卷积神经网络实现手写数字识别…

    Python 2023年8月25日
    067
  • 2021-07-30(数据分析第三次作业)

    ### 回答1: 北邮linux的第三次上机 作业_是在系统管理课程中所进行的,主要涵盖了对Linux系统的进程管理、文件系统扩展、定时任务、用户和组管理等方面的学习。 在进程管理…

    Python 2023年8月9日
    058
  • 头歌平台-机器学习-11.神经网络

    EduCoder:机器学习—神经网络 第1关:什么是神经网络 ; 第2关:神经元与感知机 编程要求: 根据提示,在右侧编辑器补充 python 代码,构建一个感知机模型,底层代码会…

    Python 2023年8月3日
    0151
  • Python ❀ 字典

    ​​1、字典使用​​ ​​1.1 访问字典内的值​​ ​​1.2 添加一个键值对​​ ​​1.3 创建一个空白字典​​ ​​1.4 删除键值对或字典​​ ​​2、字典遍历​​ ​​…

    Python 2023年5月25日
    079
  • 命名空间+作用域

    Python 2023年5月24日
    078
  • 【Python】CUDA11.6安装PyTorch三件套

    由于PyTorch 官网没有提供除适配CUDA10.3和11.3之外的安装方式,因此可以使用 Nightly Binaries方式下载与自己CUDA版本合适的PyTorch 以CU…

    Python 2023年8月1日
    091
  • git 的使用

    git 的使用 1、介绍 代码版本管理、协同开发 对文件(代码)进行版本管理 完成协同开发 项目,帮助程序员整合代码 i)帮助开发者合并开发的代码 ii)如果出现冲突代码的合并,会…

    Python 2023年6月10日
    097
  • SMBMS(超市订单管理系统)项目从零开始搭建

    如果需要完整的系统可以加我qq:1842329236 一、搭建一个maven web项目 新建一个maven,并且使用模板 maven的详细创建,及配置请看这篇文章https://…

    Python 2023年6月9日
    079
  • 规则引擎深度对比,LiteFlow vs Drools!

    🚀 优质资源分享 🚀 学习路线指引(点击解锁)知识定位人群定位🧡 Python实战微信订餐小程序 🧡 进阶级本课程是python flask+微信小程序的完美结合,从项目搭建到腾讯…

    Python 2023年8月13日
    053
  • 利用python实现Apriori关联规则算法

    关联规则 大家可能听说过用于宣传数据挖掘的一个案例:啤酒和尿布;据说是沃尔玛超市在分析顾客的购买记录时,发现许多客户购买啤酒的同时也会购买婴儿尿布,于是超市调整了啤酒和尿布的货架摆…

    Python 2023年10月9日
    092
  • python安装matplotlib绘图库

    学习目录 一、简介 二、应用 三、安装 一、简介 Matplotlib 是 Python 的绘图库,它能让使用者很轻松地将数据图形化,并且提供多样化的输出格式。Matplotlib…

    Python 2023年9月2日
    042
  • python dataframe函数添加行名称_Python pandas.DataFrame.to_records函数方法的使用

    DataFrame.to_records(index=True, column_dtypes=None, index_dtypes=None) 将DataFrame转换为一个Num…

    Python 2023年8月7日
    063
  • 这几个 Python 小游戏,上班摸鱼我能玩一天 | 内附源码

    文 | 豆豆 来源:Python 技术「ID: pythonall」 不知不觉今年已经要过完一半了,都知道今年整体的大环境真的非常差,以至于上班也没有啥激情了。 刚好六一儿童节快到…

    Python 2023年9月20日
    061
  • Jinja2模板语言最基础入门

    flask默认使用的模板引擎是jinja2,它是一个功能齐全的python模板引擎,除了设置变量,还允许我们添加if判断,执行for循环,调用函数等。以各种方式控制模板的输出。对应…

    Python 2023年8月13日
    071
  • alphalens 使用总结(一)

    Quantopian是国外著名的量化交易平台,早期聚宽就是仿照这个网站开发的,算是这类平台的鼻祖了,可惜Quantopian最近刚宣布要停止运营了。Quantopian开发了许多优…

    Python 2023年8月18日
    0175
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球