開始使用免費開始

將文字轉換為向量格式

你已經學會如何切分句子,並使用 CountVectorizer 將字詞陣列轉換成數值向量。

這裡提供一個 dataframe df,包含以下欄位:sentence、in 和 out。每個欄位都是字串陣列。sentence 是教科書中一句話的字詞清單。out 欄位給出 sentence 的最後一個字。in 欄位則是從 sentence 中移除最後一個字後得到的結果。

CountVectorizer 的 model 需要一個含有 words 欄位的 dataframe,並會產生 vec 欄位。

你將先進行一次轉換,新增 invec 欄,結果如下所示:

+----------------------+-------+------------------------------------+
|in                    |out    |invec                               |
+----------------------+-------+------------------------------------+
|[then, how, many, are]|[there]|(126,[3,18,28,30],[1.0,1.0,1.0,1.0])|
|[how]                 |[many] |(126,[28],[1.0])                    |
|[i, donot]            |[know] |(126,[15,78],[1.0,1.0])             |
+----------------------+-------+------------------------------------+
only showing top 3 rows

接著你會進行第二次轉換,結果如下所示:

+------------------------------------+----------------+
|invec                               |outvec          |
+------------------------------------+----------------+
|(126,[3,18,28,30],[1.0,1.0,1.0,1.0])|(126,[11],[1.0])|
|(126,[28],[1.0])                    |(126,[18],[1.0])|
|(126,[15,78],[1.0,1.0])             |(126,[21],[1.0])|
+------------------------------------+----------------+
only showing top 3 rows

本練習屬於課程

Python Spark SQL 入門

檢視課程

練習說明

  • 使用 model 對 df 呼叫 transform(),建立名為 result 的 dataframe。result 需包含 sentence、in、out 與 invec 欄位,其中 invec 是 in 欄位轉換而得的向量。
  • 在 result 中新增名為 outvec 的欄位。此時 result 應包含 sentence、in、out、invec、outvec 這些欄位。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Transform df using model
result = model.____(df.withColumnRenamed('in', 'words'))\
        .withColumnRenamed('words', 'in')\
        .withColumnRenamed('vec', 'invec')
result.drop('sentence').show(3, False)

# Add a column based on the out column called outvec
result = model.transform(result.withColumnRenamed('out', 'words'))\
        .withColumnRenamed('words', 'out')\
        .withColumnRenamed('vec', '____')
result.select('invec', 'outvec').show(3, False)	
編輯並執行程式碼