2222

김도형·2022년 4월 17일
0

배치 추가

"keyword_matching_init.py"

if __name__ == "__main__":
	data_path = "/home/ubuntu/src/script/curation/data"
	...
	...
	file_list = os.listdir(data_path)

위 코드를 통해서 배치 작업을 진행함 "data_path" 아래 위치한 파일 명을 읽어서 이를 바탕으로 배치 작업을 진행

— batch 작업 중 오류가 발생할 경우 보통 data_path에 csv, xlsx 확장자가 아닌 파일이 있을 경우임 → 숨겨진 파일이 있을 수도 있으므로 직접 cmd 라인에서 확인 할 필요가 있음.

주관식 자동채점 적용 현황 리스트

  • 과목 수 : 240, 문항 수 : 2820
  • 정확률 : 99.03 % ( 총 채점 수 : 34161 / 올바르게 채점한 수 : 33832 )
  • 2021-07-14 기준

imply.hunet.co.kr 에 들어가서 SQL 접속 후

subjective_question_verification

테이블을 통해 확인 할수 있음.

-- 올바르게 채점한 수
select count(*) from "subjective_question_verification"
where "__time" >= '2021-07-14'
and correct_answer_rate < 10
and correct_answer_rate > 90

-- 총 채점 수
select count(*) from "subjective_question_verification"
where "__time" >= '2021-07-14'
  • 주의사항 초기 subjective_question_verification 테이블에 들어가던 값들에 대한 기준값이 바뀌었기 때문에 날짜 조건을 걸어서 기존에 책정해 둔것에 값을 더해가는 것이 정확함.

    3. GPT-3 Pricing

처음 GPT-3를 신청하면 Trial(무료 체험 이용 기간) 상태가 되고, 3개월간 30만 토큰을 사용할 수 있게 해 줍니다. 3개월이 지나거나, 그 이전에 30만 토큰을 다 쓴다면 아래와 같은 가격정책에 따라 GPT-3 모델을 사용할 수 있습니다.

1 Token = 영어 4글자 정도로 생각하면 된다고 합니다. 짧은 단어 한개 정도를 의미한다고 보면 편할 것 같습니다.

4. GPT-3 Turorial

이제 기본적으로 GPT-3를 사용할 준비는 모두 마친 상태입니다. 그럼 파이썬에서 GPT-3를 사용하기 위해 라이브러리를 설치하고 사용하는 방법을 알아보도록 하겠습니다.

우선 가상환경에 openai 라이브러리를 설치합니다.

$ conda create --n gpt python=3.7
$ conda activate gpt
(gpt) $ pip install openai

설치까지 완료되었다면 간단한 코드를 통해 바로 테스트를 해볼 수 있습니다.

import openai

openapi.api_key = "SECRET_API_KEY"

prompt = "This is a test"

response = openai.Completion.create(engine="davinci", prompt=prompt, max_tokens=10)

print(response.choices[0].text)

------------------------------------------------------------------------------------
' of whether the programming works correctly.\n\nHere'

5. 예제를 통해 학습시키기

GPT-3는 few-shot learning을 통해 몇 가지 예제를 보여주면 성능이 더욱 좋아지는 모델입니다. 보다 효율적으로 활용하기 위해 GPT class와 Example class를 아래와 같이 생성해 줍니다.

(출처 : https://github.com/shreyashankar/gpt3-sandbox)

"""Creates the Example and GPT classes for a user to interface with the OpenAI
API."""

import openai
import uuid

def set_openai_key(key):
    """Sets OpenAI key."""
    openai.api_key = key

class Example:
    """Stores an input, output pair and formats it to prime the model."""
    def __init__(self, inp, out):
        self.input = inp
        self.output = out
        self.id = uuid.uuid4().hex

    def get_input(self):
        """Returns the input of the example."""
        return self.input

    def get_output(self):
        """Returns the intended output of the example."""
        return self.output

    def get_id(self):
        """Returns the unique ID of the example."""
        return self.id

    def as_dict(self):
        return {
            "input": self.get_input(),
            "output": self.get_output(),
            "id": self.get_id(),
        }

class GPT:
    """The main class for a user to interface with the OpenAI API.

    A user can add examples and set parameters of the API request.
    """
    def __init__(self,
                 engine='davinci',
                 temperature=0.5,
                 max_tokens=100,
                 input_prefix="input: ",
                 input_suffix="\n",
                 output_prefix="output: ",
                 output_suffix="\n\n",
                 append_output_prefix_to_query=False):
        self.examples = {}
        self.engine = engine
        self.temperature = temperature
        self.max_tokens = max_tokens
        self.input_prefix = input_prefix
        self.input_suffix = input_suffix
        self.output_prefix = output_prefix
        self.output_suffix = output_suffix
        self.append_output_prefix_to_query = append_output_prefix_to_query
        self.stop = (output_suffix + input_prefix).strip()

    def add_example(self, ex):
        """Adds an example to the object.

        Example must be an instance of the Example class.
        """
        assert isinstance(ex, Example), "Please create an Example object."
        self.examples[ex.get_id()] = ex

    def delete_example(self, id):
        """Delete example with the specific id."""
        if id in self.examples:
            del self.examples[id]

    def get_example(self, id):
        """Get a single example."""
        return self.examples.get(id, None)

    def get_all_examples(self):
        """Returns all examples as a list of dicts."""
        return {k: v.as_dict() for k, v in self.examples.items()}

    def get_prime_text(self):
        """Formats all examples to prime the model."""
        return "".join(
            [self.format_example(ex) for ex in self.examples.values()])

    def get_engine(self):
        """Returns the engine specified for the API."""
        return self.engine

    def get_temperature(self):
        """Returns the temperature specified for the API."""
        return self.temperature

    def get_max_tokens(self):
        """Returns the max tokens specified for the API."""
        return self.max_tokens

    def craft_query(self, prompt):
        """Creates the query for the API request."""
        q = self.get_prime_text(
        ) + self.input_prefix + prompt + self.input_suffix
        if self.append_output_prefix_to_query:
            q = q + self.output_prefix

        return q

    def submit_request(self, prompt):
        """Calls the OpenAI API with the specified parameters."""
        response = openai.Completion.create(engine=self.get_engine(),
                                            prompt=self.craft_query(prompt),
                                            max_tokens=self.get_max_tokens(),
                                            temperature=self.get_temperature(),
                                            top_p=1,
                                            n=1,
                                            stream=False,
                                            stop=self.stop)
        return response

    def get_top_reply(self, prompt):
        """Obtains the best result as returned by the API."""
        response = self.submit_request(prompt)
        return response['choices'][0]['text']

    def format_example(self, ex):
        """Formats the input, output pair."""
        return self.input_prefix + ex.get_input(
        ) + self.input_suffix + self.output_prefix + ex.get_output(
        ) + self.output_suffix

gpt.py 파일을 만들었다면 이제 예제를 통해 쿼리를 생성하는 gpt-3 모델을 학습해 줍니다.

gpt = GPT(engine="davinci",
					temperature=0.5,
					max_tokens=100)

gpt.add_example(Example('Fetch unique values of DEPARTMENT from Worker table.',
                        'Select distinct DEPARTMENT from Worker;'))

gpt.add_example(Example('Print the first three characters of FIRST_NAME from Worker table.',
                        'Select substring(FIRST_NAME,1,3) from Worker;'))

gpt.add_example(Example('Find the position of the alphabet ("a") in the first name column "Amitabh" from Worker table.',
                        'Select INSTR(FIRST_NAME, BINARY"a") from Worker where FIRST_NAME = "Amitabh";'))

gpt.add_example(Example('Print the FIRST_NAME from Worker table after replacing "a" with "A".',
                        'Select CONCAT(FIRST_NAME, " ", LAST_NAME) AS "COMPLETE_NAME" from Worker;'))

gpt.add_example(Example('Display the second highest salary from the Worker table.',
                        'Select max(Salary) from Worker where Salary not in (Select max(Salary) from Worker);'))

gpt.add_example(Example('Display the highest salary from the Worker table.',
                        'Select max(Salary) from Worker;'))

gpt.add_example(Example('Fetch the count of employees working in the department Admin.',
                        'SELECT COUNT(*) FROM worker WHERE DEPARTMENT = "Admin";'))

gpt.add_example(Example('Get all details of the workers whose SALARY lies between 100000 and 500000.',
                        'Select * from Worker where SALARY between 100000 and 500000;'))

gpt.add_example(Example('Get Salary details of the Workers',
                        'Select Salary from Worker'))

이렇게 몇 가지 질의 - 쿼리 예제를 통해 GPT-3를 학습시킨다음 학습되지 않은 질의를 모델에 날리게되면, 아래와 같이 쿼리를 생성해 줍니다.

profile
Go with the flow

0개의 댓글