모듈 불러오기

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

seaborn에서 제공하는 데이터셋 확인

sns.get_dataset_names()

# seaborn load_dataset('data')활용 : 결과 A에 저장
A= - sns.load_dataset('data')

컬럼 값 분포 확인 : value_counts() / 차트 그리기

# data컬럼 값 분포 확인 
a['data'].value_counts()

# plot차트 그리기
a['data'].value_counts().plot(kind='bar')

# box plot
a['data'].plot(kind='box')

# seabor boxplot을 이용해 age 별로 성별 확인 
sns.boxplot(data=a, x='age', y='sex')

# boxplot을 이용하여 class별로 age분포 확인, 또한 s 키로 분류 
sns.boxplot(data='a', x='class', y='age', hue='s')

원핫 인코딩

분포 확인 : df['  '].value_counts()
pd.get_dummies(data='  ',columns=['  ']).head()

X,Y나누기 / Train, Test 데이터셋 나누기

# X분리, 판다스 drop을 활용하여 's' 칼럼을 삭제하고 나머지를 X에 저장
X = test.drop('s', axis=1)

# Y 분리, survived 컬럼값을 y에 저장한다
y = titanic['s']

# Train / Test 데이터셋 나눠주는 함수 : train_test_split

from sklern.model_selection import train_test_split

# Train : Test => 8:2 비율로 나누기 
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state=1)

#Train 과 Test 사이즈 확인 
x_train.shape, x_test.shape, y_train.shape, y_test.shape 


# Train dataset, Test dataset 나누기 : train_test_split 함수 사용
# 입력 : X, y 
# Train : Test 비율 = 7: 3  --> test_size=0.3
# y Class 비율에 맞게 나누기 : stratify=y
# 여러번 수행해도 같은 결과 나오게 고정하기 : random_state=42 
# 결과 : X_train, X_test, y_train, y_test


X_train,X_test,y_train,y_test = train_test_split(X,y,test_size=0.3,stratify=y, random_state=42)

라이브러리 불러오기

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix 
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
from sklearn.metrics import classification_report

Decision Tree

# DecisionTree 머신러닝 모델링 
from sklearn.tree import DecisionTreeClassifier

# 1. DecisionTreeClassifier 모델 정의 -> result에 저장
# 2. dt 모델 학습(fit) : x_train, y_train
# 3. dt 모델 성능확인(score) : x_test, y_test

result = DecisionTreeClassifier()
result.fit(x_train, y_train)
result.score(x_test, y_test)


Random Forest

# RandomForest 머신러닝 모델링 
from sklearn.ensemble import RandomForestClassifier 

# 1. RandomForestClassifier 모델 정의 -> result 저장
# 2. result 모델 학습(fit) : x_train, y_train
# 3. result 모델 성능확인(score) : x_test, y_test
result = RandomForestClassifier()
result.fit(x_train, y_train)
result.score(x_test, y_test)

# result 모델 predict 함수 활용 
# 입력 : 첫번재 데이터 --> [x_test[0]]
# 예측 결과를 result_pred 저장 및 출력

result_pred = result.predict([x_test[0]])
result_pred

딥러닝 모델링

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

# model = Sequential()은 Keras에서 모델을 생성하는 함수 
model = Sequential()
# hidden layer : 10unit, activation = 'relu', input layer : (6, )
model.add(Dense(10,activation = 'relu', input_shape=(6, )))
#  output layer : 2unit, activation='softmax'
model.add(Dense(2, activation = 'softmax'))

# 모델 컴파일 : compile 
# loss = 'sparse_categorical_crossentropy'
# optimizer = 'adam'
# metrics = ['accuracy']

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# 모델 학습 : fit 
# x_train, y_train, epochs=10, batch_size=8
# 학습결과 저장 : history 

history = model.fit(x_train, y_train, epochs=10, batch_size=8)

# epochs 횟수 증가하여 모델 학습 : fit 
# x_train y_train, epochs=30, batch_size=8
# 학습결과 저장 : history
 
history = model.fir(x_train, y_train, epochs=30, batch_size=8)

# Sequential 모델 만들기 --> model 변수 저장
# input layer : (6, )
# hidden layer : 32 unit , activation='relu'
# hidden layer : 16 unit , activation='relu'
# output layer : 2 unit , activation='softmax'

model = Sequential()
model.add(Dense(32, activation='relu', input_shape=(6,)))
model.add(Dense(16, activation='relu'))
model.add(Dense(2, activation='softmax'))

# 모델 컴파일 : compile
# loss='sparse_categorical_crossentropy'
# optimizer='adam'
# metrics=['accuracy']

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# 모델 학습 : fit
# X_train, y_train, epochs=30, batch_size=8
# 학습결과 저장 : history

history = model.fit(X_train, y_train, epochs=30, batch_size=8)
  • 학습이 잘 평가되는지 valid data로 평가를 해보자
# Sequential 모델 만들기 --> model 변수 저장
# input layer : (6, )
# hidden layer : 32 unit , activation='relu'
# hidden layer : 16 unit , activation='relu'
# output layer : 2 unit , activation='softmax'

model = Sequential()
model.add(Dense(32, activation='relu', input_shape=(6,)))
model.add(Dense(16, activation='relu'))
model.add(Dense(2, activation='softmax'))

# 모델 컴파일 : compile
# loss='sparse_categorical_crossentropy'
# optimizer='adam'
# metrics=['accuracy']

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# 모델 학습 : fit
# x_train, y_train, epochs=30, batch_size=8, validation_data=(x_test, y_test)
# 학습결과 저장 : history

# validation_data 옵션을 추가해서 모델 학습에 대한 평가를 할수 있다.
# 즉, 모르는 데이터에 대해 성능평가 잘 나온다면 좋은것이다. 
history = model.fit(x_train, y_train, epochs=30, batch_size=8, validation_data=(x_test, y_test))

0개의 댓글