เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

แปลงข้อความให้เป็นรูปแบบเวกเตอร์

คุณได้เรียนรู้วิธีแยกประโยคและแปลงอาร์เรย์ของคำให้เป็นเวกเตอร์ตัวเลขโดยใช้ CountVectorizer แล้ว

มี dataframe df ที่มีคอลัมน์ดังต่อไปนี้: sentence, in และ out โดยแต่ละคอลัมน์เป็นอาร์เรย์ของ string sentence คือรายการคำที่ประกอบกันเป็นประโยคหนึ่งจากตำรา คอลัมน์ out ให้คำสุดท้ายของ sentence ส่วนคอลัมน์ in ได้มาจากการตัดคำสุดท้ายออกจาก sentence

โดย CountVectorizer model คาดหวัง dataframe ที่มีคอลัมน์ชื่อ words และจะสร้างคอลัมน์ vec ขึ้นมา

ขั้นแรก จะทำการ transform เพื่อเพิ่มคอลัมน์ 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

จากนั้น จะทำการ transform ครั้งที่สอง ซึ่งมีลักษณะดังนี้:

+------------------------------------+----------------+
|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

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Introduction to Spark SQL in Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้าง dataframe ชื่อ result โดยใช้ model เพื่อ transform() df โดย result จะมีคอลัมน์ sentence, in, out และ invec ซึ่ง invec คือผลลัพธ์การแปลงเวกเตอร์ของคอลัมน์ in
  • เพิ่มคอลัมน์ชื่อ outvec ลงใน result โดย 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)	
แก้ไขและรันโค้ด