FIFA_Online_4_Player_Evalution_Analysis (4)

2022. 5. 24. 14:31Project/FIFA Online 4 댓글 감정분석

728x90
반응형

https://github.com/JooJaeHwan/FIFA_Online_4_Player_Evalution_Analysis

 

GitHub - JooJaeHwan/FIFA_Online_4_Player_Evalution_Analysis

Contribute to JooJaeHwan/FIFA_Online_4_Player_Evalution_Analysis development by creating an account on GitHub.

github.com


데이터 모델링

필요 라이브러리 설치

!pip install konlpy
!sudo apt-get install -y fonts-nanum
!sudo fc-cache -fv
!rm ~/.cache/matplotlib -rf

데이터 전처리

from konlpy.tag import Okt
import os
import json
import pandas as pd
import tensorflow as tf
import numpy as np
okt = Okt()

Konlpy를 이용한 형태소 분리 

def tokenize(doc):
    # norm은 정규화, stem은 근어로 표시하기를 나타냄
    return ['/'.join(t) for t in okt.pos(doc, norm=True, stem=True)]

시드를 맞추기

np.random.seed(42)
tf.random.set_seed(42)

데이터확인

df = pd.read_csv("/content/drive/MyDrive/Colab Notebooks/Section4/project/ICON_Reviews.csv", index_col=0)
df.head()
name class_id rate reviews label
데이비드 시먼 101 2.32 ㅋㅋㅋㅋ이2새2끼 한 10판동안 존2나 어이없게 먹혀서 팔려고 잠금해제했더니 승격까... 1
데이비드 시먼 101 2.32 아 장점하나 더 있다. 멀던가능 하프라인까지 던져짐. 훈련코치 먹이면 더 멀리도 가능할듯 1
데이비드 시먼 101 2.32 잉국 친선용 콘시먼 후기하... 이형 꽁지머리 간지 유일한 잉글국대 레전드 키퍼로 ... 0
데이비드 시먼 101 2.32 개 병신새끼 쳐막는걸 못봤어 위치선정도 안돼 중거리슛 못막아 커브볼 못막아 땅볼볼 ... 0
데이비드 시먼 101 2.32 내가 고급여 키퍼를 딱 둘써봄 주공반데사르랑 콘시먼 둘의 특징 딱 한줄로 쓰자면주공... 0

rate는 사람들이 임의로 막 정한 별점이라서 감정분석에 크게 영향을 주지않는다고 판단하고 제거

df.drop(["rate"], axis=1, inplace=True)
df.loc[df["label"] == -1, "label"] = 2
df.head()
name class_id reviews label
데이비드 시먼 101 ㅋㅋㅋㅋ이2새2끼 한 10판동안 존2나 어이없게 먹혀서 팔려고 잠금해제했더니 승격까... 1
데이비드 시먼 101 아 장점하나 더 있다. 멀던가능 하프라인까지 던져짐. 훈련코치 먹이면 더 멀리도 가능할듯 1
데이비드 시먼 101 잉국 친선용 콘시먼 후기하... 이형 꽁지머리 간지 유일한 잉글국대 레전드 키퍼로 ... 0
데이비드 시먼 101 개 병신새끼 쳐막는걸 못봤어 위치선정도 안돼 중거리슛 못막아 커브볼 못막아 땅볼볼 ... 0
데이비드 시먼 101 내가 고급여 키퍼를 딱 둘써봄 주공반데사르랑 콘시먼 둘의 특징 딱 한줄로 쓰자면주공... 0

데이터셋 분류

from sklearn.model_selection import train_test_split

train, test = train_test_split(df, test_size = .2, random_state=42)

토큰화 진행

if os.path.isfile('train_docs.json'):
    with open('train_docs.json') as f:
        train_docs = json.load(f)
    with open('test_docs.json') as f:
        test_docs = json.load(f)
else:
    train_docs = [(tokenize(train.iloc[i][2]), int(train.iloc[i][3])) for i in range(len(train))]
    test_docs = [(tokenize(test.iloc[i][2]), int(test.iloc[i][3])) for i in range(len(test))]
    # JSON 파일로 저장
    with open('train_docs.json', 'w', encoding="utf-8") as make_file:
        json.dump(train_docs, make_file, ensure_ascii=False, indent="\t")
    with open('test_docs.json', 'w', encoding="utf-8") as make_file:
        json.dump(test_docs, make_file, ensure_ascii=False, indent="\t")
tokens = [t for d in train_docs for t in d[0]]

NLTK를 이용한 모델링

import nltk
text = nltk.Text(tokens, name='NMSC')
text.vocab().most_common(10)

'''
[('./Punctuation', 6070),
 ('하다/Verb', 5825),
 ('좋다/Adjective', 4640),
 ('이/Josa', 4345),
 ('가/Josa', 4309),
 ('에/Josa', 3955),
 ('은/Josa', 3216),
 ('는/Josa', 3077),
 ('쓰다/Verb', 2934),
 ('도/Josa', 2830)]
'''

자주 나오는 단어 시각화

import matplotlib.pyplot as plt
%matplotlib inline
plt.rc('font', family='NanumBarunGothic') 
plt.figure(figsize=(20,10))
text.plot(50)

가장 많이 쓰이는 10000개의 단어들 사용

selected_words = [f[0] for f in text.vocab().most_common(10000)]

def term_frequency(doc):
    return [doc.count(word) for word in selected_words]

X_train = [term_frequency(d) for d, _ in train_docs]
X_test = [term_frequency(d) for d, _ in test_docs]
y_train = [c for _, c in train_docs]
y_test = [c for _, c in test_docs]
import numpy as np

X_train = np.asarray(X_train).astype('float32')
X_test = np.asarray(X_test).astype('float32')

y_train = np.asarray(y_train).astype('float32')
y_test = np.asarray(y_test).astype('float32')

모델 학습

from tensorflow.keras import models
from tensorflow.keras.layers import Dense


model = models.Sequential([
                           Dense(64, activation='relu', input_shape=(10000,)),
                           Dense(64, activation='relu'),
                           Dense(3, activation='softmax')
])

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

model.fit(X_train, y_train, epochs=10, batch_size = 512)

'''
Epoch 1/10
26/26 [==============================] - 2s 44ms/step - loss: 0.9991 - accuracy: 0.5836
Epoch 2/10
26/26 [==============================] - 1s 39ms/step - loss: 0.7705 - accuracy: 0.7214
Epoch 3/10
26/26 [==============================] - 1s 38ms/step - loss: 0.5625 - accuracy: 0.7734
Epoch 4/10
26/26 [==============================] - 1s 45ms/step - loss: 0.4168 - accuracy: 0.8415
Epoch 5/10
26/26 [==============================] - 1s 38ms/step - loss: 0.3095 - accuracy: 0.8920
Epoch 6/10
26/26 [==============================] - 1s 35ms/step - loss: 0.2322 - accuracy: 0.9213
Epoch 7/10
26/26 [==============================] - 1s 36ms/step - loss: 0.1733 - accuracy: 0.9457
Epoch 8/10
26/26 [==============================] - 1s 41ms/step - loss: 0.1318 - accuracy: 0.9623
Epoch 9/10
26/26 [==============================] - 1s 42ms/step - loss: 0.1029 - accuracy: 0.9718
Epoch 10/10
26/26 [==============================] - 1s 42ms/step - loss: 0.0830 - accuracy: 0.9776
'''
results = model.evaluate(X_test, y_test)
results

'''
101/101 [==============================] - 0s 3ms/step - loss: 1.0632 - accuracy: 0.7278
[1.0632328987121582, 0.7278363108634949]
'''

모델 부호화

import pickle

with open('suggestion_model.pkl','wb') as pickle_file:
      pickle.dump(model, pickle_file)
728x90
반응형