机器学习历程——人工智能基础与应用导论 专题篇(Scikit-learn)

机器学习历程——人工智能基础与应用导论 专题篇(Scikit-learn),第1张

一、介绍 1、官网

是针对Python 编程语言的免费软件机器学习库 。它具有各种分类,回归和聚类算法,包括支持向量机,随机森林,梯度提升,k均值和DBSCAN,并且旨在与Python数值科学库NumPy和SciPy联合使用。

英文社区:scikit-learn: machine learning in Python — scikit-learn 1.0.2 documentation

中文社区:scikit-learn中文社区

2、安装

pip install -U scikit-learn

二、回归分析 1、分类

2、建模过程

• 1.导入数据

• 2.划分训练集和测试并训练模型 (对X做标准化)

 • 3.模型预测

• 4.将训练好的测试集和原始测试集绘图比较

• 5.回归模型评价

回归模型的性能评估不同于分类模型,虽然都是对照真实值进行评估,但是由于回归模型的预测结果和真实值都是连续的,所以不能求取Precision、recal和F1值等评价指标,回归模型拥有一套独立的评价指标。

3、回归模型评价指标

(1)平均绝对误差(Mean Absolute Error, MAE)——0.0

是模型预测值 f(x) 与样本真实值 y 之间距离的平均值

(2)平均绝对误差(Mean Absolute Error, MAE)——0.0

实际值与估计值距离差的平方和的均值——衡量样本整体与模型预测值偏离程度

(3)均方根误差(Root Mean Squared Error,RMSE)——0.0

(4)R2——1.0

三、例题——波士顿房价预测 1、数据介绍

•date:日期

• CRIM: 城镇人均犯罪率

• ZN: 住宅用地所占比例

• INDUS: 城镇中非住宅用地所占比例

• CHAS: 虚拟变量,用于回归分析

• NOX: 环保指数

• RM: 每栋住宅的房间数

• AGE: 1940 年以前建成的自住单位的比例

• DIS: 距离 5 个波士顿的就业中心的加权距离

• RAD: 距离高速公路的便利指数

• TAX: 每一万美元的不动产税率

• PTRATIO: 城镇中的教师学生比例

• B: 城镇中的黑人比例

• LSTAT: 地区中有多少房东属于低收入人群

2、代码1
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 24 10:51:15 2022

@author: Administrator
"""

from sklearn.linear_model import LinearRegression
from sklearn import preprocessing
from sklearn.metrics import r2_score
import pandas as pd
import numpy as np # 数组np.array()
import matplotlib.pyplot as plt

# 从excel读取数据
boston = pd.read_csv('boston.csv',index_col=[0],header=0,parse_dates = True,encoding='gbk')

# 将第一行名字读取(除最后一列名称)
# 行:index,列:columns
# 行:axis=0,列:axis=1
name_data = boston.columns[:-1] 
x_data = boston[name_data] #获取自变量
y_data = boston['Price'] #获取因变量

# 创建数组
x_da = np.array(x_data)
y_da = np.array(y_data)  

#数据可视化
# 循环
for i in range(13):
    plt.subplot(7,2,i+1) #将画布分组,7行,2列,i+1为所在组块
    plt.scatter(x_da[:,i],y_data,s=20,c = 'blue') #横轴:x_da[:,i],纵轴:x_da[:,i],点的大小:s,颜色:c
    plt.title(name_data[i]) #图标的名称
    plt.show #展示图表
# RM LSTAT PTRATIO相关性大——因变量受自变量的的影响大

# 异常值处理
# 存储房价等于50为异常值
i_=[] # 创建空列表
for i in range(len(y_data)):
    if y_da[i] == 50:
        i_.append(i) #存储房价等于50的异常值下标
        
x_da = np.delete(x_da,i_,axis=0) #删除房价等于50的样本的特性
y_da = np.delete(y_da,i_,axis=0) #删除房价等于50的样本的房价

# 次要特征(存储)
j_=[]
for i in range(13):
    if name_data[i] == 'RM'or name_data[i]=='PTRATIO'or name_data[i]=='LSTAT':
        continue  #遇到上述特征跳过去
    j_.append(i) 

x_da = np.delete(x_da,j_,axis=1) #删掉除了次要特征之外的数据

x_train = x_da[:int(0.8*len(x_da))] #X的训练集(占0.8)
x_test = x_da[int(0.8*len(x_da)):] #X的测试集(占0.2)
y_train = y_da[:int(0.8*len(x_da))] #Y的训练集(占0.8)
y_test = y_da[int(0.8*len(x_da)):] #Y的测试集(占0.2)

# 数据归一化(最大-最小值法)
min_max_scaler = preprocessing.MinMaxScaler()
x_train = min_max_scaler.fit_transform(x_train)
x_test = min_max_scaler.fit_transform(x_test)
y_train = min_max_scaler.fit_transform(y_train.reshape(-1,1))
y_test = min_max_scaler.fit_transform(y_test.reshape(-1,1))

# 训练线性回归模型
clf = LinearRegression().fit(x_train,y_train)
# 用测试集测试
y_pred = clf.predict(x_test)

#使用R2_score对模型评估
score = r2_score(y_test,y_pred)
print(score)
2、代码2
# -*- coding: utf-8 -*-
"""
Created on Wed Mar  2 16:34:16 2022

@author: lenovo
"""
from sklearn.linear_model import LinearRegression
from sklearn import preprocessing
from sklearn.metrics import r2_score
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 编写函数
def bostonprediction(x,y):
    
    min_max_scaler = preprocessing.MinMaxScaler()
    x = min_max_scaler.fit_transform(x)
    y = min_max_scaler.fit_transform(y.reshape(-1,1))
    
    clf = LinearRegression().fit(x[:-1],y[:-1])
    y_pred = clf.predict([x[-1]])
    y_true = y[-1]
    return(y_pred,y_true)

boston = pd.read_csv('boston.csv',index_col=[0],header=0,parse_dates = True,encoding='gbk')

name_data = boston.columns[:-1]
x_data = boston[name_data]
y_data = boston['Price']

x_da = np.array(x_data)
y_da = np.array(y_data)  

##滑动窗口(是固定窗口大小,进行滑动计算):Sliding window
y_pred=[]
y_tr=[]
wind = int(0.8*len(x_da)) #划分训练集、测试集界限
for i in range(wind,len(x_da)):
    x_d= x_da[i-wind:i]
    y_d = y_da[i-wind:i]
    [y1,y2] = bostonprediction(x_d,y_d)
    # 逐一追加
    y_pred.append(y1)
    y_tr.append(y2)

##类似cumsum()函数的累计求和:Expanding window
y_pred1=[]
y_tr1=[]
wind = int(0.8*len(x_da))
for i in range(wind,len(x_da)):
    x_d= x_da[:i]
    y_d = y_da[:i]
    [y3,y4] = bostonprediction(x_d,y_d)
    y_pred1.append(y3)
    y_tr1.append(y4)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/868605.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存