Skip to content

Twitter Sentiment Analysis With Neural Networks #7

@tmfdk333

Description

@tmfdk333

Twitter Sentiment Analysis With Neural Networks

DECEMBER 20, 2016

Machine Learning, AI, and other related fields have recently been surrounded by a lot of hype. Although I'm not necessarily extremely drawn to these fields this winter quarter ended up being a perfect opportunity to at least dip my feet into them. I took two classes "Data & Knowledge Bases" and "Computer Networking" which ended up being perfect platforms to do some ML studies.

최근 기계학습, AI 등 관련 분야가 대대적으로 유행되고 있다. 나는 이 분야에 극단적으로 끌리는 것은 아니었지만, 이번 겨울은 이 분야에 발을 담그는 완벽한 기회가 되었다. 나는 "Data & Knowledge Bases"와 "Computer Networking" 두 개의 수업을 들었는데, 이 수업은 결국 몇몇 ML 연구를 위한 완벽한 기반이 되었다.

I ventured into the world of ML with two projects that aimed to use Neural Networks to solve two different problems: "Twitter Sentiment Analysis" (presented on this post) and "Spam Analysis within SoundCloud" (presented on an upcoming post).

나는 Neural Networks를 사용한 서로 다른 문제인 Twitter Sentiment Analysis(현재 포스트)와 Spam Analysis within SoundCloud(다음 포스트) 두 가지 프로젝트를 가지고 ML의 세계로 뛰어들었다.

1. The "Motivation": Twitter Sentiment Analysis

While the main motivation behind this project was to learn, understand, and ultimately hand code a Neural Networks, we decided to frame all of our efforts to do Twitter sentiment analysis. In other words, we were attempting to use our NN to distinguish whether any given tweet is of positive (happy, funny, etc.) or negative (angry, sad, etc.) sentiment.

이 프로젝트의 주된 목적은 신경망을 배우고 이해하고 궁극적으로 코드를 작성하는 것이었지만, Twitter 감정 분석에 더 노력하기로 결정했다. 즉, NN을 사용하여 주어진 트윗이 긍정적(행복, 재미 등)인지, 부정적인(분노, 슬픔 등)인지 등을 구별하려고 했다.

2. The Dataset

Our dataset consisted of a huge list of roughly 1.5M tweets that had been labeled as good or bad sentiment. The dataset contained tweets labeled by the University of Michigan and Niek Sanders. Our dataset can be found here. Notice than when training and testing we simply sampled random subsets of this dataset.

데이터셋은 좋음과 나쁨이라는 감정 꼬리표가 붙은 약 1.5만 트윗의 큰 목록으로 구성되었다. 데이터셋에는 University of MichiganNiek Sanders가 라벨을 붙인 트윗이 들어있었다. 데이터셋은 여기에서 찾을 수 있다. 우리가 training과 testing을 할 때 이 데이터셋의 하위 집합을 간단한 방법으로 랜덤 샘플링하여 사용했단 것을 주의해야 한다.

3. The Intuition behind Neural Networks

The truth is that to best understand the inner workings of Neural Networks I would suggest checking out Nielsen's or Trask's work, because they do a fantastic job at presenting the subject. Alternatively, you can take a look at our work were we condensed all of these ideas there. However, I wanted to attempt to convey a simple understanding of how these NNs work.

사실, NN의 내부 동작을 가장 잘 이해하기 위해 NielsenTrask의 작업을 확인해 볼 것을 제안하고 싶다. 그들은 NN의 내부 동작에 대한 주제를 표현하는 데 환상적인 글을 작성했기 때문이다. 그 대신 당신은 Nielsen과 Trask의 아이디어들을 고려한 우리의 작업을 볼 수 있다. 나는 NN의 동작 방법에 대한 간단한 이해를 전달하고 싶었다.

An NN is essentially trying to emulate a brain. The NN will have a set of nodes (neurons) connected between each other (these connections are equivalent to synapses). The most basic NNs, called Feed-Forward NNs, have an input layer (of nodes), an output layer, and in the middle a variable number of "hidden layers". Each layer consists of a number of nodes that are fully connected to both the layers before and after them. These NNs have two possible operations: Forward Propagation and Backpropagation.

NN는 근본적으로 뇌를 모방하려고 한다. NN에는 노드의 집합(뉴런들)이 서로 연결되어 있다(이 연결은 시냅스와 같다). Feed-Forward NNs라고 불리는 가장 기본적인 NN은 input layer(노드의 input layer), output layer, 그리고 중간에는 variable number의 hidden layers를 가지고 있다. 각 layer는 자신의 이전/이후 두 계층 모두에 완전히 연결(fully connected)되는 다수의 노드로 구성된다. 이러한 NN에는 Forward Propagation과 Backpropagation 두 가지 작업이 있다.

  • Neural Network Structure

3-1) Forward Propagation

Forward Propagation is a method used to calculate the value of a node
given all the previous nodes connected to it. If we focus on the picture above, The value of the 2a node is dictated by the values of 1a, 1b, 1c. Now notice that each connection will have its own weight (this is equivalent to how close the neurons are in a brain; the closer, the easier it is for a neuron to activate the other. the further, the harder it will be.)

Forward Propagation은 연결된 이전 모든 노드들의 값으로 현재 노드의 값을 계산하는 방법이다. 위의 그림을 보면2a 노드의 값은 1a, 1b, 1c의 값에 의해 결정된다. 이제 각각의 연결이 자체 weight를 갖게 되는 것을 알 수 있다. (이것은 뇌에서 뉴런들이 얼마나 가까이에 있는지 알 수 있다. 가까울수록 뉴런이 다른 뉴런을 활성화시키기 쉬울 것이고, 멀수록 뉴런이 다른 뉴런을 활성화시키기 어려울 것이다.)

Furthermore within the node 2a there is an activation function which essentially normalizes it's own value to something between 0 and 1 (although different activation functions can be used for different purposes.)

또한 노드 2a에는 근본적으로 자신의 값을 0과 1 사이의 어떤 것으로 normalize하는 activation function(활성화 함수)이 있다. (비록 다른 activation function을 다른 목적으로 사용할 수 있다.)

So the final result is that value of 2a = activation(w1(value of 1a) + w2(value of 2a) + w3(value of 1c)).

따라서 결론적으로 2a의 값 = activation_function(w1(1a의 값) + w2(1b의 값) + w3(1c의 값)) 이다.

If one keeps doing this for all nodes, one can calculate the output of any given input. This is needed for both the training and testing phase, except that in the training phase a forward propagation is immediately followed by a backpropagation.

모든 노드에 대해 계속 이 작업을 수행하면 주어진 input의 ouput을 계산할 수 있다. 이는 training/testing 단계 모두에서 필요하다. 단, training 단계에서는 forward propagation 다음에 즉시 backpropagation이 뒤따르는 점을 제외한다.

3-2) Backpropagation

Backpropagation is a method used only during the training phase. After running the forward propagation on an NN, we calculate the error obtained between our output and our expected output and we use backpropagation to fix (or diminish) that error. Backpropagation essentially allows neurons to re-adjust their weights in such a way that given a specific input, the proper output will be returned. the exact mathematics of this are a bit convoluted so I'd rather point you to our paper to further understand the maths.

Backpropagation은 training 단계에서만 사용하는 방법이다. NN에서 forward propagation을 실행한 후에 원래의 output과 예상된 output 사이에서 얻어진 오류를 계산하고, 오류를 수정(또는 감소)하기 위해 backpropagation을 사용한다. Backpropagation은 기본적으로 뉴런이 특정 input을 받으면 적절한 output이 반환되는 방식으로 weight를 다시 조정할 수 있게 한다. Backpropagation의 정확한 수학은 조금 복잡하기 때문에 수학적으로 더욱 깊이 이해하기 위해서는 아래의 논문을 참조한다.

4. Representing Tweets

As you may have already noticed our NN accepts only numbers as inputs. Thus, we needed to find a way to represent tweets as numbers without loosing too much information. We knew that doing something simple as hashing each word wouldn't work because you loose the relation and even meaning of words. For example; Imagine HATE = 1001 and LOVE = 1000; The two words are way to similar and the NN will activate equally for both. So instead, we started tinkering around and tried 3 different methods.

이미 알고 있었겠지만 NN은 숫자만 input으로 받아들인다. 따라서, 너무 많은 정보를 잃지 않고 트윗을 숫자로 나타낼 수 있는 방법을 찾아야 했다. 단어의 의미와 관계를 잃어버릴 것이기 때문에 각 단어를 해싱하는 것과 같은 간단한 작업은 효과가 없을 것이라는 것을 알고 있었다. 예를들면 HATE=1001, LOVE=1000이라고 상상해보자. 두 단어는 비슷한 방법이고, NN은 둘 다 동일하게 활성화될 것이다. 그래서 대신 우리는 3가지 다른 방법을 시도했다.

4-1) Bayesian Probabilities

Our first very naive approach was very similar to applying Naive Bayes Classifier. We calculated the probabilities that each word in the dataset was good or bad and then fed that as the input to our Neural Network.

첫 번째로 시도한 순진한 접근 방법은 Naive Bayes Classifier를 적용하는 것과 매우 유사했다. 우리는 데이터셋에서 각 단어가 좋거나 나쁘다는 확률을 계산한 다음 이 확률을 Neural Network의 input으로 제공했다.

  • Bayesian Probabilities Representation

This provided results of around 63%, which were good, but not great. Furthermore, we found that it performed nearly identically to a Bayesian Classifier, which meant we were simply going a really complicated way to achieve the same results. Thus, although it was an interesting starting point, it was a rather poor tweet representation.

이것은 약 63%의 결과를 제공했는데, 이것은 좋긴 했지만 훌륭하지는 않았다. 게다가 Bayesian Classifier와 거의 동일하게 동작한다는 것을 알았다. 이 말은 결국 같은 결과를 얻기 위해서 매우 복잡한 길을 가고 있다는 것을 의미한다. 따라서 흥미로운 시작점이긴 했지만, 매우 형편없는 tweet representation이었다.

4-2) Word Embeddings

We heard lots of cool things about word embeddings and decided to try them out. Word Embeddings are a rather new method of describing words in a dictionary by mapping them into n-dimensional fields. The actual methodology varies depending on the authors (see wiki). In our case we used Keras' built in Word Embedding layers to build our own.

우리는 word embeddings에 대해 좋은 것들을 많이 듣고 그것들을 시도하기로 결정했다. Word Embeddings는 사전에서 단어를 n차원 영역에 매핑하여 설명하는 다소 새로운 방법이다. 실제 방법론은 저자에 따라 다양하다(wiki 참조). 우리의 경우, 우리의 것을 만들기 위해서 Keras' built in Word Embedding layers를 사용했다.

  • Word Embeddings

Although we originally thought this was going to give us fantastic results, we actually obtained poorer accuracy than with plain and simple Bayesian Probabilities. We realized that this happened because Tweets are very unique literal constructs where people use lots of uncommon things such as mentions (@Someone), hashtags (#topic), and urls. Furthermore, typos and irregular abbreviations or lack of whitespace due to length constraints, made our word embeddings inaccurate.

이것이 환상적인 결과를 가져다 줄 것이라고 생각했지만, 평범하고 간단한 Bayesian 확률보다 더 낮은 정확도를 얻었다. 우리는 twitter에서 사림들이 멘션(@Someone), 해시태그(#topic), url 과 같은 독특한 문자를 많이 사용하는 구조이기 때문에 이런 일이 일어났다는 것을 깨달았다. 또한 오타, 불규칙한 약어, 길이 제한으로 인해 공백이 없어 word embedding이 부정확했다.

4-3) Feature Vector

After our "failure" with Word Embedding, we decided to go back to the drawing board. We asked ourselves: What makes a tweet a tweet? After long philosophical contemplation, we came up with a set of features that we believed described each tweet as best as possible. We came up with a long list of features that tried to capture as much information as possible. Of course, we knew that some of these features were not as useful as others and thus, we filtered the useful ones using Correlation-Based Feature Subset Selection in WEKA. This allowed us to select only the most descriptive (and non-redundant) features from our list.

Word Embedding의 실패 후, 처음부터 다시 시작하기로 결정했다. 무엇이 tweet을 tweet으로 만들까? 스스로 질문했다. 오랜 차분한 고민 끝에 우리는 각 tweet을 가능한 한 잘 표현한다고 생각되는 일련의 feature(특징)들을 찾아냈다. 가능한 한 많은 정보를 수집하기 위해서 많은 feature 리스트를 작성했다.
물론 이러한 특징들 중 일부가 다른 feature보다 유용하지 않다는 것을 알았고, WEKA에서 Correlation-Based Feature Subset Selection(연관성 기반 feature 하위집합 선택)을 사용하여 유용한 feature들을 필터링했다.

  • Our feature list for tweet representation

This actually provided the best results, and we were actually able to reach near 70% accuracy. We considered this to be successful seeing how it would have landed us in the top 30 of the Kaggle Michigan University Twitter Sentiment Analysis Challenge.

이것은 실제로 최고의 결과를 제공했고, 우리는 거의 70%의 정확도에 도달할 수 있었다. 이것이 우리가 어떻게 Kaggle Michigan University Twitter Sentiment Analysis Challenge에서 상위 30위에 들 수 있었는지 볼 수 있는 성공적인 방법이라고 생각했다.

5. Our Results

On our experiments, we trained and tested our NN vs. an NN built using Python's Keras Library (a very popular ML library). Furthermore, we ran tests to fine tune the parameters for each NN to run at top performance. For a further interesting discussion of how each parameter affected the NNs Performance, please check out the paper below.

이 실험에서 Python Keras Library(매우 유명한 ML 라이브러리)에 내장된 NN과 우리의 NN을 training 하고 testing 했다. 또한 각 NN이 최고의 성능으로 실행될 수 있도록 parameter를 fine tune하는 테스트를 실행했다. 각 parameter가 NNs의 성능에 어떻게 영향을 미쳤는지에 대한 자세한 내용은 아래의 논문을 참조하면 된다.

We found our NN to be comparable to the Keras NN, as ours was right on the heels of Keras. Here are the full results for further comparison:

우리의 NN이 Keras의 NN의 바로 뒤에 있었기 때문에 우리의 NN과 Keras의 NN이 비슷하다는 것을 알았다. 추가 비교를 위한 전체 결과는 아래와 같다.

6. The Paper & Code

Feel free to download/bookmark the paper at Academia.com and get involved with our git repo: https://github.com/pmsosa/CS273-Project.

Academia.com에서 논문을 다운로드/북마크하고 git repo: https://github.com/pmsosa/CS273-Project에 참여해라.

Metadata

Metadata

Assignees

Labels

ML/DLMachine Learning / Deep Learning

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions