机器学习之分类回归模型(决策数、随机森林)

news2024/10/7 12:23:52

回归分析

回归分析属于监督学习方法的一种,主要用于预测连续型目标变量,可以预测、计算趋势以及确定变量之间的关系等

Regession Evaluation Metrics

以下是一些最流行的回归评估指标:
平均绝对误差(MAE):目标变量的预测值与实际值之间的平均绝对差值。
均方误差(MSE):目标变量的预测值与实际值之间的平均平方差。
均方根误差(RMSE):均方根误差的平方根。
Huber Loss:一种混合损失函数,在较大误差时从MAE过渡到MSE,在鲁棒性和MSE对异常值的敏感性之间提供平衡。
均方根对数误差
R2-Score

分类模型

决策树(监督分类回归模型)

分类树:该树用于确定目标变量在连续时最有可能落入哪个“类”。
回归树:用于预测连续变量的值。
在决策树中,节点根据属性的阈值划分为子节点。将根节点作为训练集,并根据最优属性和阈值将其分割为两个节点。此外,子集也使用相同的逻辑进行分割。这个过程一直持续,直到在树中找到最后一个纯子集,或者在该生长的树中找到最大可能的叶子数。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

根据分割指标和分割方法,可分为:ID3、C4.5、CART算法。
(1)ID3算法:以信息增益为准则来选择最优划分属性
信息增益的计算是基于信息熵(度量样本集合纯度的指标)
在这里插入图片描述
在这里插入图片描述
(2)C4.5基于信息增益率准则 选择最有分割属性的算法
在这里插入图片描述
3. CART:以基尼系数为准则选择最优划分属性,可用于分类和回归
基尼杂质-基尼杂质测量根据多数类标记的子集对随机实例进行错误分类的概率基尼不纯系数越低,意味着子集的纯度越高。分割标准- CART算法评估每个节点上的所有潜在分割,并选择最能减少结果子集的基尼杂质的分割。这个过程一直持续,直到达到一个停止条件,比如最大树深度或叶子节点中的最小实例数。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

sklearn.tree.DecisionTreeClassifier(分类)
class sklearn.tree.DecisionTreeClassifier(*, criterion='gini', splitter='best', max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0.0, max_features=None, random_state=None, max_leaf_nodes=None, min_impurity_decrease=0.0, class_weight=None, ccp_alpha=0.0)[source]

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
cancer = load_breast_cancer()
X_train, X_test, y_train, y_test = train_test_split(
    cancer.data, cancer.target, stratify=cancer.target, random_state=42)
tree = DecisionTreeClassifier(random_state=0)
tree.fit(X_train, y_train)
print("Accuracy on training set: {:.3f}".format(tree.score(X_train, y_train)))
print("Accuracy on test set: {:.3f}".format(tree.score(X_test, y_test)))
tree = DecisionTreeClassifier(max_depth=4, random_state=0)
tree.fit(X_train, y_train)

print("Accuracy on training set: {:.3f}".format(tree.score(X_train, y_train)))
print("Accuracy on test set: {:.3f}".format(tree.score(X_test, y_test)))
fig, axes = plt.subplots(2, 3, figsize=(20, 10))
for i, (ax, tree) in enumerate(zip(axes.ravel(), forest.estimators_)):
    ax.set_title("Tree {}".format(i))
    mglearn.plots.plot_tree_partition(X_train, y_train, tree, ax=ax)
    
mglearn.plots.plot_2d_separator(forest, X_train, fill=True, ax=axes[-1, -1],
                                alpha=.4)
axes[-1, -1].set_title("Random Forest")
mglearn.discrete_scatter(X_train[:, 0], X_train[:, 1], y_train)
def plot_feature_importances_cancer(model):
    n_features = cancer.data.shape[1]
    plt.barh(np.arange(n_features), model.feature_importances_, align='center')
    plt.yticks(np.arange(n_features), cancer.feature_names)
    plt.xlabel("Feature importance")
    plt.ylabel("Feature")
    plt.ylim(-1, n_features)

plot_feature_importances_cancer(tree)

在这里插入图片描述

from sklearn.tree import DecisionTreeClassifier
from sklearn.preprocessing import LabelEncoder
 
# Define the features and target variable
features = [
    ["red", "large"],
    ["green", "small"],
    ["red", "small"],
    ["yellow", "large"],
    ["green", "large"],
    ["orange", "large"],
]
target_variable = ["apple", "lime", "strawberry", "banana", "grape", "orange"]
 
# Flatten the features list for encoding
flattened_features = [item for sublist in features for item in sublist]
 
# Use a single LabelEncoder for all features and target variable
le = LabelEncoder()
le.fit(flattened_features + target_variable)
 
# Encode features and target variable
encoded_features = [le.transform(item) for item in features]
encoded_target = le.transform(target_variable)
 
# Create a CART classifier
clf = DecisionTreeClassifier()
 
# Train the classifier on the training set
clf.fit(encoded_features, encoded_target)
 
# Predict the fruit type for a new instance
new_instance = ["red", "large"]
encoded_new_instance = le.transform(new_instance)
predicted_fruit_type = clf.predict([encoded_new_instance])
decoded_predicted_fruit_type = le.inverse_transform(predicted_fruit_type)
print("Predicted fruit type:", decoded_predicted_fruit_type[0])
DecisionTreeRegressor(回归)
import os
ram_prices = pd.read_csv(os.path.join(mglearn.datasets.DATA_PATH, "ram_price.csv"))

plt.semilogy(ram_prices.date, ram_prices.price)
plt.xlabel("Year")
plt.ylabel("Price in $/Mbyte")

在这里插入图片描述

from sklearn.tree import DecisionTreeRegressor
# use historical data to forecast prices after the year 2000
data_train = ram_prices[ram_prices.date < 2000]
data_test = ram_prices[ram_prices.date >= 2000]

# predict prices based on date
X_train = data_train.date[:, np.newaxis]
# we use a log-transform to get a simpler relationship of data to target
y_train = np.log(data_train.price)

tree = DecisionTreeRegressor(max_depth=3).fit(X_train, y_train)
linear_reg = LinearRegression().fit(X_train, y_train)

# predict on all data
X_all = ram_prices.date[:, np.newaxis]

pred_tree = tree.predict(X_all)
pred_lr = linear_reg.predict(X_all)

# undo log-transform
price_tree = np.exp(pred_tree)
price_lr = np.exp(pred_lr)
plt.semilogy(data_train.date, data_train.price, label="Training data")
plt.semilogy(data_test.date, data_test.price, label="Test data")
plt.semilogy(ram_prices.date, price_tree, label="Tree prediction")
plt.semilogy(ram_prices.date, price_lr, label="Linear prediction")
plt.legend()

在这里插入图片描述

随机森林(集成学习)

先补充组合分类器的概念,将多个分类器的结果进行多票表决或取平均值,以此作为最终的结果。
每个决策树都有很高的方差,但是当我们将它们并行地组合在一起时,结果的方差就会很低,因为每个决策树都在特定的样本数据上得到了完美的训练,因此输出不依赖于一个决策树,而是依赖于多个决策树。在分类问题的情况下,使用多数投票分类器获得最终输出。在回归问题的情况下,最终输出是所有输出的平均值。这部分称为聚合。
1.构建组合分类器的好处:
(1)提升模型精度:整合各个模型的分类结果,得到更合理的决策边界,减少整体错误呢,实现更好的分类效果:
在这里插入图片描述
(2)处理过大或过小的数据集:数据集较大时,可将数据集划分成多个子集,对子集构建分类器;当数据集较小时,通过自助采样(bootstrap)从原始数据集采样产生多组不同的数据集,构建分类器。

(3)若决策边界过于复杂,则线性模型不能很好地描述真实情况。因此,现对于特定区域的数据集,训练多个线性分类器,再将他们集成。
在这里插入图片描述
(4)比较适合处理多源异构数据(存储方式不同(关系型、非关系型),类别不同(时序型、离散型、连续型、网络结构数据))
在这里插入图片描述

随机森林是一个多决策树的组合分类器,随机主要体现在两个方面:数据选取的随机性和特征选取的随机性。
在这里插入图片描述
在这里插入图片描述

from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_moons

X, y = make_moons(n_samples=100, noise=0.25, random_state=3)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y,
                                                    random_state=42)

forest = RandomForestClassifier(n_estimators=5, random_state=2)
forest.fit(X_train, y_train)
fig, axes = plt.subplots(2, 3, figsize=(20, 10))
for i, (ax, tree) in enumerate(zip(axes.ravel(), forest.estimators_)):
    ax.set_title("Tree {}".format(i))
    mglearn.plots.plot_tree_partition(X_train, y_train, tree, ax=ax)
    
mglearn.plots.plot_2d_separator(forest, X_train, fill=True, ax=axes[-1, -1],
                                alpha=.4)
axes[-1, -1].set_title("Random Forest")
mglearn.discrete_scatter(X_train[:, 0], X_train[:, 1], y_train)

在这里插入图片描述

X_train, X_test, y_train, y_test = train_test_split(
    cancer.data, cancer.target, random_state=0)
forest = RandomForestClassifier(n_estimators=100, random_state=0)
forest.fit(X_train, y_train)

print("Accuracy on training set: {:.3f}".format(forest.score(X_train, y_train)))
print("Accuracy on test set: {:.3f}".format(forest.score(X_test, y_test)))
plot_feature_importances_cancer(forest)

在这里插入图片描述

我们举一个线性回归的例子。我们有一个住房数据集,我们想预测房子的价格。下面是它的python代码。

# Python code to illustrate 
# regression using data set
import matplotlib
matplotlib.use('GTKAgg')
  
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
import pandas as pd
  
# Load CSV and columns
df = pd.read_csv("Housing.csv")
  
Y = df['price']
X = df['lotsize']
  
X=X.values.reshape(len(X),1)
Y=Y.values.reshape(len(Y),1)
  
# Split the data into training/testing sets
X_train = X[:-250]
X_test = X[-250:]
  
# Split the targets into training/testing sets
Y_train = Y[:-250]
Y_test = Y[-250:]
  
# Plot outputs
plt.scatter(X_test, Y_test,  color='black')
plt.title('Test Data')
plt.xlabel('Size')
plt.ylabel('Price')
plt.xticks(())
plt.yticks(())
# Create linear regression object
regr = linear_model.LinearRegression()
  
# Train the model using the training sets
regr.fit(X_train, Y_train)
  
# Plot outputs
plt.plot(X_test, regr.predict(X_test), color='red',linewidth=3)
plt.show()

在这里插入图片描述
在这张图中,我们绘制了测试数据。红线表示预测价格的最佳拟合线。使用线性回归模型进行个体预测:
print( str(round(regr.predict(5000))) )

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn
import warnings
 
from sklearn.preprocessing import LabelEncoder
from sklearn.impute import KNNImputer
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import f1_score
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_val_score
 
warnings.filterwarnings('ignore')
df= pd.read_csv('Salaries.csv')
print(df)

在这里插入图片描述
Here the .info() method provides a quick overview of the structure, data types, and memory usage of the dataset.

df.info()

在这里插入图片描述

# Assuming df is your DataFrame
X = df.iloc[:,1:2].values  #features
y = df.iloc[:,2].values  # Target variable

step 4: Random Forest Regressor model代码对分类数据进行数字编码处理,将处理后的数据与数字数据结合起来,使用准备好的数据训练Random Forest Regression模型。

import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import LabelEncoder
 
 Check for and handle categorical variables
label_encoder = LabelEncoder()
x_categorical = df.select_dtypes(include=['object']).apply(label_encoder.fit_transform)
x_numerical = df.select_dtypes(exclude=['object']).values
x = pd.concat([pd.DataFrame(x_numerical), x_categorical], axis=1).values
 
# Fitting Random Forest Regression to the dataset
regressor = RandomForestRegressor(n_estimators=10, random_state=0, oob_score=True)
 
# Fit the regressor with x and y data
regressor.fit(x, y)
# Evaluating the model
from sklearn.metrics import mean_squared_error, r2_score
 
# Access the OOB Score
oob_score = regressor.oob_score_
print(f'Out-of-Bag Score: {oob_score}')
 
# Making predictions on the same data or new data
predictions = regressor.predict(x)
 
# Evaluating the model
mse = mean_squared_error(y, predictions)
print(f'Mean Squared Error: {mse}')
 
r2 = r2_score(y, predictions)
print(f'R-squared: {r2}')

在这里插入图片描述

import numpy as np
X_grid = np.arange(min(X),max(X),0.01)
X_grid = X_grid.reshape(len(X_grid),1) 
   
plt.scatter(X,y, color='blue') #plotting real points
plt.plot(X_grid, regressor.predict(X_grid),color='green') #plotting for predict points
   
plt.title("Random Forest Regression Results")
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

在这里插入图片描述

from sklearn.tree import plot_tree
import matplotlib.pyplot as plt
 
# Assuming regressor is your trained Random Forest model
# Pick one tree from the forest, e.g., the first tree (index 0)
tree_to_plot = regressor.estimators_[0]
 
# Plot the decision tree
plt.figure(figsize=(20, 10))
plot_tree(tree_to_plot, feature_names=df.columns.tolist(), filled=True, rounded=True, fontsize=10)
plt.title("Decision Tree from Random Forest")
plt.show()

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1509377.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

webpack5零基础入门-4使用webpack处理less文件

1.安装less npm install less -D 2.创建less文件 .box{width: 100px;height: 100px;background: red; } 3.引入less文件并打包 执行npx webpack 报错无法识别less文件 4.安装less-loader并配置 npm install less-loader9 -D 这里指定一下版本不然会因为node版本过低报错 …

Java 启动参数 -- 和 -D写法的区别

当我们配置启动1个java 项目通常需要带一些参数 例如 -Denv uat , --spring.profiles.activedev 这些 那么用-D 和 – 的写法区别是什么&#xff1f; 双横线写法 其中这种写法基本上是spring 和 spring 框架独有 最常用的无非是就是上面提到的 --spring.profiles.activede…

【golang】28、用 httptest 做 web server 的 controller 的单测

文章目录 一、构建 HTTP server1.1 model.go1.2 server.go1.3 curl 验证 server 功能1.3.1 新建1.3.2 查询1.3.3 更新1.3.4 删除 二、httptest 测试2.1 完整示例2.2 实现逻辑2.3 其他示例2.4 用 TestMain 避免重复的测试代码2.5 gin 框架的 httptest 一、构建 HTTP server 1.1…

如何配置固定TCP公网地址实现远程访问内网MongoDB数据库

文章目录 前言1. 安装数据库2. 内网穿透2.1 安装cpolar内网穿透2.2 创建隧道映射2.3 测试随机公网地址远程连接 3. 配置固定TCP端口地址3.1 保留一个固定的公网TCP端口地址3.2 配置固定公网TCP端口地址3.3 测试固定地址公网远程访问 前言 MongoDB是一个基于分布式文件存储的数…

JDK环境变量配置-jre\bin、rt.jar、dt.jar、tools.jar

我们主要看下rt.jar、dt.jar、tools.jar的作用&#xff0c;rt.jar在​%JAVA_HOME%\jre\lib&#xff0c;dt.jar和tools.jar在%JAVA_HOME%\lib下。 rt.jar&#xff1a;Java基础类库&#xff0c;也就是Java doc里面看到的所有的类的class文件。 tools.jar&#xff1a;是系统用来编…

星星魔方

星星魔方 1&#xff0c;魔方三要素 &#xff08;1&#xff09;组成部件 6个中心块和8个角块和三阶魔方同构&#xff0c;另外每个面还有构成五角星的十个块。 &#xff08;2&#xff09;可执行操作 一共12种操作&#xff0c;其中6种是每个层顺时针旋转90度&#xff0c;另外6…

Gateway(路由映射)

1.SpringCloud Gateway Spring Cloud Gateway组件的核心是一系列的过滤器&#xff0c;通过这些过滤器可以将客户端发送的请求转发(路由)到对应的微服务。 Spring Cloud Gateway是加在整个微服务最前沿的防火墙和代理器&#xff0c;隐藏微服务结点IP端口信息&#xff0c;从而加…

用Vision Pro来控制机器人

【技术框架概述】 - visionOS App + Python Library用于从Vision Pro将头部/手腕/手指跟踪数据流式传输到任何机器人。 【定位】 - 该框架旨在利用Vision Pro控制机器人,并记录用户在环境中导航和操作的方式,以训练机器人。 【核心功能】 1. 提供visionOS应用程序和Py…

TEASEL: A transformer-based speech-prefixed language model

文章目录 TEASEL&#xff1a;一种基于Transformer的语音前缀语言模型文章信息研究目的研究内容研究方法1.总体框图2.BERT-style Language Models&#xff08;基准模型&#xff09;3.Speech Module3.1Speech Temporal Encoder3.2Lightweight Attentive Aggregation (LAA) 4.训练…

大语言模型系列-中文开源大模型

文章目录 前言一、主流开源大模型二、中文开源大模型排行榜 前言 近期&#xff0c;OpenAI 的主要竞争者 Anthropic 推出了他们的新一代大型语言模型 Claude 3&#xff0c;该系列涵盖了三个不同规模的模型&#xff1a;Opus、Sonnet 和 Haiku。 Claude 3声称已经全面超越GPT-4。…

软考71-上午题-【面向对象技术2-UML】-UML中的图2

一、用例图 上午题&#xff0c;考的少&#xff1b;下午题&#xff0c;考的多。 1-1、用例图的定义 用例图展现了一组用例、参与者以及它们之间的关系。 用例图用于对系统的静态用例图进行建模。 可以用下列两种方式来使用用例图&#xff1a; 1、对系统的语境建模&#xff1b…

人口性别年龄分布数据、不同年龄结构、性别结构人口分布数据、乡镇街道人口分布数据

人口分布是指人口在一定时间内的空间存在形式、分布状况&#xff0c;包括各类地区总人口的分布&#xff0c;以及某些特定人口&#xff08;如城市人口、、特定的人口过程和构成&#xff08;如迁移、性别等&#xff09;的分布等。 人口分布的最大特征是不平衡性。就全世界而言&am…

【工具】软件工具分享哪家强?安卓apk安装软件分享新方法,弃用QQ启用企业微信使用方法...

微信关注公众号 “DLGG创客DIY” 设为“星标”&#xff0c;重磅干货&#xff0c;第一时间送达。 前言 又又来聊软件工具分享 先简单回顾一下之前的内容&#xff1a; 按时间先后顺序&#xff1a; 1.从网盘到QQ群文件及群文件分类 【工具】软件工具分享哪家强&#xff1f;群文件使…

Mac电脑搭建前端项目环境,并适配老项目

1.上一篇文章中&#xff0c;我说到了&#xff0c;node.js中文网下载node 包&#xff0c;根据系统进行选择&#xff0c;然后安装包node即可&#xff0c;对于比较新的项目确实也是适用的&#xff0c;但是老项目就不行了会报错&#xff0c;node版本过高&#xff0c;导致环境不匹配…

Java线程的基本操作

线程的基本操作 Java线程的常用操作都定义在Thread类中&#xff0c;包括一些重要的静态方法 和线程的实例方法 。下面我们来学习一下&#xff0c;线程的常用基本操作 1.线程名称的设置和获取 线程名称可以通过构造Thread的时候进行设置&#xff0c;也可以通过实例的方法setName…

科技云报道:两会热议的数据要素,如何拥抱新技术?

科技云报道原创。 今年全国两会上&#xff0c;“数字经济”再次成为的热点话题。 2024年政府工作报告提到&#xff1a;要健全数据基础制度&#xff0c;大力推动数据开发开放和流通使用&#xff1b;适度超前建设数字基础设施&#xff0c;加快形成全国一体化算力体系&#xff1…

【Flutter】报错Target of URI doesn‘t exist ‘package:flutter/material.dart‘

运行别人项目 包无法导入报错&#xff1a;Target of URI doesn’t exist ‘package:flutter/material.dart’ 解决方法 flutter packages get成功 不会报错

Centos本地、公网邮件发送配置

目录 本地邮件发送 发送邮件的三种方式 接受邮件 配置公网发送邮件 发送文件 本地邮件发送 安装服务 # yum -y install postfix # yum -y install mailx 启动服务 # systemctl start postfix 发送邮件的三种方式 一. # mail-s“邮件主题” 收件人 ​ 邮件内容…

Linux - 安装 Jenkins(详细教程)

目录 前言一、简介二、安装前准备三、下载与安装四、配置镜像地址五、启动与关闭六、常用插件的安装 前言 虽然说网上有很多关于 Jenkins 安装的教程&#xff0c;但是大部分都不够详细&#xff0c;或者是需要搭配 docker 或者 k8s 等进行安装&#xff0c;对于新手小白而已&…

智谱清华LongAlign发布:重塑NLP长文本处理

引言 随着大型语言模型&#xff08;LLMs&#xff09;的不断进化&#xff0c;我们现在能够处理的文本长度已经达到了前所未有的规模——从最初的几百个tokens到现在的128k tokens&#xff0c;相当于一本300页的书。这一进步为语义信息的提供、错误率的减少以及用户体验的提升打…