特征抽取--标签与索引的转化: IndexToString
生活随笔
收集整理的這篇文章主要介紹了
特征抽取--标签与索引的转化: IndexToString
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
與StringIndexer相對(duì)應(yīng),IndexToString的作用是把標(biāo)簽索引的一列重新映射回原有的字符型標(biāo)簽。
其主要使用場(chǎng)景一般都是和StringIndexer配合,先用StringIndexer將標(biāo)簽轉(zhuǎn)化成標(biāo)簽索引,進(jìn)行模
型訓(xùn)練,然后在預(yù)測(cè)標(biāo)簽的時(shí)候再把標(biāo)簽索引轉(zhuǎn)化成原有的字符標(biāo)簽。當(dāng)然,你也可以另外定義其他
的標(biāo)簽。
首先,和StringIndexer的實(shí)驗(yàn)相同,我們用StringIndexer讀取數(shù)據(jù)集中的“category”列,把字符
型標(biāo)簽轉(zhuǎn)化成標(biāo)簽索引,然后輸出到“categoryIndex”列上,構(gòu)建出新的DataFrame。
?
#導(dǎo)入相關(guān)的類庫
from pyspark.sql import SparkSession from pyspark.ml.feature import IndexToString, StringIndexer #創(chuàng)建SparkSession對(duì)象,配置spark spark= SparkSession.builder.master('local').appName('IndexToStringDemo').getOrCreate() #創(chuàng)建一個(gè)簡單的DataFrame訓(xùn)練集 df = spark.createDataFrame( [(0, "a"), (1, "b"), (2, "c"), (3, "a"), (4, "a"), (5, "c")], ["id", "category"]) #創(chuàng)建StringIndexer對(duì)象,設(shè)置輸入輸出對(duì)象 indexer = StringIndexer(inputCol='category', outputCol='categoryIndex') #利用fit方法生成訓(xùn)練模型 model = indexer.fit(df) #利用生成的模型對(duì)DataFrame進(jìn)行轉(zhuǎn)換 indexed = model.transform(df) #創(chuàng)建IndexToString對(duì)象,設(shè)置輸入輸出參數(shù),獲得原有數(shù)據(jù)集的字符型標(biāo)簽,然后再輸出到“originalCategory” #列上。最后,通過輸出“originalCategory”列,可以看到數(shù)據(jù)集中原有的字符標(biāo)簽。 converter = IndexToString(inputCol='categoryIndex',outputCol='orignalCategory') converter =converter.transform(indexed) converter.select("id","categoryIndex","orignalCategory").show()?
轉(zhuǎn)載于:https://www.cnblogs.com/SoftwareBuilding/p/9492298.html
總結(jié)
以上是生活随笔為你收集整理的特征抽取--标签与索引的转化: IndexToString的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 判断变量类型
- 下一篇: [九省联考2018]IIIDX