티스토리 뷰

Mini Project: Using Keras to analyze IMDB Movie Data


 · The dataset

 - 25000개의 IMDB 데이터셋을 이용

 - Movie Data의 각 review에는 label이 붙어있음

 - Negative : 0 / Positive : 1

 - review의 단어를 기반으로 review의 sentiment를 예측하는 모델을 만드는 프로젝트를 진행해보자.

 - 이미 사전에 처리된 input data를 기반으로 네트워크 설계.

 - 각 review의 단어에 해당하는 인덱스로 접근이 가능하다.

 - 단어는 빈도수에 비례하게 정렬되므로, 예를들어 가장 빈도수가 높은 "the"에 인덱스 1이 대응됨

 - 인덱스 0은 알 수 없는 단어에 해당

 - sentence는 이 인덱스와 연결하여 벡터로 바뀜

 - 예를들어 "To be or not to be" 라는 문장은

 - 위와같이 대응됨

 - 따라서 위의 문장은 [5, 8, 21, 3, 5, 8] 이라는 벡터로 인코딩 된다.




 · Loading the data

 - 데이터는 Keras에 미리 로드되어 있으므로, 특정 파일을 open 또는 read할 필요가 없다.

 - 위와같이 데이터셋을 불러들일 수 있다.

 - 위 명령어들에 대한 설명

 - 그중 알고있어야 할 명령어로는

 - num_words : 고려해야할 가장 빈도수가 높은 단어. 

 - 이 인자는 매우 애매한 단어 (ex. Ultracrepidarian)를 거르고 싶을 때 유용하다.

 - skip_top : 무시할 단어 중 가장 상위 단어(인덱스상). 

 - 중복되는 단어 또는 일반적인 단어(most common word)를 거르고 싶을 때 유용하다.

 - 예를들면 "the"라는 단어는 네트워크가 설계될 때 도움을 주는 단어가 아니기 때문에

 - skip_top의 값을 2 이상으로 설정하여 건너 뛸 수 있다.




 · Pre-processing the data

 - 먼저 데이터를 one-hot encoding을 통해 (0, 1)벡터에 다음과 같이 전처리함

 - 만약 우리가 10개의 단어를 가지고있고, 그 벡터가 (4, 1, 8)이라면

 - 우리는 위의 10개의 단어들을 (1, 0, 0, 1, 0 0, 1, 0, 0)으로 변환하여야 한다.




 · Building the model

 - Keras를 이용하여 신경망 네트워크를 설계하고, 학습시키고 평가시킨다.

 - dropout 이나 정규화(regularization)와 같은 방법은 Keras optimizer를 이용하면 된다.

 - accuracy를 85% 이상으로 하는것을 목표로 한다.






1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Analyzing IMDB Data in Keras
# Imports
import numpy as np
import keras
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import matplotlib.pyplot as plt
%matplotlib inline
 
np.random.seed(42)
 
## 1. Loading the data
# This dataset comes preloaded with Keras, 
# so one simple command will get us training and testing data. 
# There is a parameter for how many words we want to look at. 
# We've set it at 1000, but feel free to experiment.
 
# Loading the data (it's preloaded in Keras)
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=1000)
print(x_train.shape)
print(x_test.shape)
 
## 2. Examining the data
# Notice that the data has been already pre-processed, 
# where all the words have numbers, 
# and the reviews come in as a vector with the words that the review contains. 
# For example, if the word 'the' is the first one in our dictionary, 
# and a review contains the word 'the', then there is a 1 in the corresponding vector.
# The output comes as a vector of 1's and 0's, 
# where 1 is a positive sentiment for the review, and 0 is negative.
 
print(x_train[0])
print(y_train[0])
 
## 3. One-hot encoding the output
# Here, we'll turn the input vectors into (0,1)-vectors. 
# For example, if the pre-processed vector contains the number 14, 
# then in the processed vector, the 14th entry will be 1.
 
# One-hot encoding the output into vector mode, each of length 1000
tokenizer = Tokenizer(num_words=1000)
x_train = tokenizer.sequences_to_matrix(x_train, mode='binary')
x_test = tokenizer.sequences_to_matrix(x_test, mode='binary')
print(x_train[0])
 
# And we'll also one-hot encode the output.
# One-hot encoding the output
num_classes = 2
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
print(y_train.shape)
print(y_test.shape)
 
## 4. Building the model architecture
# Build a model here using sequential. 
# Feel free to experiment with different layers and sizes! 
# Also, experiment adding dropout to reduce overfitting.
model = Sequential()
model.add(Dense(512, activation = 'relu', input_dim = 1000))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation = 'softmax'))
model.summary()
# TODO: Compile the model using a loss function and an optimizer.
model.compile(loss = 'categorical_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy'])
 
## 5. Training the model
# Run the model here. Experiment with different batch_size, and number of epochs!
# TODO: Run the model. Feel free to experiment with different batch sizes and number of epochs.
model.fit(x_train, y_train, epochs = 15, batch_size = 100, validation_data = (x_test, y_test), verbose = 2)
 
## 6. Evaluating the model
# This will give you the accuracy of the model, 
# as evaluated on the testing set. Can you get something over 85%?
score = model.evaluate(x_test, y_test, verbose=0)
print("Accuracy: ", score[1])
cs

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함