시작하기무료로 시작하기

텍스트를 벡터 형식으로 변환하기

이제 문장을 분할하고 CountVectorizer를 사용해 단어 배열을 수치 벡터로 변환하는 방법을 배우셨어요.

데이터프레임 df가 제공되며, 열은 sentence, in, out입니다. 각 열은 문자열 배열입니다. sentence는 교과서에서 가져온 한 문장을 단어 목록으로 나타낸 것이고, out 열은 sentence의 마지막 단어를 담습니다. in 열은 sentence에서 마지막 단어를 제거해 만든 것입니다.

CountVectorizer modelwords라는 열을 가진 데이터프레임을 입력으로 받아 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을 사용해 dftransform()을 적용하여 result라는 데이터프레임을 만드세요. result에는 sentence, in, out, invec 열이 있어야 하고, invecin 열을 벡터로 변환한 결과입니다.
  • resultoutvec이라는 열을 추가하세요. 이제 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)	
코드 편집 및 실행