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