반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

오늘은 Openai cookbook의 embeddings에 있는 Clustering embeddings 예제를 공부해 보겠습니다.

openai-cookbook/Clustering.ipynb at main · openai/openai-cookbook · GitHub

 

GitHub - openai/openai-cookbook: Examples and guides for using the OpenAI API

Examples and guides for using the OpenAI API. Contribute to openai/openai-cookbook development by creating an account on GitHub.

github.com

여기서 사용하는 예제는 아래 글을 보시면 구하실 수 있습니다.

IT 기술 따라잡기 :: Openai cookbook - Embeddings - Text comparison examples - Semantic text search using embeddings (tistory.com)

 

Openai cookbook - Embeddings - Text comparison examples - Semantic text search using embeddings

오늘은 openai cookbook 에 있는 Embeddings 부문의 Text comparison examples 에 있는 Semantic_text_search_using_embeddings.ipynb 예제를 살펴 보겠습니다. 우선 이 예제를 살펴 보기 전에 준비해야 할 사항들이 몇가지

coronasdk.tistory.com

첫번째 예제 코드와 실행 결과는 아래와 같습니다.

 

 

이번에는 command prompt 가 아닌 Jupyter lab을 사용해서 실행해 보았습니다.

이전 예제에서 계속 사용해 왔던 numpy와 pandas 모듈을 import 합니다.

그리고 csv 파일을 datafile_path에 담습니다.

 

그리고 pandas 모듈의 read_csv() 함수를 이용해 해당 파일을 읽어오고 이를 df변수에 담습니다.

그 다음줄은 df에 embedding이라는 컬럼을 만들고 (있으면 덮어쓰고) 그곳에 df.embedding.apply(eval).apply(np.array) 을 담습니다.

string을 numpy array로 변환시키는 부분입니다.

이건 공식처럼 외우셔도 괜찮을 것 같습니다.

아래 페이지에 가면 그 사용법이 나옵니다.

Embeddings - OpenAI API

 

OpenAI API

An API for accessing new AI models developed by OpenAI

platform.openai.com

 

 

그 다음은 df의 embedding의 값을 numpy의 vstack() 함수를 사용해서 행을 기준으로 병합합니다.

numpy.vstack(tup, *, dtype=None, casting='same_kind')

Stack arrays in sequence vertically (row wise).

 

아래 페이지에는 더 자세하게 설명 돼 있습니다.

 

numpy.vstack — NumPy v1.24 Manual

 

numpy.vstack — NumPy v1.24 Manual

If provided, the destination array will have this dtype. Cannot be provided together with out.

numpy.org

그 다음 shape은 배열의 모양을 말합니다. 

이 배열에는 총 1000개의 embedding이 있고 각 embedding 마다 1536개의 float 형식의 값이 있습니다.

그래서 matrix.shape 을 하면 (1000,1536) 이라는 값이 나옵니다.

 

1. Find the clusters using K-means

다음은 clustering을 지원해 주는 python의 모듈인 sklearn을 사용합니다.

sklearn의 cluster에 있는 KMeans라는 함수를 import 합니다.

KMeans와 관련한 설명은 여기에 있습니다.

2.3. Clustering — scikit-learn 1.2.1 documentation

 

2.3. Clustering

Clustering of unlabeled data can be performed with the module sklearn.cluster. Each clustering algorithm comes in two variants: a class, that implements the fit method to learn the clusters on trai...

scikit-learn.org

클러스터 수는 4개로 하고 KMeans를 사용해서 클러스터링 관련 계산을 해서 kmeans에 담습니다.

KMeans는 임의로 중심을 정하는 부분과 모든 데이터에 대해 중심 거리를 각각 구해서 가장 거리가 작은 중심으로 grouping을 하고 각 그룹마다 다시 평균을 구하는 것을 평균의 변화가 거의 없을 때까지 반복합니다.

 

k-평균 알고리즘 - 위키백과, 우리 모두의 백과사전 (wikipedia.org)

 

k-평균 알고리즘 - 위키백과, 우리 모두의 백과사전

위키백과, 우리 모두의 백과사전. k-평균 알고리즘(K-means clustering algorithm)은 주어진 데이터를 k개의 클러스터로 묶는 알고리즘으로, 각 클러스터와 거리 차이의 분산을 최소화하는 방식으로 동작

ko.wikipedia.org

여기서는 그룹을 4개로 나누라는 의미입니다.

 

그 다음에 나오는 fit()과 labels_ 는 항상 따라 다니더라구요.

 

fit()은 k-means clustring을 compute  해 주고 labels_는 각 포인트별로 라벨링을 해 주는 함수 입니다.

 

관련해서는 아래 페이지에 자세한 내용이 있습니다.

 

sklearn.cluster.KMeans — scikit-learn 1.2.1 documentation

 

sklearn.cluster.KMeans

Examples using sklearn.cluster.KMeans: Release Highlights for scikit-learn 1.1 Release Highlights for scikit-learn 1.1 Release Highlights for scikit-learn 0.23 Release Highlights for scikit-learn 0...

scikit-learn.org

 

그 다음에는 데이터 프레임에 Cluster라는 컬럼에 이 labels를 넣습니다.

 

그 다음은 pandas의 데이터를 다루는 함수들이 나옵니다.

Cluster를 기준으로 groupby를 하고 score.mean()으로 평균을 구합니다.

그리고sort_values()로 정렬을 했습니다.

 

 

이 결과는 4개의 그룹으로 clustering을 했고 각 그룹별 평균값일 표시한 겁니다.

 

그 다음 소스코드과 그 소스코드의 실행 결과는 아래와 같습니다.

 

 

sklearn의 manifold  모듈의 TSNE 함수를 import 합니다.

sklearn.manifold.TSNE — scikit-learn 1.2.1 documentation

 

sklearn.manifold.TSNE

Examples using sklearn.manifold.TSNE: Comparison of Manifold Learning methods Comparison of Manifold Learning methods Manifold Learning methods on a severed sphere Manifold Learning methods on a se...

scikit-learn.org

이것은 고차원 데이터를 시각화 해 주는 툴입니다.

 

그 다음은 matplotlib 모듈입니다. 이 모듈도 Visualization 관련 모듈입니다.

Matplotlib — Visualization with Python

 

Matplotlib — Visualization with Python

seaborn seaborn is a high level interface for drawing statistical graphics with Matplotlib. It aims to make visualization a central part of exploring and understanding complex datasets. statistical data visualization Cartopy Cartopy is a Python package des

matplotlib.org

[CCTV] 5.matplotlib기초 (tistory.com)

 

[CCTV] 5.matplotlib기초

서울시 CCTV 분석하기 프로젝트 5. matplotlib기초 matplotlib란? 파이썬의 대표 시각화 도구 Matplotlib는 Python 프로그래밍 언어 및 수학적 확장 NumPy 라이브러리를 활용한 플로팅 라이브러리이다. Tkinter ,

ruby-jieun.tistory.com

 

그 다음은 TSNE()의 값을 tsne 변수에 담고 이것을 fit_transform() 해서 vis_dim2에 담습니다.

fit_transform(X[, y]) Fit X into an embedded space and return that transformed output.

그리고 x와 y를 설정합니다. 

 

그리고 for 문을 통해 각 4개의 그룹별로 루프를 돌게 만들어서 각 그룹별로 색을 다르게 표현하도록 합니다.

 

plt.scatter()는 산점도를 그리는 함수 입니다.

 

matplotlib.pyplot.scatter — Matplotlib 3.7.0 documentation

 

matplotlib.pyplot.scatter — Matplotlib 3.7.0 documentation

Fundamentally, scatter works with 1D arrays; x, y, s, and c may be input as N-D arrays, but within scatter they will be flattened. The exception is c, which will be flattened only if its size matches the size of x and y.

matplotlib.org

[시각화] plt.scatter()를 활용한 산점도 그리기 (tistory.com)

 

[시각화] plt.scatter()를 활용한 산점도 그리기

0. 학습 환경 matplotlib: 3.3.4 seaborn: 0.11.1 금일 학습에는 seaborn 라이브러리에서 제공하는 iris 데이터를 사용하고자 합니다. seaborn에서 제공하는 다른 데이터셋은 '.get_dataset_names()'를 통해 확인이 가

scent-of-light.tistory.com

그리고 plt.title()에서 이 표의 제목을 정해주면 결과와 같은 그림을 얻을 수 있습니다.

 

 

 

4개의 그룹중에 녹색 그룹은 다른 그룹들과 좀 동떨어져 있는 것을 보실 수 있습니다.

 

2. Text samples in the clusters & naming the clusters

지금까지는 raw data를 clustering 하는 법과 이 clustering 한 데이터를 시각화 해서 보여주는 방법을 보았습니다.

 

이제 openai의 api를 이용해서 각 클러스터의 랜덤 샘플들을 보여 주는 코드입니다. 

openai.Completion.create() api를 사용할 것이고 모델 (engine)은 text-ada-001을 사용합니다.

prompt는 아래 질문 입니다.

What do the following customer reviews have in common?

그러면 각 클러스터 별로 review 를 분석한 값들이 response 됩니다.

 

우선 아래 코드를 실행 해 보겠습니다.

import openai

def open_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as infile:
        return infile.read()

openai.api_key = open_file('openaiapikey.txt')

# Reading a review which belong to each group.
rev_per_cluster = 5

for i in range(n_clusters):
    print(f"Cluster {i} Theme:", end=" ")

    reviews = "\n".join(
        df[df.Cluster == i]
        .combined.str.replace("Title: ", "")
        .str.replace("\n\nContent: ", ":  ")
        .sample(rev_per_cluster, random_state=42)
        .values
    )
    response = openai.Completion.create(
        engine="text-ada-001",  #"text-davinci-003",
        prompt=f'What do the following customer reviews have in common?\n\nCustomer reviews:\n"""\n{reviews}\n"""\n\nTheme:',
        temperature=0,
        max_tokens=64,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0,
    )
    print(response)

openai를 import 하고 openai api key를 제공하는 부분으로 시작합니다.

그리고 rev_per_cluster는 5로 합니다.

그 다음 for 문에서 n_clusters만큼 루프를 도는데 위에서 n_clusters는 4로 설정돼 있었습니다.

 

reviews에는 Title과 Content 내용을 넣는데 샘플로 5가지를 무작위로 뽑아서 넣습니다.

 

그리고 이 reviews 값을 prompt에 삽입해서 openai.Completion.create() api로 request 합니다.

 

그러면 이 prompt에 대한 response 가 response 변수에 담깁니다.

 

이 response 만 우선 출력해 보겠습니다.

 

Cluster 0 Theme: {
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": " Customer reviews:gluten free, healthy bars, content:\n\nThe customer reviews have in common that they save money on Amazon by ordering by themselves by looking for gluten free healthy bars. The bars are also delicious."
    }
  ],
  "created": 1677191195,
  "id": "cmpl-6nEKppB6SqCz07LYTcaktEAgq06hm",
  "model": "text-ada-001",
  "object": "text_completion",
  "usage": {
    "completion_tokens": 44,
    "prompt_tokens": 415,
    "total_tokens": 459
  }
}
Cluster 1 Theme: {
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": " Cat food\n\nMessy, undelicious, and possibly unhealthy."
    }
  ],
  "created": 1677191195,
  "id": "cmpl-6nEKpGffRc2jyJB4gNtuCa09dG2GT",
  "model": "text-ada-001",
  "object": "text_completion",
  "usage": {
    "completion_tokens": 15,
    "prompt_tokens": 529,
    "total_tokens": 544
  }
}
Cluster 2 Theme: {
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": " Coffee\n\nThe customer's reviews have in common that they are among the best in the market, Rodeo Drive, and that the customer is able to enjoy their coffee half and half because they have an Amazon account."
    }
  ],
  "created": 1677191196,
  "id": "cmpl-6nEKqxza0t8vGRAiK9K5RtCy3Gwbl",
  "model": "text-ada-001",
  "object": "text_completion",
  "usage": {
    "completion_tokens": 45,
    "prompt_tokens": 443,
    "total_tokens": 488
  }
}
Cluster 3 Theme: {
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "text": " Customer reviews of different brands of soda."
    }
  ],
  "created": 1677191196,
  "id": "cmpl-6nEKqKuxe4CVJTV4GlIZ7vxe6F85o",
  "model": "text-ada-001",
  "object": "text_completion",
  "usage": {
    "completion_tokens": 8,
    "prompt_tokens": 616,
    "total_tokens": 624
  }
}
​

이 respons를 보시면 각 Cluster 별로 응답을 받았습니다.

위에 for 문에서 각 클러스터별로 request를 했기 때문입니다.

이제 이 중에서 실제 질문에 대한 답변인 choices - text  부분만 뽑아 보겠습니다.

 

import openai

def open_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as infile:
        return infile.read()

openai.api_key = open_file('openaiapikey.txt')

# Reading a review which belong to each group.
rev_per_cluster = 5

for i in range(n_clusters):
    print(f"Cluster {i} Theme:", end=" ")

    reviews = "\n".join(
        df[df.Cluster == i]
        .combined.str.replace("Title: ", "")
        .str.replace("\n\nContent: ", ":  ")
        .sample(rev_per_cluster, random_state=42)
        .values
    )
    response = openai.Completion.create(
        engine="text-ada-001",  #"text-davinci-003",
        prompt=f'What do the following customer reviews have in common?\n\nCustomer reviews:\n"""\n{reviews}\n"""\n\nTheme:',
        temperature=0,
        max_tokens=64,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0,
    )
 
    print(response["choices"][0]["text"].replace("\n", ""))

답변은 아래와 같습니다.

 

Cluster 0 Theme:  Customer reviews:gluten free, healthy bars, content:The customer reviews have in common that they save money on Amazon by ordering by themselves by looking for gluten free healthy bars. The bars are also delicious.
Cluster 1 Theme:  Cat foodMessy, undelicious, and possibly unhealthy.
Cluster 2 Theme:  CoffeeThe customer's reviews have in common that they are among the best in the market, Rodeo Drive, and that the customer is able to enjoy their coffee half and half because they have an Amazon account.
Cluster 3 Theme:  Customer reviews of different brands of soda.

 

다음엔 df에서 샘플을 뽑아 내는 코드가 있습니다.

 

sample_cluster_rows = df[df.Cluster == i].sample(rev_per_cluster, random_state=42)

df.sample(n) 은 n개의 행들을 임의로 추출합니다.

random_state은 샘플링 결과를 고정시키기 위한 것입니다.

 

[Pandas] 파이썬 데이터프레임 랜덤 샘플링 방법 : df.sample (tistory.com)

 

[Pandas] 파이썬 데이터프레임 랜덤 샘플링 방법 : df.sample

Python의 판다스 모듈로 데이터프레임의 행들을 랜덤 추출할 수 있는 df.sample 기능에 대하여 사용 예제를 정리해보도록 하겠습니다. 이해를 돕기 위하여 아래의 데이터프레임 df에 대하여 행 샘플

jimmy-ai.tistory.com

pandas.DataFrame.sample — pandas 1.5.3 documentation (pydata.org)

 

pandas.DataFrame.sample — pandas 1.5.3 documentation

Default ‘None’ results in equal probability weighting. If passed a Series, will align with target object on index. Index values in weights not found in sampled object will be ignored and index values in sampled object not in weights will be assigned we

pandas.pydata.org

 sample_cluster_rows = df[df.Cluster == i].sample(rev_per_cluster, random_state=42)

 

여기까지만 실행하면 아래와 같은 결과를 얻습니다.

 

Cluster 0 Theme:      Unnamed: 0   ProductId          UserId  Score  \
117         400  B008JKU2CO  A1XV4W7JWX341C      5   
25          274  B008JKTH2A  A34XBAIFT02B60      1   
722         534  B0064KO16O  A1K2SU61D7G41X      5   
289           7  B001KP6B98   ABWCUS3HBDZRS      5   
590         948  B008GG2N2S  A1CLUIIJL6EHLU      5   

                                               Summary  \
117  Loved these gluten free healthy bars, saved $$...   
25   Should advertise coconut as an ingredient more...   
722                                        very good!!   
289                                  Excellent product   
590                                          delicious   

                                                  Text  \
117  These Kind Bars are so good and healthy & glut...   
25   First, these should be called Mac - Coconut ba...   
722  just like the runts<br />great flavor, def wor...   
289  After scouring every store in town for orange ...   
590  Gummi Frogs have been my favourite candy that ...   

                                              combined  n_tokens  \
117  Title: Loved these gluten free healthy bars, s...        96   
25   Title: Should advertise coconut as an ingredie...        78   
722  Title: very good!!; Content: just like the run...        43   
289  Title: Excellent product; Content: After scour...       100   
590  Title: delicious; Content: Gummi Frogs have be...        75   

                                             embedding  Cluster  
117  [-0.002289338270202279, -0.01313735730946064, ...        0  
25   [-0.01757248118519783, -8.266511576948687e-05,...        0  
722  [-0.011768403463065624, -0.025617636740207672,...        0  
289  [0.0007493243319913745, -0.017031244933605194,...        0  
590  [-0.005802689120173454, 0.0007485789828933775,...        0  
Cluster 1 Theme:      Unnamed: 0   ProductId          UserId  Score  \
536         731  B0029NIBE8  A3RKYD8IUC5S0N      2   
332         184  B000WFRUOC   A22RVTZEIVHZA      4   
424         153  B0007A0AQW  A15X1BO4CLBN3C      5   
298          24  B003R0LKRW  A1OQSU5KYXEEAE      1   
960         589  B003194PBC  A2FSDQY5AI6TNX      5   

                              Summary  \
536  Messy and apparently undelicious   
332                  The cats like it   
424          cant get enough of it!!!   
298               Food Caused Illness   
960          My furbabies LOVE these!   

                                                  Text  \
536  My cat is not a huge fan. Sure, she'll lap up ...   
332  My 7 cats like this food but it is a little yu...   
424  Our lil shih tzu puppy cannot get enough of it...   
298  I switched my cats over from the Blue Buffalo ...   
960  Shake the container and they come running. Eve...   

                                              combined  n_tokens  \
536  Title: Messy and apparently undelicious; Conte...       181   
332  Title: The cats like it; Content: My 7 cats li...        87   
424  Title: cant get enough of it!!!; Content: Our ...        59   
298  Title: Food Caused Illness; Content: I switche...       131   
960  Title: My furbabies LOVE these!; Content: Shak...        47   

                                             embedding  Cluster  
536  [-0.002376032527536154, -0.0027701142244040966...        1  
332  [0.02162935584783554, -0.011174295097589493, -...        1  
424  [-0.007517425809055567, 0.0037251529283821583,...        1  
298  [-0.0011128562036901712, -0.01970377005636692,...        1  
960  [-0.009749102406203747, -0.0068712360225617886...        1  
Cluster 2 Theme:      Unnamed: 0   ProductId          UserId  Score  \
135         410  B007Y59HVM  A2ERWXZEUD6APD      5   
439         812  B0001UK0CM  A2V8WXAFG1TEOC      5   
326         107  B003VXFK44  A21VWSCGW7UUAR      4   
475         852  B000I6MCSY   AO34Q3JGZU0JQ      5   
692         922  B003TC7WN4  A3GFZIL1E0Z5V8      5   

                               Summary  \
135                  Fog Chaser Coffee   
439                    Excellent taste   
326   Good, but not Wolfgang Puck good   
475             Just My Kind of Coffee   
692  Rodeo Drive is Crazy Good Coffee!   

                                                  Text  \
135  This coffee has a full body and a rich taste. ...   
439  This is to me a great coffee, once you try it ...   
326  Honestly, I have to admit that I expected a li...   
475  Coffee Masters Hazelnut coffee used to be carr...   
692  Rodeo Drive is my absolute favorite and I'm re...   

                                              combined  n_tokens  \
135  Title: Fog Chaser Coffee; Content: This coffee...        42   
439  Title: Excellent taste; Content: This is to me...        31   
326  Title: Good, but not Wolfgang Puck good; Conte...       178   
475  Title: Just My Kind of Coffee; Content: Coffee...       118   
692  Title: Rodeo Drive is Crazy Good Coffee!; Cont...        59   

                                             embedding  Cluster  
135  [0.006498195696622133, 0.006776264403015375, 0...        2  
439  [0.0039436533115804195, -0.005451332312077284,...        2  
326  [-0.003140551969408989, -0.009995664469897747,...        2  
475  [0.010913548991084099, -0.014923149719834328, ...        2  
692  [-0.029914353042840958, -0.007755572907626629,...        2  
Cluster 3 Theme:      Unnamed: 0   ProductId          UserId  Score  \
495         831  B0014X5O1C   AHYRTWABDAG1H      5   
978         642  B00264S63G  A36AUU1UNRS48G      5   
916         686  B008PYVINQ  A1DRWYIO7JN1MD      2   
696         926  B0062P9XPU  A33KQALCZGXG8C      5   
491         828  B000EIE20M  A39QHSDUBR8L0T      3   

                               Summary  \
495  Wonderful alternative to soda pop   
978      So convenient, for so little!   
916                    bot very cheesy   
696                         Delicious!   
491                            Just ok   

                                                  Text  \
495  This is a wonderful alternative to soda pop.  ...   
978  I needed two vanilla beans for the Love Goddes...   
916  Got this about a month ago.first of all it sme...   
696  I am not a huge beer lover.  I do enjoy an occ...   
491  I bought this brand because it was all they ha...   

                                              combined  n_tokens  \
495  Title: Wonderful alternative to soda pop; Cont...       273   
978  Title: So convenient, for so little!; Content:...       121   
916  Title: bot very cheesy; Content: Got this abou...        46   
696  Title: Delicious!; Content: I am not a huge be...        97   
491  Title: Just ok; Content: I bought this brand b...        58   

                                             embedding  Cluster  
495  [0.022326279431581497, -0.018449820578098297, ...        3  
978  [-0.004598899278789759, -0.01737511157989502, ...        3  
916  [-0.010750919580459595, -0.0193503275513649, -...        3  
696  [0.009483409114181995, -0.017691848799586296, ...        3  
491  [-0.0023960231337696314, -0.006881058216094971...        3

여기서 데이터를 아래와 같이 가공을 합니다.

 

    for j in range(rev_per_cluster):
        print(sample_cluster_rows.Score.values[j], end=", ")
        print(sample_cluster_rows.Summary.values[j], end=":   ")
        print(sample_cluster_rows.Text.str[:70].values[j])

Score의 값들을 가지고 오고 끝에는 쉼표 , 를 붙입니다.

그리고 Summary의 값을 가지고 오고 끝에는 : 를 붙입니다.

그리고 Text컬럼의 string을 가지고 오는데 70자 까지만 가지고 옵니다.

 

전체 결과를 보겠습니다.

 

Cluster 0 Theme:  Customer reviews:gluten free, healthy bars, content:The customer reviews have in common that they save money on Amazon by ordering by themselves by looking for gluten free healthy bars. The bars are also delicious.
5, Loved these gluten free healthy bars, saved $$ ordering on Amazon:   These Kind Bars are so good and healthy & gluten free.  My daughter ca
1, Should advertise coconut as an ingredient more prominently:   First, these should be called Mac - Coconut bars, as Coconut is the #2
5, very good!!:   just like the runts<br />great flavor, def worth getting<br />I even o
5, Excellent product:   After scouring every store in town for orange peels and not finding an
5, delicious:   Gummi Frogs have been my favourite candy that I have ever tried. of co
Cluster 1 Theme:  Cat foodMessy, undelicious, and possibly unhealthy.
2, Messy and apparently undelicious:   My cat is not a huge fan. Sure, she'll lap up the gravy, but leaves th
4, The cats like it:   My 7 cats like this food but it is a little yucky for the human. Piece
5, cant get enough of it!!!:   Our lil shih tzu puppy cannot get enough of it. Everytime she sees the
1, Food Caused Illness:   I switched my cats over from the Blue Buffalo Wildnerness Food to this
5, My furbabies LOVE these!:   Shake the container and they come running. Even my boy cat, who isn't 
Cluster 2 Theme:  CoffeeThe customer's reviews have in common that they are among the best in the market, Rodeo Drive, and that the customer is able to enjoy their coffee half and half because they have an Amazon account.
5, Fog Chaser Coffee:   This coffee has a full body and a rich taste. The price is far below t
5, Excellent taste:   This is to me a great coffee, once you try it you will enjoy it, this 
4, Good, but not Wolfgang Puck good:   Honestly, I have to admit that I expected a little better. That's not 
5, Just My Kind of Coffee:   Coffee Masters Hazelnut coffee used to be carried in a local coffee/pa
5, Rodeo Drive is Crazy Good Coffee!:   Rodeo Drive is my absolute favorite and I'm ready to order more!  That
Cluster 3 Theme:  Customer reviews of different brands of soda.
5, Wonderful alternative to soda pop:   This is a wonderful alternative to soda pop.  It's carbonated for thos
5, So convenient, for so little!:   I needed two vanilla beans for the Love Goddess cake that my husbands 
2, bot very cheesy:   Got this about a month ago.first of all it smells horrible...it tastes
5, Delicious!:   I am not a huge beer lover.  I do enjoy an occasional Blue Moon (all o
3, Just ok:   I bought this brand because it was all they had at Ranch 99 near us. I

이제 좀 보기 좋게 됐습니다.

 

이번 예제는 raw 데이터를 파이썬의 여러 모듈들을 이용해서 clustering을 하고 이 cluster별로 openai.Completion.create() api를 이용해서 궁금한 답을 받는 일을 하는 예제를 배웠습니다.

 

큰 raw data를 카테고리화 해서 나누고 이에 대한 summary나 기타 정보를 Completion api를 통해 얻을 수 있는 방법입니다.

 

전체 소스코드는 아래와 같습니다.

 

# imports
import numpy as np
import pandas as pd

# load data
datafile_path = "./data/fine_food_reviews_with_embeddings_1k.csv"

df = pd.read_csv(datafile_path)
df["embedding"] = df.embedding.apply(eval).apply(np.array)  # convert string to numpy array
matrix = np.vstack(df.embedding.values)
matrix.shape

from sklearn.cluster import KMeans

n_clusters = 4

kmeans = KMeans(n_clusters=n_clusters, init="k-means++", random_state=42)
kmeans.fit(matrix)
labels = kmeans.labels_
df["Cluster"] = labels

df.groupby("Cluster").Score.mean().sort_values()

from sklearn.manifold import TSNE
import matplotlib
import matplotlib.pyplot as plt

tsne = TSNE(n_components=2, perplexity=15, random_state=42, init="random", learning_rate=200)
vis_dims2 = tsne.fit_transform(matrix)

x = [x for x, y in vis_dims2]
y = [y for x, y in vis_dims2]

for category, color in enumerate(["purple", "green", "red", "blue"]):
    xs = np.array(x)[df.Cluster == category]
    ys = np.array(y)[df.Cluster == category]
    plt.scatter(xs, ys, color=color, alpha=0.3)

    avg_x = xs.mean()
    avg_y = ys.mean()

    plt.scatter(avg_x, avg_y, marker="x", color=color, s=100)
plt.title("Clusters identified visualized in language 2d using t-SNE")

import openai

def open_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as infile:
        return infile.read()

openai.api_key = open_file('openaiapikey.txt')

# Reading a review which belong to each group.
rev_per_cluster = 5

for i in range(n_clusters):
    print(f"Cluster {i} Theme:", end=" ")

    reviews = "\n".join(
        df[df.Cluster == i]
        .combined.str.replace("Title: ", "")
        .str.replace("\n\nContent: ", ":  ")
        .sample(rev_per_cluster, random_state=42)
        .values
    )
    response = openai.Completion.create(
        engine="text-ada-001",  #"text-davinci-003",
        prompt=f'What do the following customer reviews have in common?\n\nCustomer reviews:\n"""\n{reviews}\n"""\n\nTheme:',
        temperature=0,
        max_tokens=64,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0,
    )
 
    print(response["choices"][0]["text"].replace("\n", ""))

    sample_cluster_rows = df[df.Cluster == i].sample(rev_per_cluster, random_state=42)

    for j in range(rev_per_cluster):
        print(sample_cluster_rows.Score.values[j], end=", ")
        print(sample_cluster_rows.Summary.values[j], end=":   ")
        print(sample_cluster_rows.Text.str[:70].values[j])
반응형


반응형

오늘은 Open AI API 에서 제공하는 기본 Embedding 예제 소스 코드를 살펴 보겠습니다.

 

 

아래 글을 보시면 해당 API 페이지의 내용을 보실 수 있습니다.

 

https://coronasdk.tistory.com/1237

 

Embeddings - openai.Embedding.create()

https://beta.openai.com/docs/api-reference/embeddings Embeddings Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms. 기계 학습 모델 및 알고리즘에서 쉽게 사용할 수 있는 주

coronasdk.tistory.com

이 예제 코드를 실행하기 위해서 약간 고친 저의 코드는 아래와 같습니다.

 

 

print를 좀 이쁘게 하기 위해서 pprint를 import 했고 api key를 전달하는 부분을 파일에서 읽어서 전달하도록 바꾸었습니다.

openai.Embedding.create() 부분은 예제와 똑 같습니다

 

이것을 실행하면 이렇게 나옵니다.

 

 

시작하는 부분은 이렇습니다.

입력 값은 "The food was delicious and the waiter..." 입니다. 

이에 대한 응답은 JSON 형식으로 response를 받게 되고 data 밑에 embedding 이라는 항목이 있고 그 안데 배열 형식으로 수 많은 숫자들이 있습니다. 모든 숫자는 0 이하의 부동 소숫점이고 양수와 음수들이 번갈아 가며 있습니다.

소숫점 아래 숫자들은 18자리 입니다.

이 부동 소숫점 들이 몇개나 있는지 알아봤습니다.

총 1536개가 있었습니다.

 

이것만 가지고는 무슨 의미인지 전혀 알 수 없습니다.

 

이 embeddings 기능을 사용하려면 이 response를 조금 가공 해야 합니다.

의미를 알 수 있도록 가공하는 방법에 대해서는 다음 글에서 자세하게 다룰 예정입니다.

 

오늘은 간단한 방법만 알아 보겠습니다.

 

일단 response 부분을 더 보겠습니다.

 

response의 맨 아랫부분을 보면 이렇습니다.

 

 

부동 소숫점 배열이 있는 embedding 부분이 끝나면 index 가 있습니다.

현재 값은 0 입니다.

이것은 우리가 request를 할 때 한가지만 전달해서 그렇습니다.

 

request의 input 부분에 여러개를 전달하면 각각에 대한 embedding 값을 반환하고 index는 0,1,2,3 이렇게 증가하면서 몇번째 request에 대한 임베딩 값인지 알 수 있게 해 줍니다.

 

그 다음 object는 embedding 이라는 것을 말해 줍니다.

 

그 다음은 모델 정보가 나옵니다. 우리는 request에서 text-embedding-ada-002를 사용했습니다.

응답에 나온 것을 보니까 정확하게는 text-embedding-ada-002-v2 모델을 사용했네요.

 

밑줄엔 object 아이템이 있고 이것은 list 를 사용했다고 알려 주는 것 같습니다.

 

그 밑에 usage 부분에는 사용된 토큰 값이 표시 됩니다.

이 토큰의 양에 따라서 사용료가 부과가 되니까 이것도 중요한 정보 입니다.

 

우리가 사용한 토큰은 총 8개 입니다.

 

토큰에 대해 알고 싶으시면 아래 글에 간단히 설명 돼 있습니다.

 

https://coronasdk.tistory.com/1257

 

GPT-3 API로 초간단 Chatbot 만들기

오늘은 Python 과 ChatGPT API로 간단한 챗봇을 만들어 보겠습니다. import os import openai def open_file(filepath): with open(filepath, 'r', encoding='utf-8') as infile: return infile.read() openai.api_key = open_file('openaiapikey.txt') wh

coronasdk.tistory.com

 

일단 여기서 핵심 정보는 embedding 부분입니다.

 

이것을 다루려면 이 부분만 따로 추려서 다루어야 합니다.

 

response 중에 embedding 만을 따로 추리는 방법은 아래와 같습니다.

 

embeddings = response['data'][0]['embedding']

 

당연히 이 부분을 출력하면 embedding 값들만 나오겠죠.

 

 

이 embedding은 대개 유사성을 측정하는데 사용합니다.

그렇기 때문에 두개 이상의 대상에 대해 유사성을 측정하게 되는데요.

 

이 경우 이 값들을 유의미하게 사용하기 위해서 numpy의 dot() 이라는 메소드를 사용합니다.

이 dot() 메소드는 두개의 input array가 1차원인 벡터들인 경우 사용합니다.

 

다음 글에서는 이 embedding 을 가지고 유의미하게 사용하는 예제를 만들고 분석해 보겠습니다.

반응형


반응형

지난번에 OpenAI API 연결을 테스트 하기 위해 만들었던 소스코드를 분석해 보겠습니다.

 

첫번째 import OpenAI는 OpenAI API 를 사용하기 위해 필요한 겁니다.

이것은 로컬에 OpenAI 를 깔았기 때문에 사용 가능하게 된 것입니다.

지난 글에 아래 명령어를 사용해서 OpenAI를 깔았었습니다.

 

pip install openai

pip install openai --upgrade

 

Pip 명령어는 Python을 깔았기 때문에 사용 가능한 것입니다.

자세한 사항은 이전 글을 참조하세요.

 

https://coronasdk.tistory.com/1252

 

로컬 개발 환경 세팅하기 : Python , OpenAI Install

OpenAI API 를 사용하기 위해서는 OpenAI 를 로컬에 깔아야 하고 이 OpenAI API를 사용해서 어플리케이션을 만들 언어도 깔아야 합니다. 저는 파이썬을 깔겠습니다. 파이썬은 이곳에서 다운 받아서 인스

coronasdk.tistory.com

 

두번째는 함수 입니다. 

 

OpenAI를 사용하기 위해서는 내가 Open AI로 부터 받은 API KEY를 제공해서 인증을 받아야 합니다. 일정의 비밀번호이죠.

Open AI API는 유료입니다. 

지난 글에서 간단한 질문 하나 하는데 1원정도가 청구 되는 걸 보았습니다.

유료이기 때문에 나의 API KEY를 사용해서 인증을 받고 그 다음에 사용하는 만큼 금액이 청구 됩니다.

당연히 이 API KEY를 보내지 않으면 OpenAI API를 사용할 수 없습니다.

 

이 API KEY를 보내는 방법은 8번째 줄에 있습니다.

openai.api_key = "My API KEY"

 

그런데 여기에 키를 하드 코딩 하면 보안상 문제가 될 수 있고 또한 이 키가 변경이 되었을 때 일일이 모든 파일에 있는 키 정보를 업데이트 해야 합니다. 관리상의 문제가 있죠.

 

그래서 보통 이런 경우는 별도의 파일을 만들어서 관리를 하고 파이썬 파일 안에서는 이 파일을 열고 그 내용을 읽어서 사용합니다.

 

이렇게 파일을 열고 그 내용을 읽는 부분을 함수로 만든 부분이 3~5째 줄에 있는 내용입니다.

 

def open_file(filepath) : 
    with open(filepath, 'r', encoding='utf-8') as infile : 
        return infile.read() 

 

파이썬에서 함수를 만들려면 def 로 시작하면 됩니다. 그 다음은 함수 이름이 오고 그 다음 괄호 안에 파라미터들을 넣습니다.파라미터가 여러개 있는 경우 쉼표 , 로 구분합니다. 그리고 마지막엔 : 로 끝납니다.

 

그 다음 줄은 함수의 내용입니다. 

 

파이썬에서 파일을 열고 읽는 방법은 아래와 같습니다.open("파일 이름", r,)두번째 파라미터인 r은 이 파일을 읽겠다는 겁니다. w 는 파일에 내용을 쓸 때 사용하고 a는 파일 내용 마지막에 새로운 내용을 추가할 때 사용할 수 있습니다.일반적으로 프로그래밍에서는 파일을 열었으면 마지막에 더 이상 사용하지 않을 때 이 파일을 close()해주어야 합니다. file_data = open("file.txt")print(file_data.readline(), end="")file_data.close()

 

이렇게 해야 되는데요. with를 사용해면 이 close() 부분을 자동으로 해 줍니다.아래 두 줄은 위의 세 줄과 똑 같은 겁니다.

 

with open("file.txt) as file_data:print(file_data.readline(), end="")

 

Close()는 with 문을 나올 때 이루어 집니다.

 

참고로 파이썬에서는 들여쓰기로 영역을 지정합니다.자바에서는 함수 (메소드)를 선언 할 때 {}로 지정하는 것과 차이가 있습니다.

 

그러므로 파이썬에서는 들여쓰기를 할 때 주의 해야 합니다.If, for, class, def 등을 사용할 때 그 줄 끝에 : 가 나오게 되는데 그 다음줄은 반드시 들여쓰기를 해야 합니다.그리고 블럭 내의 들여쓰기 칸 수는 같습니다.

위반시에는 indentationError: unexpected indent 라는 에러를 출력합니다.

 

 

이제 위의 코드를 해석할 수 있는 사전 지식은 다 갖추었습니다.

 

open_file()이라는 함수를 만든다는 것이 첫째줄에서 이야기 하는 겁니다. 파라미터는 filepath 입니다.

다음에 칸을 들여써서 with open() 을 사용해서 파일을 엽니다. 

열 파일은 filepath입니다. 나중에 이 함수를 호출 할 때 제공해 주어야 합니다.

r은 이 파일을 읽겠다는 의미이고 세번째 파라미터는 그 파일의 인코딩 형식입니다. Txt 파일은 Ute-8이라고 선언해 주면 됩니다.

세번째 파라미터는 생략해도 작동을 할 겁니다. 보다 정확하게 하기 위해 선언 해 주셔도 됩니다.

 

as infile 은 변수 이름이 infile 이라는 겁니다. 

파일을 열었으니까 그 내용이 infile에 저장 돼 있는 겁니다.

 

그 다음은 infile의 내용을 read()를 사용해서 가져오고 그 내용을 return 하는 겁니다.

 

이로서 open_file() 함수는 다 이해 했습니다.

 

이 함수를 사용하는 부분이 바로 8번째 줄입니다.

 

openai.api_key=open_file('openaiapikey.txt')

 

openai.api_key 는 OpenAI에서 정한 규칙입니다. API 키를 제공하기 위해서는 이 변수에 API 키 정보를 담으면 됩니다.

= 이후에 내용이 아까 만들었던 함수를 호출하는 부분입니다.

파라미터는 openaiapikey.txt 입니다. 따로 폴더 정보가 없으면 현재 폴더에서 해당 파일을 찾아서 열게 됩니다.이 텍스트 파일은 미리 만들어서 그 안에 API 키 정보를 넣어 두어야 합니다.

 

자 이러면 OpenAI 에 내 API 키를 제공했고 이 키가 유효하다면 지금부터 OpenAI API 를 사용할 수 있습니다.

 

10번째 줄은 또 다른 함수를 선언 한 것입니다.

 

gpt3_completion() 이란 함수를 선언했고 파라미터는 8개나 되네요.이 파라미터들은 함수 안에서 사용하게 될 겁니다.

이 줄은 :로 끝났고 그 아래서 부터는 들여쓰기를 해서 이 함수의 영역을 나타냅니다.

이 함수는 OpenAI 의 Completion.create() API 를 사용하기 위해 만드는 겁니다.

 

우선 Completion.create()에 대해 알아야 합니다.

 

이것은 제 블로그의 Open AI > API REFERENCE > Completions - openai.Completion.create() 를 보시면 자세한 사항을 볼 수 있습니다.

 

https://coronasdk.tistory.com/1234

 

Completions - openai.Completion.create()

https://beta.openai.com/docs/api-reference/completions Completions Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position. 프롬프트가 주어지면 모델은

coronasdk.tistory.com

 

 

여기서 제일 중요한 파라미터는 prompt 입니다.

내가 OpenAI 에 질문할 내용이죠.

11번째 줄은 이 prompt 변수는 ASCII 형식으로 인코딩을 한 다음에 다시 디코딩을 한다는 내용입니다.

사실 이 부분이 없어도 이 스크립트는 에러 없이 실행 됩니다. ASCII 형식으로 한다는 것을 확실하게 하기 위해 이 부분을 넣었습니다.

 

두번째로 중요한 부분은 model 입니다.

내가 OpenAI의 어떤 모델을 사용할 것인가를 API에 알려 주는 것이죠.

 

모델들에 대해 알고 싶다면 제 블로그의 Open AI > GET STARTED > Get Started - Models를 참고하세요.

 

https://coronasdk.tistory.com/1212

 

Get Started - Models

https://beta.openai.com/docs/models/overview OpenAI API An API for accessing new AI models developed by OpenAI beta.openai.com Models Overview The OpenAI API is powered by a family of models with different capabilities and price points. You can also custom

coronasdk.tistory.com

 

 

이 예제에서는 text-davinci-003 이란 모델을 사용하겠다고 API에게 전달하고 있습니다.다음에는 테스트용으로는 text-Ada-001을 사용해야 겠습니다. 비용이 가장 저렴한 것 같네요.

 

이 저렴한 모델을 사용했더니 대답이 이렇게 나오네요.The two Koreas will be unified under a single government and president by 2020.

 

2020년 까지 통일이 된다네요.

 

이 모델로 하면 내용은 신뢰할 수 없을 것 같습니다. 그냥 API 테스트 용으로만 사용해야 될 것 같네요.

 

그 외의 파라미터 들은 https://coronasdk.tistory.com/1234 를 참조하세요.

 

이 함수는 openai.Completion.create()을 사용하기 위한 함수라고 했습니다.

그렇긴 때문에 가장 중요한 부분은 12번째 줄부터 있는 response 변수 부분입니다.

이 변수에는 openai.Completion.create() 이 들어가고 각각의 파라미터들이 세팅 돼 있습니다.

이렇게 되면 response라는 변수에 Open AI 의 GPT 3가 질문에 대답한 내용이 담기게 됩니다.

질문은 prompt에 있었구요.

21번째 줄에서는 이 응답 내용 앞과 뒤에 공백이 있다면 그 공백을 없애기 위해 strip()을 사용해서 그 결과를 text 에 담았습니다.

이 strip() 함수는 파이썬 함수입니다.

Python 튜토리얼을 참조하세요.

https://www.w3schools.com/python/ref_string_strip.asp

 

Python String strip() Method

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

22번째 줄에서는 이 text를 리턴 합니다.

 

여기까지가 gpt3_completion() 함수의 내용입니다.

요약하면 이 함수는 openai.Completion.create() API를 이용해서 Open AI에 질문을 하고 응답을 받은 후 그 내용을 반환하는 함수입니다.

 

가장 핵심적인 부분이죠.

 

여기까지가 함수 들이었구요. 이제 실질적으로 실행되는 부분이 24번째 줄에 있습니다.

 

일단 __name__ 이라는 변수가 나오는데 이 변수는 파이썬에 내장 돼 있는 변수입니다.

여기에는 일단 이 파이썬 파일의 이름 (모듈 이름)이 담기게 됩니다.

만약 다른 파이썬 파일을 실행 시키는데 그 파일에서 현재의 파일을 import 해서 사용하는 경우에 __name__ 변수에 현재의 파이썬 파일 이름 (모듈 이름) 이 담기게 됩니다.

하지만 이 파일 안에서 이 함수를 실행시키면 __name__ 변수에는 파일 이름이 아니라 __main__이라는 값이 들어가게 됩니다.

 

그러므로 if 문은 이 파일이 외부에서 import 된 것이 아니라 이 파일 자체가 실행이 돼었다면 이라는 뜻입니다.

자세한 내용은 이 글을 참조하세요.

 

https://lovelydiary.tistory.com/297

 

파이썬) __name__ 변수는 뭐지? (+if __name__=="__main__"의 의미..)

#1. 변수를 정의할 때 꼭 필요한 문장? 함수를 정의하는 것과 관련하여 파이썬 강의를 듣는 중이었다. 함수의 기능을 열심히 정의를 하고 나서 선생님이 꼭 마지막에 희한한 무언가를 붙이셨다.

lovelydiary.tistory.com

그러므로 이 파이썬을 실행하게 되면 25~27번째 줄이 실행 됩니다.

 

prompt 는 질문이 들어가게 됩니다.

이 소스코드에서는 When will South Korea and North Korea be unified?: <- 이렇게 질문 했습니다.

 

그 다음에는 response 변수에 gpt3_completion() 함수에서 반환 된 값을 저장하게 됩니다.

그리고 마지막 줄인 27번째 줄에서는 이 response 에 담겨 있는 답변을 print 하게 됩니다.

 

이 파일을 실행하면 같은 모델이라도 매번 다른 답변이 나옵니다.

여러 모델 별로도 답변의 질이 다르구요.

 

아래는 가장 저렴한 text-ada-001을 사용했을 때 답변 중 하나입니다.

 

여기에서는 북한의 리더인 F Mkotsoalae 가 살해 되면 통일 될 것이라고 나오네요.

 

북한의 리더 이름도 틀렸고 내용도 좀 허접합니다.

 

가장 좋은 모델인 text-davinci-003 을 사용해 보겠습니다.

 

통일이 될지 안 될지 그리고 된다면 언제쯤 될지 예측하는 것은 불가능 하다네요. 2차대전 이후로 갈라 졌고 협상이 이어지고 있지만 통일에 대한 타임라인은 없다는게 이 모델의 응답입니다.

 

이것은 text-davinci-003 모델이 답한 겁니다.

 

요즘 OpenAI 에서 ChatGPT라는 좀 더 진보된 인공지능 모델을 선보여서 화제입니다.

이 모델은 아직 API 가 제공되지 않고 있습니다.

조만간 제공하겠다는 안내문은 있습니다.

 

CharGPT 웹사이트로 가서 질문해 보니 아래와 같은 답변을 얻을 수 있었습니다.

 

 

text-davinci-003과 거의 유사한 답변을 얻을 수 있었습니다.

답변이 조금 더 세련 된 것 같기도 하고......

 

하여간 지금까지 OpenAI API 테스트를 위해 만든 소스코드를 해석해 봤습니다.

 

반응형


반응형

1. Imported Libraries

pandas : https://en.wikipedia.org/wiki/Pandas_(software)

 

pandas (software) - Wikipedia

Python programming library for data manipulation and analysis In computer programming, pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for

en.wikipedia.org

In computer programming, pandas is a software library written for the Python programming language for data manipulation and analysis. In particular, it offers data structures and operations for manipulating numerical tables and time series. It is free software released under the three-clause BSD license.[2] The name is derived from the term "panel data", an econometrics term for data sets that include observations over multiple time periods for the same individuals

 

https://pandas.pydata.org/

 

Python Data Analysis Library — pandas: Python Data Analysis Library

Python Data Analysis Library pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language. pandas is a NumFOCUS sponsored project. This will help ensure t

pandas.pydata.org

 

numpy : https://en.wikipedia.org/wiki/NumPy

 

NumPy - Wikipedia

From Wikipedia, the free encyclopedia Jump to navigation Jump to search Numerical programming library for the Python programming language NumPy (pronounced (NUM-py) or sometimes [2][3] (NUM-pee)) is a library for the Python programming language, adding sup

en.wikipedia.org

NumPy (pronounced /ˈnʌmp/ (NUM-py) or sometimes /ˈnʌmpi/[2][3] (NUM-pee)) is a library for the Python programming language, adding support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. The ancestor of NumPy, Numeric, was originally created by Jim Hugunin with contributions from several other developers. In 2005, Travis Oliphant created NumPy by incorporating features of the competing Numarray into Numeric, with extensive modifications. NumPy is open-source software and has many contributors.

 

https://www.numpy.org/

 

NumPy — NumPy

NumPy NumPy is the fundamental package for scientific computing with Python. It contains among other things: a powerful N-dimensional array object sophisticated (broadcasting) functions tools for integrating C/C++ and Fortran code useful linear algebra, Fo

www.numpy.org

NumPy is the fundamental package for scientific computing with Python. It contains among other things:

  • a powerful N-dimensional array object
  • sophisticated (broadcasting) functions
  • tools for integrating C/C++ and Fortran code
  • useful linear algebra, Fourier transform, and random number capabilities

Besides its obvious scientific uses, NumPy can also be used as an efficient multi-dimensional container of generic data. Arbitrary data-types can be defined. This allows NumPy to seamlessly and speedily integrate with a wide variety of databases.

NumPy is licensed under the BSD license, enabling reuse with few restrictions.

 

boto3 : Interacting for S3   https://boto3.amazonaws.com/v1/documentation/api/latest/index.html

 

Boto 3 Documentation — Boto 3 Docs 1.9.148 documentation

 

boto3.amazonaws.com

Boto is the Amazon Web Services (AWS) SDK for Python. It enables Python developers to create, configure, and manage AWS services, such as EC2 and S3. Boto provides an easy to use, object-oriented API, as well as low-level access to AWS services.

 

sagemaker.amazon.common

 

2. https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.seed.html

 

numpy.random.seed — NumPy v1.16 Manual

Parameters: seed : int or 1-d array_like, optional Seed for RandomState. Must be convertible to 32 bit unsigned integers.

docs.scipy.org

numpy.random.seed(seed=None)

Seed the generator.

This method is called when RandomState is initialized. It can be called again to re-seed the generator. For details, see RandomState.

Parameters:

seed : int or 1-d array_like, optional

Seed for RandomState. Must be convertible to 32 bit unsigned integers.

See also

RandomState

 

3. numpy.random.random_sample(size=None) : https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.random_sample.html?highlight=random%20random_sample#numpy.random.random_sample

 

numpy.random.random_sample — NumPy v1.16 Manual

Parameters: size : int or tuple of ints, optional Output shape. If the given shape is, e.g., (m, n, k), then m * n * k samples are drawn. Default is None, in which case a single value is returned.

docs.scipy.org

numpy.random.randint : https://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randint.html

 

numpy.random.randint — NumPy v1.16 Manual

Parameters: low : int Lowest (signed) integer to be drawn from the distribution (unless high=None, in which case this parameter is one above the highest such integer). high : int, optional If provided, one above the largest (signed) integer to be drawn fro

docs.scipy.org

4. 

5. df : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.html

 

pandas.DataFrame — pandas 0.24.2 documentation

Parameters: data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame Dict can contain Series, arrays, constants, or list-like objects Changed in version 0.23.0: If data is a dict, argument order is maintained for Python 3.6 and later. index

pandas.pydata.org

 

 

 

6. df - Print values

7. 파일로 저장 pandas.DataFrame.to_csv : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

 

pandas.DataFrame.to_csv — pandas 0.24.2 documentation

Parameters: path_or_buf : str or file handle, default None File path or object, if None is provided the result is returned as a string. If a file object is passed it should be opened with newline=’‘, disabling universal newlines. Changed in version 0.24.0:

pandas.pydata.org

8. 함수 : 3개의 파라미터를 받음 - 파일을 S3에 저장하는 함수

9. 함수 : boto3를 사용해서 해당 파일을 S3 버킷으로부터 다운 받음

boto3.Session().resource('s3') : https://boto3.amazonaws.com/v1/documentation/api/latest/guide/session.html

 

Session — Boto 3 Docs 1.9.148 documentation

Session A session manages state about a particular configuration. By default a session is created for you when needed. However it is possible and recommended to maintain your own session(s) in some scenarios. Sessions typically store: Credentials Region Ot

boto3.amazonaws.com

10. 8번 함수를 실행시켜 해당 파일을 S3에 저장

upload_fileobj : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html?highlight=upload_fileobj#S3.Bucket.upload_fileobj

 

S3 — Boto 3 Docs 1.9.148 documentation

The response of this operation contains an EventStream member. When iterated the EventStream will yield events based on the structure below, where only one of the top level keys will be present for any given event. Response Syntax { 'Payload': EventStream(

boto3.amazonaws.com

11. 9번 함수를 실행시켜 해당 파일을 S3로부터 다운 받음

Bucket object download_fileobj : https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html?highlight=download_fileobj#S3.Bucket.download_fileobj

 

S3 — Boto 3 Docs 1.9.148 documentation

The response of this operation contains an EventStream member. When iterated the EventStream will yield events based on the structure below, where only one of the top level keys will be present for any given event. Response Syntax { 'Payload': EventStream(

boto3.amazonaws.com

12. 

13. 처음 시작 5개 데이터를 출력함

df.head() : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.head.html

 

pandas.DataFrame.head — pandas 0.24.2 documentation

Return the first n rows. This function returns the first n rows for the object based on position. It is useful for quickly testing if your object has the right type of data in it. Parameters: n : int, default 5 Number of rows to select. Returns: obj_head :

pandas.pydata.org

14. 해당 컬럼들을 매트릭스에 담음 ??? 

pandas.DataFrame.as_matrix : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.as_matrix.html?highlight=as_matrix#pandas.DataFrame.as_matrix

 

pandas.DataFrame.as_matrix — pandas 0.24.2 documentation

Parameters: columns : list, optional, default:None If None, return all columns, otherwise, returns specified columns.

pandas.pydata.org

15. X 값들

16. ???

17. y 컬럼을 매트릭스에 담음

 

18. y 값 형태. 10줄에 1개 컬럼

19. y 값

20. y 값을 한줄에 표시함

numpy.ravel : https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html

 

numpy.ravel — NumPy v1.16 Manual

Parameters: a : array_like Input array. The elements in a are read in the order specified by order, and packed as a 1-D array. order : {‘C’,’F’, ‘A’, ‘K’}, optional The elements of a are read using this index order. ‘C’ means to index the elements in row-m

docs.scipy.org

21. y 값

23. 함수 : 전달받은 파일을 ????

write_numpy_to_dense_tensor : https://github.com/aws/sagemaker-python-sdk/blob/master/src/sagemaker/amazon/common.py

 

aws/sagemaker-python-sdk

A library for training and deploying machine learning models on Amazon SageMaker - aws/sagemaker-python-sdk

github.com

read_records

24. 함수 : 해당 파일을 ?????

25. write_recordio_file 함수를 실행 함

 

 

26. 첫 3 줄만 출력

27. read_recordio_file 함수 실행

32. 해당 파일을 S3에 저장함

33. 해당 파일을 S3에서 다운 받음

 

반응형
이전 1 다음