ChatGPT를 이용한 아이리스(IRIS) 품종 분류 프로젝트
1. ChatGPT API를 이용해 질문에 답변을 할 수 있는 클래스를 만들어 봅시다.
(모델은 "gpt-3.5-turbo"을 사용)
from openai import OpenAI
class GptAPI():
def __init__(self, model, client):
self.messages = []
self.model = model
self.client = client
def get_message(self, prompt):
self.messages.append({"role": "user", "content": prompt})
stream = self.client.chat.completions.create(
model=self.model,
messages=self.messages,
stream=True,
)
result = ''
for chunk in stream:
if chunk.choices[0].delta.content is not None:
string = chunk.choices[0].delta.content
print(string, end="")
result = ''.join([result, string])
self.messages.append({"role": "system", "content": result})
model = "gpt-3.5-turbo"
client = OpenAI(api_key=api_key)
gpt = GptAPI(model, client)
2. 아래 질문을 GPT에 입력해 보세요.
sklearn.datasets 모듈을 이용해 아이리스(iris) 데이터를 다운받아 봅시다. 다운받은 데이터는 `df`라는 데이터프레임으로 만들어 주세요. 그리고 피처(feature) 이름을 단순하게 변경해 봅시다. 마지막으로 데이터프레임의 데이터를 확인해 봅시다.
text = 'sklearn.datasets 모듈을 이용해 아이리스(iris) 데이터를 다운받아 봅시다. 다운받은 데이터는 `df`라는 데이터프레임으로 만들어 주세요. 그리고 피처(feature) 이름을 단순하게 변경해 봅시다. 마지막으로 데이터프레임의 데이터를 확인해 봅시다.' # 질문을 입력하세요
gpt.get_message(text)
⬇️ 위의 코드 실행 결과 : GPT가 생성한 파이썬 코드⬇️
```python
from sklearn.datasets import load_iris
import pandas as pd
# 아이리스 데이터 다운로드
iris = load_iris()
# 데이터프레임 생성
df = pd.DataFrame(data=iris.data, columns=['sepal_length', 'sepal_width', 'petal_length', 'petal_width'])
# 데이터 확인
print(df.head())
```
⬇️ GPT가 생성한 파이썬 코드 실행 결과⬇️
3. 아래 질문을 GPT에 입력해 보세요.
종속변수와 4개의 독립변수가 어떠한 관계를 가지는지 boxplot(상자 수염 그림) 그래프를 그려 확인해 봅시다.
text = '종속변수와 4개의 독립변수가 어떠한 관계를 가지는지 boxplot(상자 수염 그림) 그래프를 그려 확인해 봅시다.' # 질문을 입력하세요
gpt.get_message(text)
⬇️ 위의 코드 실행 결과 : GPT가 생성한 파이썬 코드⬇️
```python
import matplotlib.pyplot as plt
# 종속변수 추가
df['target'] = iris.target
# boxplot 그리기
plt.figure(figsize=(10, 6))
df.boxplot(by='target', figsize=(15, 10))
plt.show()
```
⬇️ GPT가 생성한 파이썬 코드 실행 결과⬇️
4. 아래 질문을 GPT에 입력해 보세요.
데이터는 8:2 비율로 데이터를 분리 해주세요. random_state는 1로 고정합시다. 마지막으로 독립변수 4개를 사용해 의사결정나무를 학습해 봅시다.
text = '데이터는 8:2 비율로 데이터를 분리 해주세요. random_state는 1로 고정합시다. 마지막으로 독립변수 4개를 사용해 의사결정나무를 학습해 봅시다.' # 질문을 입력하세요
gpt.get_message(text)
⬇️ 위의 코드 실행 결과 : GPT가 생성한 파이썬 코드⬇️
```python
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
# 독립변수와 종속변수 분리
X = df.drop('target', axis=1)
y = df['target']
# 데이터 분리
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)
# 의사결정나무 모델 학습
clf = DecisionTreeClassifier(random_state=1)
clf.fit(X_train, y_train)
# 예측
y_pred = clf.predict(X_test)
# 정확도 출력
print('정확도:', accuracy_score(y_test, y_pred))
```
⬇️ GPT가 생성한 파이썬 코드 실행 결과⬇️
정확도: 0.9666666666666667
5. 아래 질문을 GPT에 입력해 보세요.
피처 임포턴스(Feature Importance)를 확인해 어떠한 독립변수가 모델 학습에 큰 영향을 주었는지 확인해 봅시다.
text = '피처 임포턴스(Feature Importance)를 확인해 어떠한 독립변수가 모델 학습에 큰 영향을 주었는지 확인해 봅시다.' # 질문을 입력하세요
gpt.get_message(text)
⬇️ 위의 코드 실행 결과 : GPT가 생성한 파이썬 코드⬇️
```python
# 피처 임포턴스 확인
feature_importance = pd.DataFrame({'feature': X.columns, 'importance': clf.feature_importances_})
feature_importance = feature_importance.sort_values(by='importance', ascending=False)
print(feature_importance)
```
⬇️ GPT가 생성한 파이썬 코드 실행 결과⬇️
6. 아래 질문을 GPT에 입력해 보세요.
"classification report"를 이용해 예측 모델이 잘 학습되었는지 결과 보고서를 작성해 봅시다.
text = '"classification report"를 이용해 예측 모델이 잘 학습되었는지 결과 보고서를 작성해 봅시다.' # 질문을 입력하세요
gpt.get_message(text)
⬇️ 위의 코드 실행 결과 : GPT가 생성한 파이썬 코드⬇️
```python
from sklearn.metrics import classification_report
# classification report 출력
print(classification_report(y_test, y_pred))
```
⬇️ GPT가 생성한 파이썬 코드 실행 결과⬇️