【pyspark学习从入门到精通24】机器学习库_7

目录

聚类

在出生数据集中寻找簇

主题挖掘

回归


聚类

聚类是机器学习中另一个重要的部分:在现实世界中,我们并不总是有目标特征的奢侈条件,因此我们需要回归到无监督学习的范式,在那里我们尝试在数据中发现模式。

在出生数据集中寻找簇

在这个例子中,我们将使用 k-means 模型在出生数据中寻找相似性:

python 复制代码
import pyspark.ml.clustering as clus
kmeans = clus.KMeans(k = 5, 
 featuresCol='features')
pipeline = Pipeline(stages=[
 assembler,
 featuresCreator, 
 kmeans]
)
model = pipeline.fit(births_train)

估计模型后,让我们看看我们是否能找到不同簇之间的一些差异:

python 复制代码
test = model.transform(births_test)
test \
 .groupBy('prediction') \
 .agg({
 '*': 'count', 
 'MOTHER_HEIGHT_IN': 'avg'
 }).collect()

前面的代码产生了以下输出:

嗯,MOTHER_HEIGHT_IN 在第 2 个簇中显著不同。仔细研究结果(这里我们显然不会这么做)可能会揭示更多的差异,并允许我们更好地理解数据。

主题挖掘

聚类模型不仅限于数值数据。在自然语言处理领域,像主题提取这样的问题依赖于聚类来检测具有相似主题的文档。我们将经历这样一个例子。

首先,让我们创建我们的数据集。数据由互联网上随机选择的段落组成:其中三个涉及自然和国家公园的主题,其余三个涵盖技术。

python 复制代码
text_data = spark.createDataFrame([
 ['''To make a computer do anything, you have to write a 
 computer program. To write a computer program, you have 
 to tell the computer, step by step, exactly what you want 
 it to do. The computer then "executes" the program, 
 following each step mechanically, to accomplish the end 
 goal. When you are telling the computer what to do, you 
 also get to choose how it's going to do it. That's where 
 computer algorithms come in. The algorithm is the basic 
 technique used to get the job done. Let's follow an 
 example to help get an understanding of the algorithm 
 concept.'''],
 (...),
 ['''Australia has over 500 national parks. Over 28 
 million hectares of land is designated as national 
 parkland, accounting for almost four per cent of 
 Australia's land areas. In addition, a further six per 
 cent of Australia is protected and includes state 
 forests, nature parks and conservation reserves.National 
 parks are usually large areas of land that are protected 
 because they have unspoilt landscapes and a diverse 
 number of native plants and animals. This means that 
 commercial activities such as farming are prohibited and 
 human activity is strictly monitored.''']
], ['documents'])

首先,我们将再次使用 RegexTokenizer 和 StopWordsRemover 模型:

python 复制代码
tokenizer = ft.RegexTokenizer(
 inputCol='documents', 
 outputCol='input_arr', 
 pattern='\s+|[,.\"]')
stopwords = ft.StopWordsRemover(
 inputCol=tokenizer.getOutputCol(), 
 outputCol='input_stop')

接下来是我们管道中的 CountVectorizer:一个计算文档中单词数量并返回计数向量的模型。向量的长度等于所有文档中所有不同单词的总数,这可以在以下片段中看到:

python 复制代码
stringIndexer = ft.CountVectorizer(
 inputCol=stopwords.getOutputCol(), 
 outputCol="input_indexed")
tokenized = stopwords \
 .transform(
 tokenizer\
 .transform(text_data)
 )
 
stringIndexer \
 .fit(tokenized)\
 .transform(tokenized)\
 .select('input_indexed')\
 .take(2)

前面的代码将产生以下输出:

如你所见,文本中有 262 个不同的单词,现在每个文档由每个单词出现次数的计数表示。

现在轮到开始预测主题了。为此,我们将使用 LDA 模型------潜在狄利克雷分配模型:

python 复制代码
clustering = clus.LDA(k=2, 
 optimizer='online', 
 featuresCol=stringIndexer.getOutputCol())

k 参数指定我们期望看到的主题数量,优化器参数可以是 'online' 或 'em'(后者代表期望最大化算法)。

将这些谜题拼凑在一起,到目前为止,这是我们最长的管道:

python 复制代码
pipeline = ml.Pipeline(stages=[
 tokenizer, 
 stopwords,
 stringIndexer, 
 clustering]
)

我们是否正确地发现了主题?嗯,让我们看看:

python 复制代码
topics = pipeline \
 .fit(text_data) \
 .transform(text_data)
topics.select('topicDistribution').collect()

这是我们得到的:

看起来我们的方法正确地发现了所有的主题!不过,不要习惯看到这么好的结果:遗憾的是,现实世界的数据很少是这样的。

回归

我们不能在没有构建回归模型的情况下结束机器学习库的一章。

在这一部分,我们将尝试预测 MOTHER_WEIGHT_GAIN,给定这里描述的一些特征;这些特征包含在这里列出的特征中:

python 复制代码
features = ['MOTHER_AGE_YEARS','MOTHER_HEIGHT_IN',
 'MOTHER_PRE_WEIGHT','DIABETES_PRE',
 'DIABETES_GEST','HYP_TENS_PRE', 
 'HYP_TENS_GEST', 'PREV_BIRTH_PRETERM',
 'CIG_BEFORE','CIG_1_TRI', 'CIG_2_TRI', 
 'CIG_3_TRI'
 ]

首先,由于所有特征都是数值型的,我们将它们整合在一起,并使用 ChiSqSelector 仅选择最重要的六个特征:

python 复制代码
featuresCreator = ft.VectorAssembler(
 inputCols=[col for col in features[1:]], 
 outputCol='features'
)
selector = ft.ChiSqSelector(
 numTopFeatures=6, 
 outputCol="selectedFeatures", 
 labelCol='MOTHER_WEIGHT_GAIN'
)

为了预测体重增加,我们将使用梯度提升树回归器:

python 复制代码
import pyspark.ml.regression as reg
regressor = reg.GBTRegressor(
 maxIter=15, 
 maxDepth=3,
 labelCol='MOTHER_WEIGHT_GAIN')

最后,再次将所有内容整合到一个 Pipeline 中:

python 复制代码
pipeline = Pipeline(stages=[
 featuresCreator, 
 selector,
 regressor])
weightGain = pipeline.fit(births_train)

创建了 weightGain 模型后,让我们看看它在我们测试数据上的表现如何:

python 复制代码
evaluator = ev.RegressionEvaluator(
 predictionCol="prediction", 
 labelCol='MOTHER_WEIGHT_GAIN')
print(evaluator.evaluate(
 weightGain.transform(births_test), 
 {evaluator.metricName: 'r2'}))

我们得到以下输出:

遗憾的是,这个模型不比抛硬币的结果好。看来,如果没有与 MOTHER_WEIGHT_GAIN 标签更相关的额外独立特征,我们将无法充分解释其方差。

相关推荐
视觉AI2 分钟前
SiamMask原理详解:从SiamFC到SiamRPN++,再到多任务分支设计
人工智能·目标检测·计算机视觉·目标分割
Olafur_zbj2 分钟前
【EDA】EDA中聚类(Clustering)和划分(Partitioning)的应用场景
机器学习·数据挖掘·聚类
视觉&物联智能3 分钟前
【杂谈】-人工智能驱动的网络安全威胁:新一代网络钓鱼
网络·人工智能·web安全·网络安全·安全威胁分析
weixin_549808368 分钟前
以运营为核心的智能劳动力管理系统,破解连锁零售、制造业排班难题
大数据·人工智能·零售
struggle20259 分钟前
LinuxAgent开源程序是一款智能运维助手,通过接入 DeepSeek API 实现对 Linux 终端的自然语言控制,帮助用户更高效地进行系统运维工作
linux·运维·服务器·人工智能·自动化·deepseek
中关村科金34 分钟前
大模型训练平台:重构 AI 研发范式的智慧基建
人工智能·大模型·大模型训练平台
一点.点1 小时前
自动驾驶领域专业词汇(专业术语)整理
人工智能·自动驾驶·专业术语
烟锁池塘柳01 小时前
【深度学习】评估模型复杂度:GFLOPs与Params详解
人工智能·深度学习
果冻人工智能1 小时前
🧠5个AI工程师在第一次构建RAG时常犯的错误
人工智能
FAREWELL000751 小时前
C#进阶学习(十六)C#中的迭代器
开发语言·学习·c#·迭代器模式·迭代器