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

前言

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

波士顿房价预测

下载相关数据集

  • 数据集是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)

效果展示

image

总结

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

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:【机器学习】线性回归预测 - Python技术站

(0)
上一篇 2023年4月2日 下午5:26
下一篇 2023年4月2日

相关文章

  • 【机器学习】支持向量机分类

    前言 支持向量机是一类按监督学习方式对数据进行二元分类的广义线性分类器,其决策边界是对学习样本求解的最大边距超平面。SVM尝试寻找一个最优决策边界,使距离两个类别最近的样本最远。SVM使用铰链损失函数计算经验风险并在求解系统中加入了正则化项以优化结构风险,是一个具有稀疏性和稳健性的分类器 。SVM可以通过核方法(kernel method)进行非线性分类,是…

    2023年4月2日
    00
  • 【机器学习】K-means聚类分析

    前言 聚类问题是无监督学习的问题,算法思想就是物以类聚,人以群分,聚类算法感知样本间的相似度,进行类别归纳,对新输入进行输出预测,输出变量取有限个离散值。本次我们使用两种方法对鸢尾花数据进行聚类。 无监督就是没有标签的进行分类 K-means 聚类算法 K-means聚类算法(k-均值或k-平均)聚类算法。算法思想就是首先随机确定k个中心点作为聚类中心,然后…

    2023年4月2日
    00
  • 【深度学习】DNN房价预测

    前言 我们使用深度学习网络实现波士顿房价预测,深度学习的目的就是寻找一个合适的函数输出我们想要的结果。深度学习实际上是机器学习领域中一个研究方向,深度学习的目标是让机器能够像人一样具有分析学习的能力,能够识别文字、图像、声音等数据。我认为深度学习与机器学习最主要的区别就是神经元。 深度学习中重要内容 建立模型——神经元 基本构造 一个神经元对应一组权重w,a…

    2023年4月2日
    00
  • 【机器学习】手写数字识别

    前言 logistic回归,是一个分类算法,可以处理二元分类,多元分类。我们使用sklearn中的logistic对手写数字识别进行实践。 数据集 MNIST数据集来自美国国家标准与技术研究所,训练集由250个不同人手写数字构成,50%高中学生,50%来自人口普查局。 数据集展示 数据集下载 百度云盘:链接:https://pan.baidu.com/s/1…

    2023年4月2日
    00
  • 【机器学习】数据准备–python爬虫

    前言 我们在学习机器学习相关内容时,一般是不需要我们自己去爬取数据的,因为很多的算法学习很友好的帮助我们打包好了相关数据,但是这并不代表我们不需要进行学习和了解相关知识。在这里我们了解三种数据的爬取:鲜花/明星图像的爬取、中国艺人图像的爬取、股票数据的爬取。分别对着三种爬虫进行学习和使用。 体会 个人感觉爬虫的难点就是URL的获取,URL的获取与自身的经验有…

    2023年4月2日
    00
合作推广
合作推广
分享本页
返回顶部